0

I beg your help to my project I wish to send the data from slave to master but only one data is receive out of two slaves.

//master



#include <Wire.h>


void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output

}

void loop() {
  Wire.requestFrom(8, 1);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c= Wire.read(); // receive a byte as character
    char q= Wire.read();

  Serial.print(c);         // print the character
  Serial.print(q);
  }

  delay(1500);
}

////slave 1

#include <Wire.h>

void setup() {
  Serial.begin(9600); // Starting Serial Terminal
  Wire.begin(8);                // join i2c bus with address #8
}

void loop(){
  Wire.onRequest(requestEvent); // register event

  delay(1500);
}
void requestEvent() {

  Wire.write('Q'); 
  Serial.println("Sent");
}

////slave 2

#include <Wire.h>

void setup() {
  Serial.begin(9600); // Starting Serial Terminal
  Wire.begin(8);                // join i2c bus with address #8
}

void loop() {
  Wire.onRequest(requestEvent); // register event

  delay(1500);
}
void requestEvent() {

  Wire.write('Y'); 
  Serial.println("Sent");
}
  • I think both slaves has same address that's why you are facing this issues, because master communicate with both slave with same address and receive only one data, that might be slave 1 or 2. You need to change slave address and synchronize the communication of both slave with master. – Vaibhav Apr 23 at 12:19
  • What hardware, i.e. microcontroller, are you using? – MichaelT Apr 23 at 15:41
3

You cannot have 2 devices with the same address at the I2C bus. If they both try to send at the same time with different data, the data will either get corrupted, or one of the slaves will stop to send. You cannot request data from more than 1 device at once with I2C.

You have to give the slaves different addresses. Then you have to do the requests sequentially, first a request (with the corresponding read) to the first slave and after that is done, you can start a second request (with the corresponding read).


Besides that, the reading code is not good. You are testing in the condition of the while loop, if there is anything to read (which can be only 1 byte), but then you read 2 bytes. In your case you only have to read 1 byte, since you also request only 1 byte. In the case, when you request more than 1 byte, you can either check, if there are enough bytes in the buffer (with something like if(Wire.available()>=2) ), or you can just work through the buffer byte by byte (with while(Wire.available()){ data = Wire.read();} , note the single read in the while loop).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.