Hello i have spotted problem and dont know why it happens so maybe you will tell me ![]()
Im trying to do a 1 arduino which will recive datas from all other slave arduinos and based of that data will do some more objectives. So i decded to try to communicate throught I2C, becouse i have read that i can connect a lot of slaves.
MASTER CODE
#include <Wire.h>
// MAX INT 32767
int x = 1;
int numberOfSlaves = 4;
void setup()
{
 Wire.begin();    // join i2c bus (address optional for master)
 Serial.begin(9600); // start serial for output
}
int output = 0;
void loop()
{
 if (x == numberOfSlaves + 1) {
  x = 1;
 }
 Serial.print("Reading from:");
 Serial.println(x);
 Wire.requestFrom(x, 1); // the first byte
 while (Wire.available())
 {
  unsigned char received = Wire.read();
  output = received;
 }
 for (int i = 0 ; i < 3 ; i++) // next 3 bytes
 {
  Wire.requestFrom(x, 1);
  while (Wire.available())
  {
   unsigned char received = Wire.read();
   output |= (received << 8);
  }
 }
 Serial.print(output);
 Serial.println(".");
 delay(1000);
 x++;
}
Slave 1 CODE rest is the same they just have other numbers and send other data in order to check if they work good.
#include <Wire.h>
// MAX INT 32767
void setup()
{
Wire.begin(1);Â Â Â Â Â Â Â Â // join i2c bus with address #2
Wire.onRequest(requestInt); // register event
}
int byteSending = 1;
int toTransfer = 1; // data that will be transfered as int
int Shift = toTransfer;
int mask = 0xFF;
unsigned char toSend = 0;
void loop()
{
//toTransfer = random(10000, 32767);
delay(10);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestInt()
{
if (byteSending == 1) //send packet 1
{
 toSend = Shift & mask;
 Shift = Shift >> 8;
 Wire.write(toSend);
 byteSending = 2;
}
else if (byteSending == 2) //send packet 2
{
 toSend = Shift & mask;
 Shift = Shift >> 8;
 Wire.write(toSend);
 byteSending = 3;
}
else if (byteSending == 3) //send packet 3
{
 toSend = Shift & mask;
 Shift = Shift >> 8;
 Wire.write(toSend);
 byteSending = 4;
}
else if (byteSending == 4) //send packet 4
{
 toSend = Shift & mask;
 Shift = Shift >> 8;
 Wire.write(toSend);
 byteSending = 1;
 //initialization for next turn
 Shift = toTransfer;
 mask = 0xFF;
 toSend = 0;
}
}
I also attached a circuit.
Every GND is attached to each other.
The whole idea works fine for 3 slave arduino connected. Every arduino sends its unique data. After 4th it always sends "0". Do you know why?

