Monday, May 13, 2013

Arduino: I2C Communication between 2 Arduinos with Wire Library

The next method of communication I will look at is I2C communication. I2C stands for Inter-integrated circuit. It allows one master device to connect to a large number of slave devices using only 2 pins (signal and clock).  The nice folks at Arduino have made this very easy with the Wire library. It is included with the Arduino IDE and is supported on most Arduino boards.

Before we begin you may want to peruse the Arduino website. The Wire library is described HERE and detailed HERE.  When you finish those, let's dive in.

The first thing I did was run the master_reader and slave_sender examples. This was very easy. It sends hello from the slave to the master and displays it on the serial monitor.

Below is a picture of the wiring. It is simple. Wire the SCL pins and the SDA pins together through a pull-up resistor. I used 4k7. A good example can be found at THIS instructable. You also need to connect the grounds of the two boards as well as the vcc. I copied over the diagram for convenience (to the right).

Next I decided to make it transmit something useful. I made an I2C HC-SR04. The slave Arduino constantly takes distance measurements with the HC-SR04 sonar module. The master Arduino can then poll the slave whenever it wants to get the current distance measurement.

Wiring is the same as above. Make sure you use your pull-up resistors. I connected the trigger pin of the sonar to pin 7 and the echo to pin 8, but you could use any of them.

HERE is my code. Hopefully I will have time to rewrite the slave for the ATtiny in the future. That is the plan. Right after wireless communication, robot arm, computer vision..


1 comment: