Electronic – Do microcontrollers support threading

microchipmicrocontrollerrtosthread

It has been a while since I took "Embedded Systems" course where we studied "Super-Loops", "RTOS", Semaphores, Multitasking (cooperative vs premptive) so sorry for this question.

We have an an application where we have an ADCinterface to a number of signals and where we are sending SMS at the same time. We are using super-loop. The problem is:

When we are sending SMS's, the rest of application has to wait on it.

My question is: do microcontrollers (32 bit PIC, ARM or 8051 based etc) support threading so that one thread can take care of SMS while we read ADCs in a separate thread, or it is just a matter of using RTOS which supports multi threading vs super-loop which does not?

Best Answer

As long as the microcontroller supports interrupts, has enough memory and gives you full control over the state which the CPU assumes (program counter, registers, stack) when you return from an interrupt, full fledged preemptive multitasking is possible. This is generally accomplished by setting up a hardware timer to generate an interrupt at regular intervals, and context switching (AKA changing the currently executing task) in the interrupt service routine (by backing up the registers and stack of the currently running task to RAM, restoring the previously backed up state of another task from RAM and returning from the interrupt). Most microcontrollers can do this, albeit some 8-bit microcontrollers have insufficient RAM for saving the state of multiple pending tasks (like some ATtiny and PIC parts).

Whether or not this is practical is a completely different story. It introduces a lot of extra complexity, some overhead but perhaps most importantly unpredictable timing to the firmware.


I think your problem is better solved with cooperative multitasking (super loop). You just need to refactor the SMS code into a non-blocking form (think state variable + switch statement), so that transmitting a SMS doesn't block the CPU from running your ADC code. Essentially you must remove all blocking code (delays, polling loops) from both your ADC code and your SMS code.

Even simpler would be to just service the ADC in a conversion complete interrupt. This way you can send the SMS with a simpler, blocking driver implementation (programmed as a sequence of steps, branches and delays instead of an explicit state machine), while the ADC is still handled transparently in the "foreground" by your interrupt handler.