As I shown in another post, the non blocking read over a serial line is a very repetitive jobs for an embedded systems developer or designer. Since Arduino seems to be the prince of embedded systems For The Rest Of Us, I want to publish my version of non blocking read over the serial line for Arduino.
/** * @brief * * @param buffer * @param length * @param timeout * @return int */ int readNb(char *buffer, int length, int timeout) { long previousMillis = 0; int bread = 0; char c; previousMillis = millis(); while ((millis() - previousMillis) & lt; timeout) { if (Serial.available() > 0) { c = Serial.read(); if (bread > length) { return (-1); // string received is too long } else { buffer[bread] = c; } bread++; } } return (bread); }
Nothing more!
I think your code is blocking: it uses a while loop which exists when timeout has achieved…until then, the sketch is inside it. Am I wrong?
I wanted to say: “exits” instead of “exists”, sorry