Firstly, I need to mention that I am using Strings because I am on an ESP32 and it makes my life so much easier.
I have written a piece of code that sends a command to an RFID reader and then reads a part of the incoming data.
Please note that the send command routine is basic and won't be used in a real working environment. Not in this form anyway.
// outside of void loop()
bool command = true;
// RFID routine
if (activateRFID)
{
// send command to reader
if (command)
{
Serial1.print("mt2000\r"); // set read interval
command = false; // so that this code executes only once
// delay(500);
// Serial1.flush();
// read incoming data from the sent command
if (Serial1.available() > 10)
{
String str = Serial1.readStringUntil((char)'>');
Serial.println(str);
}
// delay(2000);
// Serial1.flush();
}
String rf_id;
// read incoming data from a RFID card read at some point in time
if (Serial1.available() > 10)
{
Serial.println();
Serial.print("Before: ");
Serial.println(Serial1.available()); // number of bytes available to read
char input[9];
String str = Serial1.readStringUntil((char)'B');
Serial.println(str);
Serial1.flush();
}
}
My purpose is to send the command then read part of the incoming data(first if(Serial1.available() > 10)) then "flush" the rest of that respective data so that the serial buffer is empty so that it can be ready for the next incoming piece of data(second if(Serial1.available() > 10)).
The problem is that I can't figure out a way of "flushing" the extra data before the second if (Serial1.available() > 10).
I've tried using Serial1.flush() in the places that it is commented in the code above, but this doesn't discard the buffer. In both cases this adds the data from the command to the data that's coming when I read a RFID card.
I've also tried other methods that I've found on this forum, like:
while(Serial1.available())
{
char t = Serial1.read();
}
And it still enters in the second if (Serial1.available() > 10).
Using delay(500) and using it only before the first if (Serial1.available() > 10) is the only way to ensure that the second if (Serial1.available() > 10) isn't true.
I am trying to understand this because in a normal working environment the reader can read card after card and I don't want the incoming data from the first read to add to the second read and so on. That's why there is a Serial1.flush(); at the end of the code.
If I remove that Serial1.flush(); the code enters the second if twice and the second time Serial.println(str); prints the rest of the data that came from reading a card. I think that this Serial1.flush(); does something useful but only because the default serial timeout is 1000ms and the RFID reader is set to read cards at a 2000ms interval.
The more I dig in the less I understand.