Components Required:
1. Arduino Uno – 2 – Buy
2. Linux PC/Windows PC (Tested with Windows 10, Ubuntu 14.04 LTS)
3. USB cable A to B – 2 – Buy
4. Jumper Wires
Way to go ->
1. Connect Arduino Uno to PC via the USB cable.
2. Upload Master.ino in one Arduino and Slave.ino in the other.
Master.ino
/* I2C Master */
#include <Wire.h>
int x = 0;
void setup() {
Serial.begin(9600);
// Start the I2C Bus as Master
Wire.begin();
}
void loop() {
Wire.beginTransmission(9); // transmit to device #9
Wire.write(x); // sends x
Wire.endTransmission(); // stop transmitting
x++; // Increment x
if (x > 5) x = 0; // `reset x once it gets 6
Serial.print(x);
delay(500);
}
Slave.ino
/* I2C Slave */
#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
Serial.begin(9600);
// 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
}
void loop() {
//If value received is 0 blink LED for 200 ms
if (x == 0) {
Serial.println("Game On!");
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
delay(200);
}
//If value received is 3 blink LED for 400 ms
if (x == 3) {
Serial.print("Game's afoot!");
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
delay(100);
}
}
Slave.ino
/* I2C Slave */
#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
Serial.begin(9600);
// 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
}
void loop() {
//If value received is 0 blink LED for 200 ms
if (x == 0) {
Serial.println("Game On!");
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
delay(200);
}
//If value received is 3 blink LED for 400 ms
if (x == 3) {
Serial.print("Game's afoot!");
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
delay(100);
}
}
Hardware Connections ->
1. Arduino Uno to Arduino Uno
No comments:
Post a Comment