Real-time operating systems for microcontrollers. Embedded systems and os for them

Hello, Habr!
Today I will tell you about such an interesting thing as operating system real time (RTOS). I'm not sure if it will be interesting for seasoned programmers, but I think beginners will like it.

What is an RTOS?

If we look at Wikipedia, we see as many as 4 definitions.
In short, an RTOS is an operating system that reacts to external events within a certain period of time. Hence, we can understand the main purpose of an RTOS - devices in which a quick reaction to events is required (however, in no case should the operation of an RTOS be confused with interrupts).

Why do we need it?

There are quite a few reasons for this.
First, the RTOS supports multitasking, process priorities, semaphores, and more.
Secondly, it is very lightweight and requires almost no resources.
Thirdly, we can get all of the above on almost any hardware (for example, FreeRTOS runs even on 8-bit AtMega).
And fourthly: just play and have fun.

Review of 3 well-known RTOS.

Attention: what follows is my personal opinion.
FreeRTOS
One of the most popular RTOS today. Ported to a huge amount of iron. Official site.
pros
1) Free
2) Ported to a large number of gland
3) Powerful functionality
4) There are various libraries: graphics, internet and more.
5) Good documentation.
Minuses
1) Quite a complicated process of porting to new hardware.

Conclusion: This is a truly professional RTOS with good documentation. It will be good for a beginner if there is already a port on his hardware.

KeilRTX
Until recently, this RTOS was commercial, but recently became open. Works on arm architecture only. Official site.
pros
1) Free
2) Easily ported to new hardware (within the arm architecture).
3) There are various libraries: graphics, internet and more.
Minuses
1) Working for Keil with her is almost impossible
2) Slightly stripped down functionality
3) Only arm is supported.
4) (on personal experience) Loses to many RTOS in speed.
Conclusion: ideal for beginners and small projects.
uc / os
Powerful commercial RTOS. Site .
pros
1) A huge number of functions and libraries.
2) Supports a lot of iron
Minuses
1) Commercial.
2) Difficult to use.

Conclusion: it is a stretch to call it an RTOS for a beginner.

Other interesting RTOS

RTLinux An RTOS based on regular Linux.
QNX RTOS based on Unix.

Features of development using RTOS

Well, first of all, you need to understand the following: RTOS is not Windows. It cannot be installed. This system is simply compiled with your program.
When writing programs with RTOS, functions in their usual sense are not used. Processes (or tasks) are used instead of functions. The difference is that processes, unlike functions, are infinite loops and never end (unless someone or he himself kills him - that is, unloads him from memory).
If several processes are enabled, the RTOS switches them, displaying machine time and resources one by one. This is where the concept of process priority arises - if two processes simultaneously need machine time, then the RTOS will give it to the one with the higher priority.
In RTOS there are special delay functions - so that time is not wasted during the delay of one process, the second is executed.
Now let's talk about such a thing as a semaphore - this is such a thing that controls a process's access to application resources. For each resource there is a marker - when a process needs a resource, it takes it and uses this resource. If there is no marker, then the process will have to wait for it to be returned. I will give an example: different processes send information on one UART. If there was no semaphore, then they would send bytes one by one and it would be a mess. And so the first process took the marker on the UART, sent a message and gave it to the second (and so on - ad infinitum).

Additional RTOS libraries.

RTOS often offer various libraries for working, for example, with graphics, the Internet, etc. They are really comfortable and you shouldn't hesitate to use them. However, remember that without the RTOS for which they are written, they will not work.
Here are some examples:
For RTX

What comes to mind when you hear an operating system? Surely vents, Linux, Macos .. or something like that. True, and when asked why it is needed, everyone will confidently answer: listen to music, play a game (on the Internet!), While talking with a friend on Skype. At the same time, contemplating how the LED flashes, having received a byte from uart =).

And if you dig deeper, listening to music, sending data over the Internet are all single processes, and since we have one processor, it can perform only one task at a time. Therefore, the tasks are performed alternately in small "portions", the essence of the OS is to do it imperceptibly for the user: so that the sound does not wheeze and the bikes go off and everything works at the same time. At the same time, if one of the tasks "hangs", then everything else continued to work.

If we discard all the extra buns and leave the bare essence, then first of all the OS is just a timer that counts down equal intervals of time, and also switches between tasks without user intervention, performs some part and switches again. You also need to take into account that most tasks may not have time to be completed in one time slice, so you need to save the state of the task at the time of switching to another, and the next time restore the state of the variables. All this is managed by the task scheduler.

There are two main types of operating systems: preemptive and cooperative. In the first case, switching between tasks will be "hard", i.e. if the time slice is 1ms, then first the first task will be executed for exactly 1ms, then the second for exactly 1ms, etc. Such axes are called real time (RTOS). For cooperative ones, it is a little simpler, the process itself must say that “I have fulfilled”, therefore they cannot be attributed to RTOS.

It will not work to push preemptive onto small AVRs for a reason small amount RAM. Of the available options for cooperatives, I liked mRTOS, you can read the details of this system on the author's website (easily googled). main reason its use - simplicity, availability of a ready-made version for CAVR, for understanding general principles the very thing.

So, the main questions remain, why and when to use the axis. In theory, everything is the same as what you do with the axis, you can do without it, because the resources are the same. From the fact that you adapt it to the project, megahertz will not fly into space, the iron will remain the same, therefore the resources are the same.

So it's worth asking yourself a few questions:
1.Can you manage your resources wisely?
2. Isn't it supposed in the process of writing the firmware to reinvent the same bicycle, similar to the scheduler?
3. How readable is your code? Are you able to open it in six months or a year and figure it out right away?
4. Do you write alone or in a group?

It is difficult to answer the first question, because it all depends on the developer's curvature. With the second, it is more and more clear, if there are many independent tasks and it is planned to perform them at regular intervals, then it is better to look towards the OS. With the third, it is also clear, it is much easier to understand a separate task than picking dependencies in the main loop. If you do not write alone, then there are also advantages here, because everyone can write their own problem separately, without interfering with the rest.

Combining the above, the scope of application is quite specific, for a certain range of tasks. You shouldn't shove it into every project. For most radio amateur crafts, the axis is redundant, but having an idea of ​​it before, I would probably have shoved it in a couple of projects.

Now let's take a look under the hood. To run mRTOS, you need to connect mrtos.c to the project and include mrtos.h. The structure of the code is slightly different from the usual

#include #include "mrtos.h" // here is the body of the function where we write our super code void task1 () (while (1) // tasks in any OS are built on the basis of an infinite loop { // here is the code of your task DISPATCH; // function of transferring control to the scheduler } ; } // timer interrupt handler 0 interrupt [TIM0_OVF] void timer0_ovf_isr (void) (char ii; #asm ("cli") TCNT0 = 0x9C; inc_systime (); for (ii = 0; ii< init_tasks; ii++ ) if (tasks[ ii] .delay ) -- tasks[ ii] .delay ; #asm("sei") } void main(void ) { // initialize peripherals Init_mRTOS (); // initialize the os // here we create tasks (tasks) 3 tasks have been created here create_task (task1, 1, Active); // create a task (task name, priority, status) create_task (task2, 1, Active); create_task (task3, 1, Active); Sheduler (); // start the scheduler while (1); )

#include #include "mrtos.h" // here is the body of the function where we write our super code void task1 () (while (1) // tasks in any OS are built on the basis of an infinite loop (// here is the code of your task DISPATCH; // function control transfer to the scheduler);) // timer 0 interrupt handler interrupt void timer0_ovf_isr (void) (char ii; #asm ("cli") TCNT0 = 0x9C; inc_systime (); for (ii = 0; ii

Now in more detail. the number of tasks is indicated in mrtos.h by the APPTASKS N. The task is declared inside task1 () (), task2 () (), etc. you planner. As you can see, the task consists of an infinite loop, this is normal and should be, but inside the task it is imperative to give control to the scheduler. Either the WAIT or DISPATCH function. If this is not done, then the task will run indefinitely.

How it works? Let's create an LED blinking task.

void task1 () (while (1) (PORTB.0 =! PORTB.0; WAIT (100););)

void task1 () (while (1) (PORTB.0 =! PORTB.0; WAIT (100););)

WAIT is a kind of analogue of delay () only, during the delay, the microcontroller does nothing and runs empty cycles. During WAIT, control is transferred to other tasks. Those. you can create a bunch of tasks by flashing different LEDs, with different WAITs, and they will all flash with different frequencies. If delays are not needed then DISPATCH is used at the end.

When using WAIT, it is important to understand that the entire system has a minimum tick (time slice), so we are not waiting for WAIT (50) 50 milliseconds, but 50 system ticks. The tick setting depends on how often Timer0 interrupts are called, i.e. if we set the interrupt to 1ms, then we can assume that our action will be completed within 1ms. Experiments have shown that it is possible to reduce the system tick to ~ 20 μs at a clock of 16 MHz.

The timer setting is no different from the previously studied one, since timer0 only has an overflow interrupt, then all settings are tied to this. In the latest versions of CAVR, it is very convenient to write time requiments, the settings will be automatically generated.

create_task (task1, 1, Active);

create_task (task1,1, Active);

With priorities, it's still pretty tricky. If there are two tasks with different priorities and a task with a high priority is constantly being executed, then we will never enter a task with a low priority. Therefore, you need to organize the work so that all tasks have access. We will not focus on this, we will save it for the next time. Task status, Active - started, stopped StopTask.

So, for those who want to just blink the LED:

#include #include "mRTOS.h" void task1 () (while (1) (WAIT (1000); PORTB.0 =! PORTB.0;)) // Timer 0 overflow interrupt service routine interrupt [TIM0_OVF] void timer0_ovf_isr (void) (char ii; #asm ("cli") TCNT0 = 0xb2; inc_systime (); for (ii = 0; ii< init_tasks; ii++ ) if (tasks[ ii] .delay ) -- tasks[ ii] .delay ; #asm("sei") } void main(void ) { DDRB= (1 << DDB7) | (1 << DDB6) | (1 << DDB5) | (1 << DDB4) | (1 << DDB3) | (1 << DDB2) | (1 << DDB1) | (1 << DDB0) ; PORTB= (0 << PORTB7) | (0 << PORTB6) | (0 << PORTB5) | (0 << PORTB4) | (0 << PORTB3) | (0 << PORTB2) | (0 << PORTB1) | (0 << PORTB0) ; // Timer / Counter 0 initialization// Clock source: System Clock // Clock value: 7.813 kHz TCCR0 = (0<< CS02) | (1 << CS01) | (1 << CS00) ; TCNT0= 0x83 ; // Timer (s) / Counter (s) Interrupt (s) initialization TIMSK = (0<< OCIE2) | (0 << TOIE2) | (0 << TICIE1) | (0 << OCIE1A) | (0 << OCIE1B) | (0 << TOIE1) | (1 << TOIE0) ; Init_mRTOS() ; create_task(task1, 1 , Active) ; Sheduler() ; while (1 ) ; }

#include #include "mRTOS.h" void task1 () (while (1) (WAIT (1000); PORTB.0 =! PORTB.0;)) // Timer 0 overflow interrupt service routine interrupt void timer0_ovf_isr (void) (char ii ; #asm ("cli") TCNT0 = 0xb2; inc_systime (); for (ii = 0; ii

As a bonus, I tried to make a polyphonic (two-voice) melody "Dr. Mario chill". The idea is that each leg of the controller is constantly inverted in a separate task, thereby generating a frequency. By changing the delay, you can change the pitch of the note.

void task2 (void) (while (1) (if (mute == 0) // if allowed to play(if (note_ch2 [n_n] == 0) // if there is a pause then wait, play nothing(PORTB.4 = 0; WAIT (5);) else (PORTB.4 =! PORTB.4; // if not pause then kick with the required frequency WAIT (note_ch2 [n_n]); ))))

void task2 (void) (while (1) (if (mute == 0) // if it is allowed to play (if (note_ch2 == 0) // if there is a pause then we wait, we do not play anything (PORTB.4 = 0; WAIT ( 5);) else (PORTB.4 =! PORTB.4; // if not pause, then kick with the required frequency WAIT (note_ch2);))))

I did not bother with the idea, in 1 task a meander is generated with a note frequency for the solo part, in the second for the bass. The pitch of each note is taken from the arrays. Duration, switching and termination in task 3.

void task3 (void) (while (1) (WAIT (1500); // play the minimum note duration for (mute = 0; mute< 500 ; mute++ ) // cut off the note so that they don't merge(PORTB.3 = 0; PORTB.4 = 0;); mute = 0; // set the flag that you can play sound n_n ++; // go to the next note if (n_n == n_max) // if we played everything then go in a circle(n_n = 0;)))

void task3 (void) (while (1) (WAIT (1500); // play the minimum note duration for (mute = 0; mute< 500; mute++) //обрываем ноту, чтобы не сливались { PORTB.3 = 0; PORTB.4 = 0; }; mute = 0; //выставляем флаг, что можно воспроизводить звук n_n++; //переходим на следующую ноту if(n_n == n_max) //если сыграли все то идем по кругу { n_n = 0; } } }

I used a simple scheme to mix the two channels.

Total small piece

For those who wish the firmware

I developed a little more than 10 electronic devices and completely dispensed with their low-level operation without an operating system. The situation changed when the functionality of the next device expanded dramatically. In addition, there is a need for a task that is called at specified time intervals, and the accuracy of the call affects the result. It also became clear that it would not be possible to write all the software in the allotted time, and it would be created later. After some thought, I realized that the project needed to include a real-time operating system (RTOS or RTOS).

Unlike a PC, where the OS is more of a layer for working with system resources, for an RTOS microcontroller it is primarily a task scheduler, in fact it plays the main role in "real time". At the moment, it is important for me to provide the so-called "pseudo-parallel" task execution. That is, there are several tasks with the same priority and it is important to call them in the specified order at specified intervals.

The following example is clear: in the Eurobot 2011 project, there were 18 peripheral devices in the system. 2 electronic boards could be combined into one in terms of functionality. Their cost would decrease, their reliability would increase (the number of components in the system would be reduced), and the amount of free space in the case would increase. The circumstance is complicated by the fact that the number of tasks grows proportionally and here you cannot do without the OS. RTOS also helps to avoid possible downtime of the processor, for example, during ADC conversion, you can block this task and perform others, thereby correctly distributing the work of the device. It is also important that now the device will not fall due to a failure in the task; instead, it is possible to maintain partial operability (although this may lead to unpredictable results). How do we ensure the growth of these indicators? In fact, we squeeze everything possible out of the MK, effectively using its computational capabilities.

After a short search, the choice fell on freeRTOS. This RTOS is distributed in C source and ported to 27 architectures. The last circumstance is decisive for me. It will reduce labor costs when working with MCUs from other manufacturers. Now I'm more interested in the port for the AVR.

The presence of RTOS freeRTOS in the project eats up about 9.8 KB of program memory and 1.8 KB of RAM. For example, for ATmega32 and the WinAVR compiler this is 60% and 85%, respectively. It is already difficult to create a device with great functionality for this model - there will not be enough memory. But this problem disappears with the newer AVR models. This is completely unimportant for the Mega2560 with its 256KB of program memory and 8KB of RAM. The trend of future MCs only accompanies the success of the RTOS.

Having skimmed through the Runet, I was surprised to find that there is no OS documentation in Russian. What is it! The original documentation is distributed at an additional cost. The situation was simplified by the article by Andrey Kurnits ( [email protected]) from the magazine "Components and Technologies". With the consent of the author, I will use the materials of the article in a revised version. His article may well serve as documentation in Russian. But the original is not available in printed form, the site of the magazine is lying, so the material will have to be slightly reworked. In general, the author has made an excellent article and there is no point in going over the theory again, it will be published in full here. The original article will be attached at the end of the publication. I also noticed that users were having difficulty compiling the RTOS. This is due to the fact that an external makefile is used, which contains the paths to the folders. Therefore, I will attach a finished project as a template for AVR Studio and AVR Eclipse. Unfortunately, the native makefile does not output debug information such as RAM and program memory usage, this had to be fixed by adding the appropriate standard call.

So, briefly about the need, it is advisable to use an RTOS in your project, if necessary:

Organize multitasking and alternate tasks

Ensure that the task starts at strictly defined intervals

Transfer information from one task to another

Add new tasks as needed

RTOS advantages over M TO:

  1. Multitasking. RTOS provides the programmer with a ready-made, debugged multitasking mechanism. In a simple case, each task can be programmed separately, all work can be divided among several team members. You don't need to worry about switching between tasks, the scheduler will do it.
  2. Time base. Time intervals must be measured. An RTOS must have this tool. It will allow you to perform actions at strictly allocated intervals.
  3. Data exchange between tasks. To do this, the RTOS uses a queue.
  4. Synchronization. If different tasks use the same resource, such as a serial port, then mutexes and critical sections can be used. If you need to perform tasks in a strict sequence or when a specific event occurs, you can use semaphores or signals to synchronize tasks.

Disadvantages of RTOS:

1. A sharp increase in the required program memory for the implementation of the kernel

2. Increasing the required RAM for storing the stack of each task, semaphores, queues, mutexes and other objects of the system kernel.

3. Delays when switching between tasks to save the context.

DescriptionfreeRTOS:

FreeRTOS is a free open source hard real-time OS. Mostly written in C, but there are assembler inserts. It was developed by Real Time Engineers ltd specifically for embedded systems. Recently, the SafeRTOS project has begun to develop - a modified, documented, tested and certified version of FreeRTOS for compliance with the IEC 61508 safety standard. This project was handled by a German company and now safeRTOS is used in the aerospace industry and medical technology. There is also the openRTOS project - a commercial version with a manufacturer's warranty.

Main features of freeRTOS:

1. Scheduler supports 3 types of multitasking:

Displacing

A cooperative

Hybrid

2. The kernel size is 9.8 KB compiled for AVR. (WINAVR)

3. The base of the kernel - 4 files in C.

4. Supports tasks and coroutines. Coroutines are specially designed for MCUs with a small amount of RAM.

5. Rich tracing capabilities.

6. It is possible to track stack overflow.

7. There are no software restrictions on the number of simultaneously executed tasks.

8. There is no limit on the number of task priorities.

9. Several tasks can be assigned the same priority

10. Advanced means of synchronization "task-task" and "task-interrupt":

Queues

Binary semaphores

Counting semaphores

Recursive semaphores

Mutexes

11. Mutexes with priority inheritance.

12. Support for memory protection module for Cortex-M3

13. Supplied in debugged form with demo projects for various platforms and compilers.

14. Free. Can be used in projects without disclosing source code under the extended GPL license.

15. Documentation is paid, but available online here.

16. The context switching time for AVR with quartz at 16MHz will be only 20.8 µs. This is exactly how much it takes to save data to the task stack and call the next one. (An interesting note, if you compare this with the PIC18xxx, then the AVR controller makes it 4 times faster !!!, most likely this is due to the quality of the compiler)

Preemptive multitasking means that a running task with a low priority is overlapped by a finished task with a higher priority. Switching between tasks occurs at equal time slices. Therefore, before the high-priority task can begin execution, the current time slice must have elapsed when the low-priority task is being executed.

Thus, the reaction time of FreeRTOS to external events in preemptive multitasking mode is no more than one time slice of the scheduler, which can be set in the settings. By default, it is 1ms.

If several tasks with the same priority are ready for execution, then the scheduler allocates one time slice to each of them, after which control is received by the next task with the same priority, and so on in a circle.

Cooperative multitasking differs from preemptive multitasking in that the scheduler itself cannot interrupt the execution of the current task, even a task with a high priority that is ready for execution. Each task must independently transfer control to the scheduler. Thus, the high-priority task will wait for the low-priority task to complete its work and return control to the scheduler. The response time of the system to an external event becomes undefined and depends on how long the current task will be executed before control is transferred. Cooperative multitasking was used in the Windows 3.x family of operating systems.

Preemptive and cooperative multitasking concepts come together in hybrid multitasking, where the scheduler is called every time slice, but unlike preemptive multitasking, the programmer has the ability to force this in the body of the task. This mode is especially useful when it is necessary to shorten the response time of the system to an interrupt. Suppose that a low-priority task is currently being executed, and a high-priority task is waiting for some interruption to occur. Then an interrupt occurs, but at the end of the interrupt handler, execution returns to the current low-priority task, and the high-priority one waits until the current time slice ends. However, if after the execution of the interrupt handler, control is transferred to the scheduler, then it will transfer control to a high-priority task, which can reduce the system response time associated with an external event.

Whyonchatb?

You can start developing a microcontroller device running FreeRTOS by downloading its latest version.

The FreeRTOS distribution is available as a regular or self-extracting ZIP archive. Distribution Contains directly the kernel code (in the form of several header files and files with source code) and demo projects (one project for each development environment for each port). Next, you should unpack the archive to any suitable location on the development station.

Despite the large number of files in the archive, the directory structure is actually simple. If you plan to design devices on 2-3 architectures in 1-2 development environments, then most of the files related to demo projects and various development environments will not be needed.

The detailed directory structure is shown in the diagram.

All kernel source code is located in the / Source directory.

Content:

1.tasks.c- implementation of the task mechanism, scheduler

2. queue.c- implementation of queues

3. list.c- internal needs of the scheduler, but the functions can also be used in application programs.

4. croutine.c- implementation of coroutines (may be absent if coroutines are not used).

Header files that are in the directory source / include

1.tasks.h, queue.h, tist.h, croutine.h- header files, respectively, for the files of the same name with the code.

2. FreeRTOS.h-contains preprocessor directives for configuring compilation.

3.mpu_wrappers.h- contains overrides of the FreeRTOS programming interface (API) functions to support the memory protection module (MPU).

4.portable.h-platform-dependent settings.

5.projdefs.h-some system definitions

6.semphr.h- defines API functions for working with semaphores, which are implemented on the basis of queues.

7. StackMacros.h- contains macros to control stack overflow. Each hardware platform requires a small piece of kernel code that implements FreeRTOS's interoperability with that platform. All platform-specific code is in the subdirectory / Source / Portable, where it is categorized by development environments (IAR, GCC, etc.) and hardware platforms (for example, AtmelSAM7S64, MSP430F449). For example, the subdirectory / Source / Portable / GCC / ATMega323 contains the files port.c and portmacro.h that implement saving / restoring the task context, initializing the timer to create the time base, initializing the stack of each task and other hardware-dependent functions for the mega AVR family of microcontrollers and the WinAVR compiler (GCC).

Separately, you should highlight the subdirectory / Source / Portable / MemMang which contains the files heap_l.c, heap_2.c, heap_3.c, which implement 3 different mechanisms for allocating memory for the needs of FreeRTOS, which will be described in detail later.

The / Demo directory contains ready-to-compile and build demo projects. The common part of the code for all demo projects is highlighted in a subdirectory / Demo / Commo n.

To use FreeRTOS in your project, you need to include the kernel source files and related header files. There is no need to modify them or understand their implementation.

For example, if you plan to use the port for MSP430 microcontrollers and the GCC compiler, then to create a project from scratch "you will need subdirectories / Source / Portable / GCC / MSP430_GCC and / Source / Portable / MemMang... All other subdirectories from the / Source / Portable directory are unnecessary and can be removed.

If you plan to modify the existing demo project (which, in fact, is recommended at the beginning of the FreeRTOS study), then you will also need subdirectories / Demo / msp430_GCC and / Demo / Common... The rest of the / Demo subdirectories are unnecessary and can be removed.

When creating an application, it is recommended to use makefile(or development environment project file) from the corresponding demo project as a starting point. It is advisable to exclude from the build (build) files from the / Demo directory, replacing them with your own, and files from the / Source directory - intact. The header file should also be mentioned FreeRTOSConfig.h found in every demo project. FreeRTOSConfig.h contains definitions (#define) that allow configuring the FreeRTOS kernel:

1. A set of system functions.

2. Using coroutines.

3. The number of priorities of tasks and coroutines

4. Sizes of memory (stack and heap).

5. Clock frequency of MK.

6. The period of the time scheduler allocated to each task of execution, which is usually equal to 1 ms. Disable some system functions and reduce the number of priorities (reduces memory consumption).

The FreeRTOS distribution also includes tools for converting trace information received from the scheduler into text form (directory / TgaseCon) and license text (directory / License).

conclusions

With the help of the first article in the series, the reader got acquainted with the operating system for FreeRTOS microcontrollers. The features of the work are shown. Describe the contents of the FreeRTOS distribution. The basic steps to start developing a device running FreeRTOS are given.

In future publications, attention will be paid to the multitasking mechanism, namely tasks and coroutines. An example of the scheduler will be shown using the example of Atmel AVR microcontrollers and the WinAVR compiler (GCC).

I constantly ask this question, while doing my hobby - developing a home automatic control system (smart home) based on a 16-bit microcontroller - is this really the right approach? A month and a half ago, I already wrote in my blog on the topic "Microcontrollers versus systems-on-a-chip." So, I'm going to write about it again.

In part, I was motivated by the release of the Stellaris Launchpad and the Arduino Due. They are both based on 32-bit microcontrollers and are very similar in many ways. I have studied the datasheet for both, and although they differ decently in price, they are designed for one target audience. I thought that maybe I should switch from MSP430 to Stellaris, or maybe even switch to a fundamentally different system, use something like Raspberry Pi instead of microcontrollers.

Both Stellaris Launchpad and Arduino Due are very powerful, but not designed to run Linux. They run either on executable code written directly for them, or under the control of a real-time operating system (RTOS), a minimalistic OS with very short response times to external events. They are both significantly more complex than the MSP430 or 8-bit AVRs.

On the other hand, in real life (outside the internet), most people I know use Raspberry Pi or other embedded Linux systems. The use of microcontrollers is a rather rare case among those whom I have met. Even Arduino is much less popular in my environment than embedded Linux. As I understand it, why would anyone buy an Arduino when you can get a Raspberry Pi, which can do much more, but costs the same or less? There is a huge amount of ready-made software for Linux, and you can program on it using simple scripting languages.

For me personally, the reason I don't want to use Linux is because I use it every day at work, and when I get home, I don't have the pleasure of having to work on Linux-like systems again. I have no problem using Linux, but there is too much of it all over the place, it weighs me down. It is much more interesting for me to work with simple electronic devices on 8/16-bit microchips.

However, I do not turn my back on reality. If I want to stay in tune with the real world, I have to use the tools that are used in the real world. Otherwise, it is like wanting to drive a car with a steam engine, just because the internal combustion engine is too mundane, so I use it all the time. If the world around us is switching to a more advanced technology, it is necessary to master it, whether I like it or not. Especially if I want my blog to be interesting to people and remain relevant.

In my smart home project, I actually ran into this problem. I have already made a LAN driver for the control system on the MSP430 and everything looks very decent. Basically, I can do whatever is needed for an automation system on the MSP430. However, I wonder if the way I do it is correct? Am I trying to eat soup with a fork when there is a spoon? Maybe Linux is a better system? Let me explain.

If we stop and look at the current situation, in terms of technological advances for November 2012. I ask myself, are microcontrollers good and relevant enough compared to systems-on-a-chip using Linux?

If you list the projects on embedded systems that come to my mind, these are: drones, robots, home automation, motor controllers, sensors, wristwatches, 3D printers, etc. In which of these cases is embedded Linux better than microcontrollers? And why?

I believe that there are three situations when a microcontroller is the best choice: where instant (realtime) response to events is important; where extremely low energy consumption is required; and where you need to use chips of the lowest possible cost.

For a start, the use of cheap microcircuits is not so important for me. I do my hobby for myself and do not intend to ever release competitive products. I don’t have to think about moving production to a slave labor plant to be competitively priced for the small projects I develop. I would be happy if I could solder more than one board a day, thanks to my abilities!

For example, for a smart home project, I can design a remotely controlled switch. It can turn on / off lights or something else. At the same time, I can go to my local electrical store and buy the same for $ 20, made in China. Will I ever beat that price by trying to sell my own switch? I don’t think it’s possible.

If you think about it, this also applies to a lot of other things needed for home automation. Sensors for temperature, smoke, movement, etc., I am quite capable of making the same myself, but it is unlikely that financial benefits can be derived from this. Who cares to buy such things from me for $ 75 when they can find them for $ 20 in Household Products?

If you are thinking about deriving some benefit from your hobby, then it is better to pay attention to more expensive and complex products. For example, a home automation controller or thermostat usually costs more than $ 100, and leaves more freedom for individual creativity, you can build one, sell to your neighbors, and even make money from it.

But wanting to get a better price for the final device doesn't mean using the cheapest microcontroller on earth. In fact, this is a bad idea because the development time has the same cost as the parts used. The microcontroller may be cheap, but it takes more time to write the control code. Time is money, and if you work faster, you can achieve more.

All these reflections lead me to the conclusion that it is more profitable to develop a smart home system on Linux than on microcontrollers, despite my personal preferences, not to use Linux (I like low-level programming more than scripts, Linux makes me bored).

Returning to the topic of the topic, the price of microcontrollers, this can be an important factor for large corporations about to release a new product, but on an individual level, if you try to run a business in the Kickstarter style, this factor is not so important, in fact, the fast development time. more important than the cost of the components.

On the other hand, microcontrollers can be a better choice than systems-on-a-chip when low power consumption is required. In such systems, there are two points: low consumption of the circuit itself, during operation, and a short start time. A typical battery-saving method for small devices is to shut off itself. When you turn off your Linux computer, it takes a decent amount of time to get back to work, sometimes up to a few minutes. This time is not acceptable for embedded systems.

If you take a microcontroller like the MSP430, it can run for years on a single battery. Stellaris Launchpad and Arduino Due, in principle, are capable of this, they consume more power than the MSP430, but still very little compared to the Raspberry Pi. Also, the MSP430 can instantly start after shutdown.

Thus, I am absolutely confident that in all situations where low-voltage operations are required, it makes sense to use microcontrollers. There are a wide variety of battery operated devices available where the need arises.

In the third case, as I already said, using a microcontroller is more meaningful than Linux, in operations requiring instant response (realtime response). I mean devices like 3D printers and CNC machines, I know what I'm talking about because I have devoted a lot of time to studying them. By their nature, they require a high degree of precision in their work, which depends slightly less than entirely on the response time to commands.

For example, if you are running a circular saw that is currently cutting off a piece of wood or metal, you cannot stop the process, due to the fact that the computer that controls it needs a pause to flush the data from memory to disk or something otherwise in the same spirit. Anyone who has used a PC is familiar with the occasional freeze that occurs intermittently during normal use. Now imagine that you have a large drilling machine, running a PC, which suddenly starts checking for updates for Windows, while working, and the drill is drilling through the table on which it stands, because the computer lost control of her.

PCs and systems-on-a-chip are not designed to work in real time, even with Windows, even with Linux, but of course they are trying to get close to this. As an example, there is a real-time patch for the Linux kernel, and a special CNC software built to do this kind of work. I'm not familiar enough with this Linux patch to know how flexible it is to fully control real-time events. But I think that this is only a possible alternative, since Linux, no matter what patches are hung on it, will never beat microcontrollers in this area, thanks to their interrupt system.
In conclusion, I want to say that I spent a lot of time trying to find areas where the use of microcontrollers in my projects has an advantage. And it looks like the era of world domination of the Raspberry Pi and the Beaglebones has come. This is the current situation in the DIY community. In most cases, it is faster and easier to develop on these systems, so it is often the best choice for most projects.

For microcontrollers, only the areas of low-voltage devices, real-time operations, and low-cost devices remain.

It doesn't depend on what microcontrollers might seem "more fun" than PCs. This is something that you have to come to terms with.

Translation from English of the original post