Hello everybody,
this is an introductional tutorial for newcomers to understand how writing code can be done to achieve:
- buttons beeing responsive to buttonpresses all the time
- blinking multiple LEDs with different frequencies
- executing multiple actions of any kind in (almost) parallel
by using state-machines and non-blocking timing.
You need quite some knowledge and more than one concept to do this.
Because of this amount of knowledge and the mutliple concepts,
it takes more time that just 5 minutes to understand this.
If you are searching for a quick solution - I'm serious - skip this tutorial and try your luck to find a ready to use code. Though the probability to find what you need exactly is very unlikely.
Right from the start: get a clear picture of the different way of code-execution.
It will help a lot if you get a clear picture how code-execution proceeds
differently
from line to line if you code state-machines and non-blocking timing.
one attempt is to look at this video of a mechanical animated lego-scene
There is one single crank-wheel that keeps rotating to make all actions go on all the time. The crank wheel drives everything
There is one single "motor" that drives everything.
In translated to programming there is one single function that keeps all details proceeding.
This one single function is void loop() itself.
As long as void loop() is looping everything is in motion.
In the lego-scene there are three chains that are driven by the one single crank-wheel.
(picture missing yet)
all three chains are driven by the one single crank-wheel.
There are levers mounted on the chain. If the chain keeps on moving the levers push/pull other parts of the mechanic making other parts do some action. These actions are done only from time to time in a periodic manner. There are pauses between these actions
while the crank-wheel keeps spinning all the time.
This is what state-machines combined with non-blocking timing does:
void loop() is looping FAST all the time but actions only occur if certain conditions become true.
This Lego-example shall show the "it is always spinning = void loop() is always looping
And of course this example has its limits and in coding some things are different.
Using delay() in your code equivalents to stop spinning the crank-wheel.
If you would stop spinning the crank-wheel the whole animation stops.
And this is the reason why you can't use delay() in non-blocking code
for the same reason you can't use while-loops or for-loops.
A while-loop or a for-loop is like you disconnect the rest of the mechanic driven by the crank-wheel to make just one chain moving and only after finishing the while-loop reconnect the rest of the mechanic again. The rest of the mechanic would stay stopped until you re-connect the rest.