I'm writing some code that compares information from two Arduino Unos by an Arduino Mega 2560. The problem that I'm having is that when I read the information coming in through Serial1
and Serial2
on my if
statements, I get both inputs out on my serial monitor for the Mega, but if I try to compare them after I have read them it comes out not working the way it is intended. I don't know if I might be missing some syntax on my code or if I'm doing this wrong but I would appreciate any help I can get.
byte inData;
byte inDataTwo;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
Serial1.begin(9600);
Serial2.begin(9600);
while (!Serial)
{
; // wait for serial port to connect. Needed for native USB port only
}
}
void loop()
{
if (Serial1.available()>0 )
{
inData = Serial1.read();
Serial.print(char(inData));
}
if (Serial2.available()>0)
{
inDataTwo = Serial2.read();
Serial.print(char(inDataTwo));
}
if(inData == inDataTwo)
{
Serial.print("true");
}
else
{
Serial.print("False");
}
}`
1 Answer 1
I think your code is implemented wrong in general. Even if it worked "like intended" it would not behave like you might want it to.
The first problem is, that you are polling for bytes that are received asynchronuously. That means that two byte sequences must not only be equal, they must also be sent "at the same time" if they should pass your comparison test. As the atmega will loop()
very fast, there is only very little tolerance in timing.
Secondly, the variables you write received values to are not reset, meaning that once they have the same value they will pass the if statement until another byte has been received. Actually they aren't initialized and therefore will be 0
at the very beginning. So I wonder why you don't get your Serial
interface flushed with true
. Is this actually the entire code?
As a solution I suggest accumulating received bytes into a buffer and waiting for a soecific termination byte (often /n
). If a termination character has been received, perform the comparison on that buffer.
else