problem on wire function (I2C)

Hi everyone.

I am trying to make three arduino decvices (slaves) to send the number of cars they read by sensors to another arduino (master) when it requests.

The problem is the LCD always print this value 255, I've searched about it, but I conldn't understand how to do it in the right way.

here are the codes

1- Slave sender

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#include <Wire.h>
int threshold;  
int sens2;
int street2=0;
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
lcd.setCursor(5,0);
lcd.print("Hello!");
delay(2000);
lcd.clear();
sens2 = 0;
Wire.begin(8);
Wire.onRequest(requestEvent);

}

void loop()
{
sens2 = analogRead(A3);
threshold=1020;
if (sens2>threshold)
{
 street2++; 
 delay(1500);
 Serial.println(sens2);
}
lcd.setCursor(0,0);
lcd.print("street2 = ");
lcd.print(street2);
}

void requestEvent() {
  Wire.write(street2); 
}

2- Master reader

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#include <Wire.h>

int threshold;  
int sens1;
int street1=0;
int street2= 0;
void setup()
{
Serial.begin(9600);
lcd.begin(20,4);
lcd.setCursor(5,1);
lcd.print("Hello!");
delay(2000);
lcd.clear();
sens1 = 0;
Wire.begin();
}

void loop()
{

sens1 = analogRead(A3);
threshold=1020;
if (sens1>threshold)
{
 street1++; 
 delay(1500);
 Serial.println(sens1);
}
Wire.requestFrom(8, 2);    // request 2 bytes from slave device #8

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

  delay(500);
lcd.setCursor(0,0);
lcd.print("street1 = ");
lcd.print(street1);
lcd.setCursor(0,1);
lcd.print("street2 = ");
lcd.print(street2);

Serial.println(sens1);
}

On the sender, the requestEvent() function is an interrupt service routine. All variables shared between interrupt service routines and other functions need to be declared volatile. street2 is not.

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

That second comment is absolute rubbish. The value was sent as an int (two bytes), NOT as a string. The two bytes need to be read as the MSB and LSB and reconstructed as an int.

The value was sent as an int (two bytes)

Not with this it wasn't. :frowning:

void requestEvent() {
  Wire.write(street2); 
}

To send multiple bytes from the slave, you need break down the data into bytes, and send them all with one Wire.write command.

There are many ways to do this, but using the simplified highByte/lowByte Arduino syntax to break and integer

void requestEvent() {
  uint8_t buffer[2];
  buffer[0] =  highByte(street2);
  buffer[1] =  lowByte (street2);  
  Wire.write(buffer, 2);
}