I use serial monitor to enter SSID and password to make WiFi connection. If I connect next time to the same SSID I can only press Enter key without entering any data and Wifi connection is successful.
This code forces me to press enter key everytime I run program. What schould I do to pass after 10 seconds delay without pressing enter key everytime?
(edit)
I used Serial.setTimeout(10000) after Serial.begin and commented line while(Serial...
This way program waits 10 seconds for entering data and after this time goes on. Works.
void setup()
{
bool dataReceived = false;
Serial.begin(57600);
while(millis() < 5000)
{
if (Serial.available() > 0)
{
dataReceived = true;
break;
}
}
if(dataReceived == true)
{
// do what needs to be done with the data
}
}
When setup starts, millis() equals zero. The above loops for 5 seconds waiting for serial data. If data is received, a flag is set to true and and the while-loop is terminated (break statement).
Next the code checks the flag and takes action based on that.
Your approach will work as well, but I don't use blocking functions if it can be prevented and hence I don't use readBytesUntil().
The above approach also works if you want to wait for a while for a button press.
void setup()
{
bool buttonIsPressed = false;
pinMode(someButton, INPUT_PULLUP);
while(miillis() < 5000)
{
if(digitalRead(someButton) == LOW)
{
buttonnIsPressed = true;
break;
}
}
if(buttonIsPressed == true)
{
// do something if button was pressed within 5 seconds of start up
}
}