Also asked in forum.arduino.cc
bool receive_command(char answer[]);
void serial_flush(void);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
for(byte i=0;i<3;i++){
if(receive_command("OK")) Serial.println("OK found");
serial_flush();
}
}
void loop() {}
void serial_flush(void) {
while (Serial.available()) Serial.read();
}
bool receive_command(char answer[]) {
unsigned long _time = 0;
const int max_time = 10000;
bool flag = 0;
Serial.print("in Serial buffer=");
Serial.println(Serial.available());
if(Serial.available()){
Serial.write(Serial.read());
Serial.println(" left in serial buffer");}
while (Serial.available() < 2) {
if ((millis() - _time) > max_time) {
Serial.println("waited too long nothing received");
return flag;
}
}
do {
if (Serial.findUntil(answer, '\n')) return flag = 1;
} while (Serial.available());
return flag;
}
via serial monitor with CR+LF line ending I`m sending this string: abcdefghijklmnopqrstuvwxyzOKabcdefghijklmnopqrstuvwxyz 26chars+OK+26chars+CR+LF=56 chars
Output:
in Serial buffer=0
OK found
in Serial buffer=1
b left in serial buffer
in Serial buffer=0
waited too long nothing received
after OK is found serial_flush() is executed but after second run there serial.available() shows there is something in serial buffer. right at that moment it was char 'b' but it also can show char 'd' and 'c' depending how long it will run.
why serial_flush() is not clearing the buffer?
Thanks.
b
orc
ord
... serial_flush() exits beforee
is received, since the buffer is empty (e
has not yet arrived) ................ imagine that you are the Arduino and you receive one character every hour ... what do you do after you have received theO
K
?