I want to know if it's possible to run two or more different program loops concurrently on an arduino?
I've implemented an event-based system that deals with several different tasks using specific durations for each event. The system works fine but one issue I have is that certain functions, specifically functions that connect to the wifi and to an mqtt server require the use of delay() while they're waiting for a connection and thus the program blocks in certain areas.
This is why I thought of having multiple threads...
Another solution would be to monitor the connection status without the use of a delay.
I already do this when using the ESP8266WiFiClass' scanNetwork() function which can run asynchronously.
WiFi.scanNetworks(true);
and I keep checking for the connection status with each tick.
Is it possible to do the same thing with the WiFi.begin() and the PubSubClient's connect() methods?
On any single-core microcontroller the way to have mutliple loops running is to have only one loop which is
void loop() itself
and whenever some part of the code shall not run a flag-variable is set to false
boolean initialWiFiBeginDone = false;
boolean check_If_WL_CONNECTED = false;
if ( !initialWiFiBeginDone) {
WiFi.begin("network-name", "pass-to-network");
check_If_WL_CONNECTED = true;
initialWiFiBeginDone = true;
}
if (check_If_WL_CONNECTED == true) {
// lines of code that check for wifi beeing connected or not
// and code that makes visible that code tries to connect
// and code for a timeout and if timeout occured
// inicating "no WiFi-connection"
}
The timeout has to be done non-blocking by avoiding a while-loop
remember if you want quick-responsive multi-tasking the only loop that is looping is
Thank you, this answers my question. I was under the impression that we couldn't perform any actions until the connection was made. I'll just keep checking the status until it connects.
I was going to continue writing more code for thread management on an Arduino micrcontroller, but then today I realised that most of it would already be written for me in the implementations of the functions, "setjmp" and "longjmp".
If I go on the Github account for 'glibc', I can navigate to:
sysdeps/arm/setjmp.S
sysdeps/arm/__longjmp.S
Inside these two Assembler files is everything I need to restore all the registers, restore the stack pointer and jump to an address in code -- but I can't find an implementation written in Thumb instructions.
With microcontrollers such as the sam3x83 or d21, can I temporarily switch from Thumb to ARM? So the thread manager could run in ARM instructions, and then the threads could all be Thumb. I'm reading one website here that says you use the BLX instruction to switch from Thumb to ARM, is that right? And then I can switch back to Thumb by executing "MOV PC,0x00".