Networking and communications

I2C Bus

I connected 3 Atmega328p microcontrollers on a I2C Bus on a bread-board. One is the Master and the two others are the slaves with addresses 1 and 2. The code increments a counter when the counter is 1 the first node blinks an LED and when the counter is 2 the second node blinks another LED. The SDA and SCL line have 4.7k pull-up resistors connected to VCC.

photo

Master code

#include 'Wire.h'
int x = 0;
void setup() {
Wire.begin();
// Start the I2C Bus as Master
}
void loop() {
x++; // Increment counter x
Wire.beginTransmission(1); // transmit to device #1
Wire.write(x); // transmit x
Wire.endTransmission(); // stop transmitting
delay(1000);
Wire.beginTransmission(2); // transmit to device #2
Wire.write(x); // transmit x
Wire.endTransmission(); // stop transmitting
delay(1000);
if (x > 2) x = 0; // reset counter
}




Slave code

#include 'Wire.h'
int LED = 8;
int x = 0;
void setup() {
pinMode (LED, OUTPUT);// LED pin as Output
Wire.begin(1); // Start I2C as Slave on address 1
Wire.onReceive(receiveEvent);// trigger when something is received.
} void receiveEvent(int bytes) {
x = Wire.read(); // read character from I2C
}
void loop() {
if (x == 1) {
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
delay(200);
digitalWrite(LED, HIGH);
}
else {
digitalWrite(LED, LOW);
}
}