Home » Blog » Christmas » IoT Controller Main Loop – Running in Circles

IoT Controller Main Loop – Running in Circles

iot controller main loop

Your IoT controller main loop is the heart of the matter. Running forever and responding to your commands.

Pretty much all of your computers have a main loop that continuously listens for events and triggers responses. In most cases, your main program loop is hidden in the operating system. For example, when you click your mouse, Windows OS gets a message identifying a mouse click and its source. The Windows main loop processes this message and triggers a response from the source program.

Since your Arduino or NodeMCU do not have an operating system, you need to write the IoT controller main loop yourself. It runs continuously, circling back every few microseconds. Here is the main loop coded in my antenna switch controller.

void loop()
/* Handle a firmware update, if any */

/* Confirm Online Status */

/* If a command is received... */
if ((ClientConnected) && GetClientData()) 

  /* Process the command */
  int m = ProcessCommands();

  /* Provide feedback on command success or failure */
  switch (m) 
    Respond("! Invalid Command");
    Respond("! Bad Parameter");
    Respond("! No Control");

First, we check to see whether a firmware update is coming in. If so, the loop pauses for the update and then our whole program reboots. All of this is handled by the OTA update library.

Second, we make sure that we are still connected to our WIFI client and whether a command has been received. If no commands pending, our loop just circles back to run again.

If a command has been received, it is dealt with by ProcessCommand() shown previously. You get an error code that lets you know if all went well, or not.

IoT Controller Main Loop – Delay versus Yield

Based on my insertion of delay commands, my main loop runs at a maximum of once every 300 millisecond, which is plenty fast enough to listen for new commands coming in.

So, what is that yield() command for? NodeMCU runs two processes. First is your program. Second is radio system on chip. You need to share the CPU cycles between these. Yield ensures that your firmware gives enough time for the WIFI to do its work without interruption.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.