}

10/18/2012

i2c communication between an Arduino Uno and an Arduino Mega 2560



I've never worked with i2c before, except to connect an i2c LCD.  In this video, I get an Arduino Mega 2560 and an Arduino Uno to talk to eachother over an i2c bus.

The Arduino Mega 2560 is set up as the master device.  I connect pin 20 (SDA) to a negative power rail on the breadboard, and pin 21 (SCL) to a positive rail.  On the Arduino Uno, I have A4(SDA) connected to the negative power rail and A5 (SCL) connected to the positive.  The SDA and SCL channels from each Arduino are now connected to eachother.

I must now provide power to the SDA and SCL channels of the i2c bus.  I use the +5VDC pin on the Mega 2560 to power the SDA and SCL channels, going through a 4.7K ohm pull-up resistor first.

The last connection I make is to connect an LED up to digital pin 8 of the Arduino Uno, going through a 510 ohm current limiting resistor on the ground side.

Below is the code I used for each Arduino.  The master, the Mega 2560, sends an 'H' to i2c device #6.  When the Uno receives the 'H', it turns the LED on pin 8 ON.  The Mega waits 3 seconds, then sends an 'L' to the Uno.  The Uno reads the 'L', then turns the LED OFF.  Pretty simple code.  Note that the receiveEvent() routine is basically an interrupt handler.  This way the Uno will stop whatever it is in the middle of whenever i2c traffic is received.

First the Master - the Arduino Mega 2560


//i2c Master Code(MEGA)
#include <Wire.h>

void setup()
{
  Wire.begin();
  delay(2000);
}
void loop()
{      
      Wire.beginTransmission(5);
      Wire.write('H');
      Wire.endTransmission();
      
      delay(3000);
      
      Wire.beginTransmission(5);
      Wire.write('L');
      Wire.endTransmission();
      
      delay(3000);     
}

and now the code for the slave, the Arduino Uno


//i2c Slave Code(UNO)
#include <Wire.h>

void setup()
{
  Wire.begin(5);
  Wire.onReceive(receiveEvent);
  
  pinMode(8,OUTPUT);
  digitalWrite(8,LOW);
}

void loop()
{
}

void receiveEvent(int howMany)
{
  while(Wire.available())
  {
    char c = Wire.read();
    
    if(c == 'H')
    {
      digitalWrite(8,HIGH);
    }
    else if(c == 'L')
    {
      digitalWrite(8,LOW);
    }
  }
}