Introduction: Communicating With Two Arduinos

by Lindsey Mikel and Kenny McNeese

Step 1: Basic Connections

First, you have to connect both Arduinos to each other. For this, only three wires are needed. Connect the GND pin of the first Arduino to the GND of the other; do the same using the A4 and A5 pins.

Step 2: Add LED to the Secondary Arduino

Connect one of the Arduinos to a breadboard and connect an LED to that breadboard.We connected our LED to pin 13 on the secondary Arduino using a 220 ohm resistor. Connect the short end of the LED to ground.

Step 3: Adding the Potentiometer

In this step, we will connect a Potentiometer to the Master Arduino. Using the GRD pin on the Arduino, Take a wire to the negative row on the breadboard. Connect the postive row to 5 on the Analog side. Insert the potentiometer into the breadboard. Ground it, by connecting the first pin to the negative row. Connect the second pin to number 2 on the Arduino analog side. Use the third pin to connect to the postive row on the breadboard.

Step 4: Master Arduino Code

#include 
// Include the required Wire library for I2C
#include
int potPin = 2;
int potVal = 0;
void setup() {
  // Start the I2C Bus as Master
  Wire.begin(); 
  Serial.begin(9600);
  pinMode(potPin, INPUT);  //Optional, pins are listed as inputs by default
}
void loop() {
  potVal = analogRead(potPin);
  Wire.beginTransmission(9); // transmit to device #9
  Wire.write(potVal);              // sends x 
  Wire.endTransmission();    // stop transmitting
  Wire.requestFrom(9, 6);    // request 6 bytes from slave device #8
  while (Wire.available()) { // slave may send less than requested
    char x = Wire.read(); // receive a byte as character
    Serial.print(x);         // print the character
  }
  
  delay(500);
}

Step 5: Slave Arduino Code

#include <Wire.h>
int ledPin = 11;
int x = 0;
void setup() {
  Serial.begin(9600);
  pinMode (ledPin, 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);
  Wire.onRequest(requestEvent);
}
void requestEvent()
{
  Wire.write("Hello ");
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
}
void loop() {
Serial.println(x);
int pwm = map(x,0, 1023, 0, 255); 
analogWrite(ledPin, x);

}