Hello.
I'm facing a problem with connecting Arduino UNO (as slave) and Ardunio micro (as master). I've connected their grounds together, pins A4 together and pins A5 together. I've run the below codes but although I'm assigning x a value of 5, I'm getting the word linked with x==0 which is "Hello" instead of "Hello5". I would appreciate your help, please.
master's code
#include <Wire.h>
int x = 0;
void setup() {
// Start the I2C Bus as Master
Wire.begin();
Serial.begin(9600);
}
void loop() {
Wire.beginTransmission(9); // transmit to device #9
Wire.write(x); // sends x
Wire.endTransmission(); // stop transmitting
x = 5;
Serial.println(x);
//x++; // Increment x
// if (x > 5) x = 0; // `reset x once it gets 6
// delay(500);
}
Salve's code
#include <Wire.h>
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);
Serial.begin(9600);
}
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("Hello");
}
//If value received is 3 blink LED for 400 ms
if (x == 1) {
Serial.println("Hello again");
if (x == 2) {
Serial.println("Hello2");
}
if (x == 3) {
Serial.println("Hello3");
}if (x == 4) {
Serial.println("Hello4");
}if (x == 5) {
Serial.println("Hello5");
}
}
}