Friday, September 19, 2014

Communication between Arduinos on I2C using Wire Library

Example to implement I2C communiation between Arduino Uno, using Wire Library.


Connection:


I2CMaster.ino
#include <Wire.h>

#define LED_PIN 13
byte CMD_ON = 0x00;
byte CMD_OFF = 0x01;
byte cmd = CMD_OFF;

byte slave_address = 7;

void setup()
{
  // Start I2C Bus as Master
  Wire.begin(); 
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);

}
void loop()
{
  if(cmd == CMD_OFF){
    delay(500);
    cmd = CMD_ON;  //prepare next cmd
  }else{
    delay(1500);
    cmd = CMD_OFF;  //prepare next cmd
  }
  
  Wire.beginTransmission(slave_address);
  Wire.write(cmd);
  Wire.endTransmission();
}

I2CSlave.ino
#include <Wire.h>

#define LED_PIN 13

//7-bit slave address (optional)
byte slave_address = 7;
byte CMD_ON = 0x00;
byte CMD_OFF = 0x01;

void setup() {
  // Start I2C Bus as Slave
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);  

}

void loop() {

}

void receiveEvent(int howMany) {
  byte cmd = Wire.read();
  if (cmd == CMD_ON){
    digitalWrite(LED_PIN, HIGH);
  }else if(cmd == CMD_OFF){
    digitalWrite(LED_PIN, LOW);
  }
}

Reference: Wire Library

No comments:

Post a Comment