wvmarle:
Serial.println(distance);This is the same as you use to print on your Serial monitor, so it will convert the int to char array, then print the separate chars. So you're sending your int in the form of ASCII characters. On the other end you then have to read these characters, put them in a char array, and convert that back to an int.
Actually you can do this much more efficiently.
What is the maximum value this distance can be? So far you're talking about values of 100-200. If no more than 255 ever, you can change the type to byte, and then send that using Serial.write(). Then you just have to read a single byte on the other side. If it can be larger than 255 but no more than 65535, you can use an unsigned int. That's two bytes on Arduino, I don't know about Teensy - so use uint16_t instead which is certain to be 16 bits or 2 bytes.
When using the Serial.write() function your receiving code becomes something like:
// In case of sending a single byte (0 <= distance <= 255):
byte distance;
if (Serial.available())
distance = Serial.read();
// In case of sending a 16-bit int (0 <= distance <= 65535):
byte i[2];
uint16_t distance;
if (Serial.available()) {
i[0] = Serial.read(); // Read the first byte
i[1] = Serial.read(); // Read the second byte
distance = uint16_t(i[0] << 8) | i[1]; // Reassemble the original value.
}
Please note: I don't know the order in which the two bytes of the int are sent; I guess it's high byte first, low byte second but it may be the other way around and then of course you have to swap the two in the "reassemble" line.
Thank very much sir for putting efforts to teach me.
If im gonna use this code on the receiver side
// In case of sending a single byte (0 <= distance <= 255):
byte distance;
if (Serial.available())
distance = Serial.read();
Can i use "distance" in this part of my code?
if (XBee.read() >=100 ) //changing XBee.read() into distance, is the 100 int? since there is math happening
{
digitalWrite(relay, LOW);
}
else
{
digitalWrite(relay,HIGH);
}
delay(3000);
}
Thank you sir, really appreciate your effort!