Introduction: Communication Between Two Arduinos (I2C)

We will be setting up two Arduinos to communicate using the I2C protocol. This is a simple project to take input from a push-button switch on the first Arduino, send the signal received from the button to the second ("slave") Arduino, and use the slave to turn on an LED once the appropriate signal is received.

You will need:

2 Arduinos

2 220 Ohm resistors

1 LED

1 Push-button switch

2 Breadboards (medium or large)

Step 1: Hook Up the Master Arduino

In this project, we use two Arduino Unos, one to act as the "master," and one to act as the "slave."

First, we will hook up the master Arduino to send a signal when the button is pressed. It will then send a 0 or 1 to the slave, indicating whether to turn the LED on or off.

Pins used:

pin 2 - Digital read from the button switch.

Ground

VCC (5V)

Parts used:

1 push-button switch

1 200 Ohm resistor

Step 2: Hook Up the "Slave" Arduino

The slave Arduino receives the signal from the master Arduino. The signal should be either a 0 or a 1. If it is a 1, it turns its LED on, and if it is a 0, it sends the signal to turn the LED off.

Pins used:

pin 9 - Output to turn on the LED

Ground - Connect to the ground rail on the breadboard

VCC (5V) - Connect to the power rail on the breadboard

Parts used:

1 220 Ohm resisitor

1 LED

Step 3: The "Master" Arduino Code

#include < Wire.h > // <-- remove spaces

int x =0;

int slaveAddress = 9;

const int buttonPin = 2; // the number of the pushbutton pin

int buttonState = 0; // variable for reading the pushbutton status

void setup()

{

pinMode( buttonPin, INPUT ); // initialize the pushbutton pin as an input

Wire.begin(); // join i2c bus (address optional for master)

Serial.begin( 9600 ); // start serial for output

}

void loop()

{

// read the state of the pushbutton value:

buttonState = digitalRead( buttonPin );

// check if the pushbutton is pressed. If it is, the buttonState is HIGH:

if ( buttonState == HIGH )

{

x = 1;

}

else

{

x = 0;

}

Wire.beginTransmission( slaveAddress ); // transmit to device #9

Wire.write(x); // sends x

Wire.endTransmission(); // stop transmitting

delay(200);

}

Step 4: The "Slave" Arduino Code

#include < Wire.h > // <-- remove spaces

int LED = 13;

int x = 0;

void setup()

{

// Define the LED pin as Output

pinMode (LED, OUTPUT);

// Start the I2C Bus as Slave on address 9

Wire.begin(9);

// Attach a function to trigger when something is received.

Wire.onReceive(receiveEvent);

}

void receiveEvent( int bytes )

{

x = Wire.read(); // read one character from the I2C

Wire.endTransmission(); // stop transmitting

}

void loop()

{

if (x == 0) {

digitalWrite(LED, HIGH);

delay(200);

}

if (x == 0) {

digitalWrite(LED, LOW);

delay(200);

}

}