How does the main while loop trigger/work in C?

Thread Starter


Joined Feb 28, 2023
I am trying to visualize the main while loop and the way it works. I have written some code that toggles a PIN and then attached an oscilloscope to visualize the output. It was not a very nice one - it definitely did not look the same as I would get from a global interrupt. Something like this: (lower one is the interrupt)

I recently had a little problem where I had an interrupt that took too long and thus the code was never going back to the main while loop. That got me thinking what triggers and defines the main while loop? How would it look like in a graph similar to the one I free-drew above? Hopefully my question is understandable :)


Joined Feb 24, 2006
This implies, to me at least, that the main loop takes a variable and unpredictable amount of time to do the tasks in the main loop and return to the toggling of the pin. If you want to make you main loop behave like a periodic interrupt, then you can do that, but it takes a great deal of time and effort to make all paths through the code take the same amount of time. There is normally no pressing reason to do this.


Joined Oct 2, 2009
There are a number of possible options.

(1) You can have an endless empty loop written as:


This suggests that all operations are interrupt driven. When an event occurs, an interrupt is triggered and the ISR (interrupt service routine) takes over and executes the desired operation. This is commonly used in RTOS (real time operating systems) where any number of processes can be in line waiting to be executed.

(2) You can have a process being executed in the foreground:
... process goes here ...

This is a typical way to run an application, even with interrupt driven events. An interrupt event may simply set a request flag so that the main process knows when to execute the required task.

(3) Another example is in low power battery operated systems where the processor can be placed in SLEEP or STOP mode.
The processor is awaken by an interrupt event and then put back to SLEEP or STOP. This minimizes power consumption demanded from the battery.


Joined Jan 30, 2016
I'm surprised at your description. Are you saying the edges of your pin's waveform were sloping? Are you sure it was configured as an output? What were you using as a delay mechanism? Can you post your code?

Depending on your microcontroller the impact of an interrupt that takes too long will vary. In the case of an Arduino it will eventually return to the main loop once the interrupt routine exits - of course if it never exits....

For ESP8266 or ESP32 a watchdog timer (WDT) will throw an exception and reboot the processor if things take too long. (Arduino doesn't have one by default but you can set one up).