So I was trying to use on of my Arduinos to send a single byte to my other 2 Arduinos based on which they would modify their PWM values.
I checked all the hardware twice, it is working fine on its own. But my problem is that when I put the system together the slave Ardunios only read the first byte sent from the master the next one is not read at all.
Please help me, I have no clue what is going wrong!
I have attached a picture as well if it helps.
My code is as follows:
Master Code
// Wire Master Writer
// Writes data to an I2C/TWI slave device
#include <Wire.h>
void setup()
{
Wire.begin(); // join i2c bus (address optional for master)
}
void loop()
{
Wire.beginTransmission(5); // transmit to device #5
Wire.write(1); // sends one byte
Wire.endTransmission(); // stop transmitting
Wire.beginTransmission(4); // transmit to device #5
Wire.write(1); // sends one byte
Wire.endTransmission(); // stop transmitting
delay(1000);
Wire.beginTransmission(5); // transmit to device #5
Wire.write(2); // sends one byte
Wire.endTransmission(); // stop transmitting
Wire.beginTransmission(4); // transmit to device #5
Wire.write(2); // sends one byte
Wire.endTransmission(); // stop transmitting
}
Slave code
// Wire Slave Receiver
// Receives data as an I2C/TWI slave device
#include <Wire.h>
int i = 0;
int led = 13;
int data;
void setup()
{ pinMode(3, OUTPUT);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
pinMode(11, OUTPUT);
pinMode(led, OUTPUT);
Wire.begin(4); // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event
}
void loop()
{
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
data = Wire.read(); // receive byte as a character
if(data == 1)
{//Switch all motors on
analogWrite(3, 255);
analogWrite(6, 255);
analogWrite(9, 255);
analogWrite(11, 255);
}
else if (data == 2)
{// Switch all motors off
analogWrite(3, 0);
analogWrite(6, 0);
analogWrite(9, 0);
analogWrite(11, 0);
}
else if (data == 3)
{//Switch on motora at half speed
analogWrite(3, 125);
analogWrite(6, 125);
analogWrite(9, 125);
analogWrite(11, 125);
}
else if(data == 4)
{ //Speed up one motor very slowly
for (int i=0; i<=255; i++)
{
analogWrite(11, i);
//analogWrite(motorPin2, i);
delay(10);
}
delay(500); //Hold it!
//Decrease Motor Speed from 255 -> 0
for(int i=255; i>=0; i--)
{
analogWrite(11, i);
// analogWrite(motorPin2, i);
delay(10);
}
delay(500); //Hold it!
}
else
{// Blink LED for unidentified character
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
}