I2C sending a message to slave.

Hi there, here is what I’m trying to accomplish. I have a master device and a slave device connected via I2C. Master has an ultrasonic sensor measuring the distance and sends a an integer “1” to slave device when the distance is <15cm. The slave should receive the sent integer and do something accordingly. In my example below, I only turn on an LED when the distance is < 15cm. However, I cannot get this code working and I couldn’t figure out why. I would very much appreciate if someone can point out what I’m doing wrong.

Thank you.

-----Master code-----

#include <Wire.h>

#define trigPin 13
#define echoPin 12

int duration, distance;

void setup()
{
  Wire.begin();
  Serial.begin(19200);
  delay(50);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, HIGH);

  delayMicroseconds(1000);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance > 1 && distance < 15) {
    Wire.beginTransmission(2); // transmit to device #2
    Wire.write(1); //send 1 to slave
    Wire.endTransmission(); // stop transmitting
  }
}

-----Slave Code-----

#include <Wire.h>

int led = 13;
int receivedValue;

void setup() {
  Serial.begin(19200);
  Wire.begin(2);                // join i2c bus with address #2
  Wire.onReceive(receiveCall); // register event
  pinMode(led, OUTPUT);
}

void loop() {

}

void receiveCall(int byteCount) {
  if (byteCount == 1) {
    receivedValue  = Wire.read();
    receivedValue |= Wire.read();
    if (receivedValue == 1) {
      digitalWrite(13, HIGH);
    }
  }
}

Why are you sending 1 as a byte, and then if you get 1 byte, reading two?

Why are you not printing anything on the slave?

    receivedValue  = Wire.read();
    receivedValue |= Wire.read();
    if (receivedValue == 1) {
      digitalWrite(13, HIGH);

Since you only send one byte the second one will be garbage, and probably -1 (0xFFFF). Thus once you "or" it in, it won't be 1, and you won't turn on pin 13.

Ahh what a simple mistake, this is what happens when you copy code from internet. Thank you very much, it works now.