Michael BOUVY
CTO E-commerce

Arduino : howto master to master I2C

twi multi-master master
Published on 2013/05/25

I've been working since many weeks (months) on designing a home automation "box" project, and could hardly find a way to get my Arduinos (actually bare ATMega328 + Arduino's Optiboot bootloader) communicating together without having the (physical) master poll all the other µCs continuously. After lots of googling, I finally got an answer thanks to the official Arduino Forum : I should use multi-master I2C to allow all my Arduino's to talk to each other (and that doing, interrupting receivers as it would be the case with slaves).

IC logo

Doing this is in fact pretty simple : you only to use the Arduino's official Wire (I2C) library as following.

Master #1

#include <Wire.h>

#define I2C_ADDRESS_OTHER 0x2
#define I2C_ADDRESS_ME 0x1

void setup() {
 Serial.begin(9600);
 Wire.begin(I2C_ADDRESS_ME);
 Wire.onReceive(receiveI2C);
}

void loop() {
 delay(5000);
 Wire.beginTransmission(I2C_ADDRESS_LCD);
 Wire.write("hello world from 0x1 to 0x2");
 Wire.endTransmission();
}

void receiveI2C(int howMany) {
 while (Wire.available() > 0) {
  char c = Wire.read();
  Serial.print(c);
 }
 Serial.println();
}

Master #2

#include <Wire.h>

#define I2C_ADDRESS_OTHER 0x1
#define I2C_ADDRESS_ME 0x2

void setup() {
 Serial.begin(9600);
 Wire.begin(I2C_ADDRESS_ME);
 Wire.onReceive(receiveI2C);
}

void loop() {
 delay(5000);
 Wire.beginTransmission(I2C_ADDRESS_LCD);
 Wire.write("hello world from 0x2 to 0x1");
 Wire.endTransmission();
}

void receiveI2C(int howMany) {
 while (Wire.available() > 0) {
  char c = Wire.read();
  Serial.print(c);
 }
 Serial.println();
}

That's all, now connect Arduino Uno's I2C pins (A4 [SDA] and A5 [SCL]) between each board, not forgetting the pull-up (1.2kΩ is fine) resistors for both SDA & SCL. You should then see "hello world" messages sent through serial on both of your Arduino masters.

Michael BOUVY

I'm Michael BOUVY, CTO and co-founder of Click&Mortar, a digital agency based in Paris, France, specialized in e-commerce.

Over the last years, I've worked as an Engineering Manager and CTO for brands like Zadig&Voltaire and Maisons du Monde.

With more than 10 years experience in e-commerce platforms, I'm always looking for new challenges, feel free to get in touch!