What is the preferred way to "wait" for something to finish in the Application code?


What is the preferred way to wait for something to finish? i.e. turn on a switch for [x] amount of time and turn off the switch after [x] amount of time? I am currently using delay() and it seems like a bad way to do things given pausing the processor can lead to unforeseen problems down the road in the application code.

pinMode(D0, OUTPUT);
digitalWrite(D0, HIGH);
Serial.println(“delaying for ten seconds”);
digitalWrite(D0, LOW);
System.sleep(SLEEP_MODE_DEEP, 30);

Any help/guide is appreciated, I am using the BoronLTE & Electron3G for this application.

I am currently using delay() and it seems like a bad way to do things

I would agree with your statement. In general, things don’t work so well once the loop cadence/velocity slows down. Obviously putting a delay() in the loop halts it all together. This is OK for very short periods (1-10 mSec) but not good for seconds.

Solution all depends how complicated your app logic is. A better way (IMO) to manage this is to implement a Finite State Model (FSM) - search on the community for many good posts about this. Within the states you then have one state for the normal looping (could call this STANDBY) and another for the waiting (WAITING_TO_DO_X). If within STANDBY a switch is turned on, then a timestamp is recorded e.g timestart = millis(); and the state is set to be WAITING_TO_DO_X. The controller for WAITING_TO_DO_X state does not block with delay it just tests millis() - timestart >= delay_period and when true will set the state to STANDBY, perform the action, i.e. turn off the switch. You could avoid using FSM and set timestart = 0 to mean not in waiting and thus only test for delay when timestart > 0.


Software Timers are another option.

For high precision or very rapid timing you can use hardware timers via SparkIntervalTimer (only Gen1&2 - currently not available for Gen3 Argon, Boron, Xenon).


Thank you for the thorough reply!
While here, what’s the preferred way of clearing all application firmware on the electron & boron?

I keep this post handy.


I guess just flashing a new user application to the device. You could use the default “tinker” application which is a known working, generic program that comes on all devices from the factory. I don’t think there is a factory reset on Electron and Photon… There is on Gen 3 devices but fresh from the factory, the memory location for factory reset is blank and therefore doesn’t work out-of-the-box. You have to put known working code in the factory reset location if you want to use that feature. (I can’t find the factory reset info in the docs so hopefully I’m correct.)

1 Like