Simple I2C protocol for advanced communication between Arduinos

Main task – advanced communication between multiple Arduinos using I2C bus.
Main problem – most online tutorials covers just one blinking LED with almost no practical use. Slave just executes ONE and SAME function every time Master asks about it. I’d like to outsource slave Arduinos for zillions of tasks.
Proposed solution – simple protocol which enables to send any number of commands to Slave, opposing single return from simple
Wire.onRequest();

Strong communication skills are always a key to success:

Say we have one Arduino(Slave) dedicated for position sensors and motor drives. Other slave for handling user interface tasks (displays, input controls, wifi communication). And a Master Arduino for controlling them all together. Master can ask to do any number of tasks(not just one from one Arduino).

Official Wire (I2C library for Arduino ) reference doesn’t add a lot of clarity for novices.
Good starting point is this tutorial: http://arduino.cc/en/Tutorial/MasterWriter. It just lacks of two pull-up resistors on SDA and SCL lines. Do not forget them. * Also some people report problems when multiple Arduinos are connected to one computer at the same time.

As you can see from above tutorial, communication is performed by transferring chars or bytes (max value 255). Thats not much use if you want to transfer real-life values like integers from
analogRead(); or control some Digital PMW Pin.

So, second highly recommended tutorial can be found here: http://jamesreubenknowles.com/arduino-i2c-1680. It shows how to easily transfer and receive integer values by splitting them into two bytes (warning: some bitshifting involved).

Main problem for me was that I had multiple sensors on one sensor-dedicated slave. And on master’s request
Wire.onRequest(); Slave could only return one value. So I made simple protocol for choosing desired sensor. The same method can be used for performing different tasks on slave, not just returning different values. You can make slave perform any function from its arsenal.

LastMasterCommand=Wire.read();// 1 byte (maximum 256 commands), it can be easily changed to integer

}

Now when we have command (LastMasterCommand), we will wait for execution request from Master:

Request execution

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

voidsetup(){

Wire.onRequest(slavesRespond);// Perform on master's request

}

...

voidslavesRespond(){

intreturnValue=0;

switch(LastMasterCommand){

case0:// No new command was received

Wire.write("NA");

break;

case1:// Return X sensor value

returnValue=GetXSensorValue();

break;

case2:// Return Y sensor value

returnValue=GetYSensorValue();

break;

case3:

// Another useful function if received command = 3, and so on...

break;

}

uint8_t buffer[2];// split integer return value into two bytes buffer

buffer[0]=returnValue>>8;

buffer[1]=returnValue&0xff;

Wire.write(buffer,2);// return slave's response to last command

LastMasterCommand=0;// null last Master's command and wait for next

}

Function on Master’s side for getting X Sensor value from Slave Arduino:

GetXSensorValue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

intGetXSensorValue(byteSlaveDeviceId){

// SEND COMMAND

Wire.beginTransmission(SlaveDeviceId);

Wire.write(1);// Transfer command ("1") to get X sensor value;

delay(10);

// GET RESPONSE

intreceivedValue;

intavailable=Wire.requestFrom(SlaveDeviceId,(byte)2);

if(available==2)

{

receivedValue=Wire.read()<<8|Wire.read();// combine two bytes into integer

}

else

{

Serial.print("ERROR: Unexpected number of bytes received (XSensorValue): ");

Serial.println(available);

}

Wire.endTransmission();

returnreceivedValue;

}

Thats all, functions can do any tasks, not only read sensors. For example they can control a motor or LED’s and return no useful data (just report successful execution).
Using same technique You can expand this simple protocol, i.e. pass a command number AND then some parameters to Slave, and then execute it. I showed basic principle.

Complete Master side program: (click to expand)

Master

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

// Simple I2C protocol for Arduino

// Master side program

// (c) 2014 Ignas Gramba

//

#include <Wire.h>

voidsetup()

{

Wire.begin();// join i2c bus (address optional for master)

Serial.begin(9600);// start serial for output

}

voidloop()

{

intx=GetXSensorValue(1);// 1 - slave's address

Serial.print("X Sensor value: ");

Serial.println(x);

delay(100);

}

intGetXSensorValue(byteSlaveDeviceId){

// SEND COMMAND

Wire.beginTransmission(SlaveDeviceId);

Wire.write(1);// Transfer command ("1") to get X sensor value;

delay(10);

// GET RESPONSE

intreceivedValue;

intavailable=Wire.requestFrom(SlaveDeviceId,(byte)2);

if(available==2)

{

receivedValue=Wire.read()<<8|Wire.read();// combine two bytes into integer

}

else

{

Serial.print("ERROR: Unexpected number of bytes received (XSensorValue): ");

Serial.println(available);

}

Wire.endTransmission();

returnreceivedValue;

}

Complete Slave side program: (click to expand)

Slave

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

// Simple I2C protocol for Arduino

// Slave side program

// (c) 2014 Ignas Gramba

//

#include <Wire.h>

#define XSensorPin A1

#define YSensorPin A2

constbyteSlaveDeviceId=1;

byteLastMasterCommand=0;

voidsetup(){

Wire.begin(SlaveDeviceId);// join i2c bus with Slave ID

Wire.onReceive(receiveCommand);// register talk event

Wire.onRequest(slavesRespond);// register callback event

pinMode(XSensorPin,INPUT);

pinMode(YSensorPin,INPUT);

}

voidloop(){

delay(100);

}

voidreceiveCommand(inthowMany){

LastMasterCommand=Wire.read();// 1 byte (maximum 256 commands)

}

voidslavesRespond(){

intreturnValue=0;

switch(LastMasterCommand){

case0:// No new command was received

Wire.write("NA");

break;

case1:// Return X sensor value

returnValue=GetXSensorValue();

break;

case2:// Return Y sensor value

returnValue=GetYSensorValue();

break;

}

bytebuffer[2];// split int value into two bytes buffer

buffer[0]=returnValue>>8;

buffer[1]=returnValue&255;

Wire.write(buffer,2);// return response to last command

LastMasterCommand=0;// null last Master's command

}

intGetXSensorValue(){

intval=analogRead(XSensorPin);

returnval;

}

intGetYSensorValue(){

intval=analogRead(YSensorPin);

returnval;

}

UPADATE

Update: I wrote new example for sending command AND passing data for Slave functions.

Now Master sends not only command number (one byte), but 11 bytes data packet consisting of:

Command number (one byte)

1-st argument value (int) (or two bytes)

2-nd argument value (int) (or two bytes)

3-rd argument value (int) (or two bytes)

4-th argument value (int) (or two bytes)

5-th argument value (int) (or two bytes)

I plan to use functions with maximum 5 integer arguments. If You need more/less or wish to change input/output variables type it can be easily done, by examining these examples. They are completely based on previous ones. Maximum size of standard buffer in Wire library is 32 bytes.

In order to work correctly, data packet has always be the same size (even if Your function doesn’t need any arguments You have to pass zeroes or any values). Also if You are not interested in return value of any Slave’s function, than You can execute commands in
Wire.onReceive(); function. There is no need to ask for return
Wire.onRequest(); if You are interested in just sending data from Master to Slave. But if You have just one function that returns something, use
Wire.onRequest(); everywhere. Wire likes consistency. A lot.

In this example Master creates a data packet (command number, and five integer variables), sends it to Slave, Slave performs sum of all 5 variables and returns result to Master. Master prints result in serial window. Slave acts as a math-coprocessor for the Master 🙂

Tip – if You don’t see correct answer in serial window – press “reset” button on Master, while serial window is open. This will solve early power-on miscommunication issues. Later both sides will work correctly.

Complete Master side program v0.2: (click to expand)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

// Simple I2C protocol v0.2 for Arduino

// Master side program

// (c) 2014 Ignas Gramba

//

#include <Wire.h>

byteDataPacket[11];

bytecommand_nr;

inta,b,c,d,e;// arguments

byteSlaveDeviceId=1;

voidsetup()

{

Wire.begin();// join i2c bus (address optional for master)

Serial.begin(9600);// start serial for output

command_nr=2;// initialise test values

a=105;

b=2350;

c=4587;

d=12587;

e=12;

}

voidloop()

{

makeDataPacket(command_nr,a,b,c,d,e);

sendDataPacket();

intresponse=receiveResponse();

Serial.print("Slave response: ");

Serial.println(response);

while(1);// Stop

}

voidmakeDataPacket(bytecommand,intaa,intbb,intcc,intdd,intee){

DataPacket[0]=command;

DataPacket[1]=aa>>8;

DataPacket[2]=aa&255;

DataPacket[3]=bb>>8;

DataPacket[4]=bb&255;

DataPacket[5]=cc>>8;

DataPacket[6]=cc&255;

DataPacket[7]=dd>>8;

DataPacket[8]=dd&255;

DataPacket[9]=ee>>8;

DataPacket[10]=ee&255;

}

voidsendDataPacket(){

Wire.beginTransmission(SlaveDeviceId);

Wire.write(DataPacket,11);

delay(10);

}

intreceiveResponse(){

intreceivedValue;

intavailable=Wire.requestFrom(SlaveDeviceId,(byte)2);

if(available==2)

{

receivedValue=Wire.read()<<8|Wire.read();// combine two bytes into integer

Support

14 Comments

Mark Schilke
January 22, 2015 at 21:08

Hello, Ignas.

Thank you for sharing and explaining your Arduino I2C protocol programs. I don’t know if you have done any more development work on them lately, but you may encounter some difficulty with the code as it is shown in your July 2014 blog.

When I tried using your programs, I found that the slave did not make an immediate response to the command sent by the master. In fact, it was always one command behind. I believe that is because transmission of the data packet does not actually begin when the Wire.write statement in the sendDataPacket subroutine is executed — it is only putting the 11 bytes into the I2C buffer. Execution of the Wire.endTransmission statement in the receiveResponse subroutine is what sends out the command over the wired connection, but by then it is too late.

After I added a Wire.endTransmission statement to the sendDataPacket subroutine (and a Wire.beginTransmission statement to the receiveResponse subroutine), the protocol worked exactly as it should. If you like, I can send you the modified code and the results I got with them.

A more effective communication mechanism exists – master (with unique ID) gives a job to each slave (must have different IDs) and each time ends transmission by releasing the I2C bus. After the each slave finishes, it acquires the I2C bus for transmission and posts a response back to master. This is more optimal as the I2C bus is not being locked until one slave finishes off work 😛

i.e. master should not wait for the result in the function GetXSensorValue, but just post a job for the slave and bail out immediately. Slave should respond back when it’s done.

Alex
May 13, 2016 at 14:24

As far as I am aware slave cannot initiate a connection on its own.
Each time connection has to be requested by a master.

pahval
October 31, 2015 at 18:17

hi! man, this is just what i was looking for, starting from scratch but working on big project (18 sensors, 6 relays, sending sensor data to master and receiving relay commands from master, and maybe parameters for slave’s part of relay automation, you know like, i send to master temp number at wich slave will start the heater), and i just wanna know what does this mean:

DataPacket[1] = aa >> 8;
DataPacket[2] = aa & 255;

…this aa>>8 and aa & 255…

and in:

a = Wire.read() << 8 | Wire.read()

…this wire.read() << 8 | wire.read()

my intuition tells me you decoded that "a" value in two forms, but i dont understand (and i must, for i will burn my brain trying to figure it out just based on your code!) why, how and what do you get with it… i mean, a=105, so what, you present that number in 2 ways so that -what?- you can get -what?…

dont have to tutor me here if you dont want to, but please, could you maybe send me some info on what this is all about so i can scan the web for it…

………………………

well, when you are allready here, ill tell you bout my project…

i have a growbox (for tomatoes, of course), wich has about 18 sensors and 6 relays (i like to play rough) wich are connected to mega slave,
and in my room i (will) have rgb led strip, some sensors, ir emmiter, electric door lock etc. basically automated crib with lots of stuff i dont really need, wich would be operated on master intel edison, and i need slave to send sensor data to master wich sends them to my app as i am controlling with my app the tv buttons, blinds, coffee machine, lights, some relays and of course, reading and controling growbox (trigger lamps when master rtc hits 22:00 or whatever time i need, display sensor data etc.), so i need this type of communication between master and slave (slave send all sensor data, receive at wich value and/or when do something), but man, this cyphering of values really grinds my gears…

I am assuming that Line 10 is where I have to define all of the slave ID’s
I am not connected using the A4 & A5 pins I am using SCL and SDA If this in incorrect please assist me where to find the correct information.

I currently have three Arduino’s on a buss proper resistors installed. Is there a way to create
this communications bus with the SLC SDA or should I be using A4 A5 with this code?

Also Line 7 would also need to add another DataPacket [12] for the next device? and if so what else would need to change.?