Still accept Serial communications whilst delay() is processing

Hi,

The way my code is set up is that my server sends the time to the arduino every second. It also sends other data and my arduino will perform a delay() as part of the processing. However, this causes an issue as the time backs up whilst the delay is running. When the delay is finished (after 3000ms), three time messages (sent every 1000ms) come through back to back.

This is an issue which could be solved with multithreading, by running the delay on another thread each time and leaving the main thread to still receive and process the time messages.

What's the best way to approach this?

The time message comes in the format eg. 'TIME_12:53' and when they come through back to back it's something like 'TIME_12:53TIME_12:54TIME_12:55'

void loop()
{
  if(Serial.available() > 0)
  {
    while(Serial.peek() > -1)
    {
      message += (char) Serial.read(); // read the entire message so no termination character is required
    }

    if(message.startsWith("TIME")
    {
        ...
    }
    else if(message.equals("eg. performDelay")
    {
        delay(3000);
        ...
    }

You might need to go for storing a reference value of time (using a variable for storing a time), and then use functions that work with time like micros() or millis() .... like... if current time minus reference time is less than some duration of time, then don't carry out an action..... but if the duration requirement is met...then carry out the action.

This allows you to not use the delay() function, which can really get in your way..... and still have a delay effect without the baggage/hassles that comes with delay()

See the "Blink Without Delay" example for some ideas on handling your timing without using delay.

I made a simple fix: update the time every 5 seconds. It was only being displayed as HH:mm anyway, so the 5 second delay ensures no more than one time messages gets sent at any one time.

Rixterz: I made a simple fix: update the time every 5 seconds. It was only being displayed as HH:mm anyway, so the 5 second delay ensures no more than one time messages gets sent at any one time.

Whether you update it every hour, minute, second or less it is better to use millis() rather than delay() for timing.

UKHeliBob: Whether you update it every hour, minute, second or less it is better to use millis() rather than delay() for timing.

Not to mention that the OP will eventually want to learn how to properly use millis() and understand the Blink Without Delay sketch. It is just a matter of time that these band-aids won't work anymore for a project.