Arduino Nano, I2C Slave - PI And More

Ok, so we have built the I2C Master. Now all we need are slaves to talk to.

Again, as with the I2C Master, the code for the I2C Slave is not that difficult. I will share the code first and than talk about it:

#include <Wire.h> #define ANSWERSIZE 3 String answer = "PAM"; void setup() {   Wire.begin(9);   Wire.onRequest(requestEvent); // data request to slave   Wire.onReceive(receiveEvent); // data slave received   Serial.begin(9600);   Serial.println("I2C Slave ready!"); } void receiveEvent(int countToRead) {   while (0 < Wire.available()) {     byte x = Wire.read();   }   Serial.println("Receive event"); } void requestEvent() {   byte response[ANSWERSIZE];   for (byte i=0;i<ANSWERSIZE;i++) {     response[i] = (byte)answer.charAt(i);   }   Wire.write(response,sizeof(response));   Serial.println("Request event"); } void loop() {   delay(50); }

As we did in the I2C Master, we start with including the library Wire with the command #include <Wire.h>. Also in the header I have defined the size and answer that we will send. Of course in your application the answer will probably not be static but this will suffice to show the workings of I2C.

In the setup() function we have Wire.begin(9). Notice the 9 between the brackets which defines the id of the device. When we initialized Wire in the I2C Master, we did not put anything between the brackets.

The next to lines define which functions are called when we receive data, Wire.onRequest(), and when we are requested to send data, Wire.onReceive().

The function receiveEvent is called when a Wire.write is called by the I2C Master. As you can see, you continue to read data while Wire.available() which means data is still there to be received.

The function requestEvent is called when the I2C Master calls Wire.requestFrom. The Wire.write() function expects a array of bytes and a size as it’s parameters so I converted the string into an array of bytes.

In this case the loop() function does not do anything, so I just put a delay function in there.

As with the I2C Master example, the Serial functions are merely there to show that it works if you monitor it on your serial monitor.

Let’s put two Nano’s together and see the result.

Share this:

  • X
  • Facebook
Like Loading...
  • Arduino

Tag » Arduino Nano I2c Slave Address