FreeRTOS or other OSes for MCU, practicalities of it - Page 1
Forum section: electronics / general

author: Simon
author_rank: Unknown
timestamp: September 15, 2014, 08:27:22 am
content: I'm looking to use larger MCU's for speed mainly. As projects get more complex I am wondering if some sort of operating system will help, maybe freeRTOS ? basically my question is what does the OS do, does it help setup the chip or would it be a peice of code that runs alongside mine and manages the timing of it ?Basically what OSes should I consider and will they give me any simplicity in my projects ?

author: tggzzz
author_rank: Super Contributor
timestamp: September 15, 2014, 10:17:12 am
content: Quote from: Simon on September 15, 2014, 08:27:22 amThose questions will be answered in general by reading any standard introductory text (on a manufacturer's website or a magazine/web article) about RTOSs. For individual RTOSs, you will have to RTFM.It will be easy to determine whether a specific CPU/MCU is supported; if so I would expect it to configure the memory, timers, and other low-level hardware. But a CPU/MCU is only part of a system.Questions that you might like to focus on:does the RTOS support the peripherals in your hardware; e.g. having "ethernet support" is insufficient since you also need drivers that support the particular ethernet chip/corecharacterise your application in terms of how many tasks/activities are asynchronous w.r.t. each other, and any necessary synchronisation between tasks/activitiescharacterise your applications computational and i/o timing constraintsIf you can't do that then you are not in a position to use an RTOS.Given time and the ability to learn through experience, you might like to implement your project, and then reflect on the pain points. Then use 20:20 hindsight to assess whether what features of an RTOS might lessen the pain next time around.QuoteThey will simplify some aspects of your code at the expense of complicating others; typically small simple projects will not benefit. Where the tradeoffs lie will depend on your application, your hardware, and your experience; a general answer is not possible.

author: Simon
author_rank: Unknown
timestamp: September 15, 2014, 10:38:26 am
content: I've been reading the FreeRTOS website and not got far as it talks a lot about the code used in the RTOS and how it works in itself but nothing about how it interacts with my code and hardware which is what I'm trying to understand. I'll keep digging around.

author: tggzzz
author_rank: Super Contributor
timestamp: September 15, 2014, 11:19:17 am
content: Quote from: Simon on September 15, 2014, 10:38:26 amThat website assumes you know what an RTOS is. It states its features and presumes you can understand them in terms of standard RTOS terminology, operation and use.That's quite reasonable, but you want/need an "RTOS for dummies" intro. ( Sorry, I don't have time to find one for you now.) You wil best be able to learn from such an article if you have an understanding of the pain points in systems without an RTOS - and hence what RTOSs do and don't do.

author: Kjelt
author_rank: Super Contributor
timestamp: September 15, 2014, 11:30:32 am
content: HW eng. going SW, I do encourage the effort but tggzz is right you need to start with reading first, you also do not ask a question on this forum about a specific chip without at least having read its datasheet now do you?http://en.wikipedia.org/wiki/Real-time_operating_system

author: Kjelt
author_rank: Super Contributor
timestamp: September 15, 2014, 11:32:44 am
content: aaah google "RTOS for dummies" is your bestfriendbethttp://www.cis.upenn.edu/~lee/06cse480/lec-RTOS_RTlinux.pdfhttp://www.iar.com/Global/Resources/Developers_Toolbox/RTOS_and_Middleware/Basic_Concepts_for_Real_Time_Operating_Systems.pdfhttp://documentation.renesas.com/doc/products/tool/apn/res05b0008_r8cap.pdf

author: Simon
author_rank: Unknown
timestamp: September 15, 2014, 11:40:37 am
content: I think I was relatively clear that I'm not expecting to implement an RTOS in a project tomorrow and that I'm just looking about at the minute trying to understand implications and if i should really use one. Thank you for your suggestions, I was starting to wonder if there was something I was missing as the FreeRTOS website does seem to go over my head, I'll step back and start again.

author: eurofox
author_rank: Unknown
timestamp: September 15, 2014, 11:55:41 am
content: Quote from: Simon on September 15, 2014, 11:40:37 amSimon,I wrote from scratch an RTOS in assembly long time ago when this kind of tool was not available.When you have an application where you can manage all control in one main loop (all inputs and outputs) you don't need an RTOS and sometimes help with interruptsWhen you program start to be to complicated and that you need to manage several task in background then you better use an RTOS

author: nctnico
author_rank: Super Contributor
timestamp: September 15, 2014, 01:15:37 pm
content: I never used an OS on a microcontroller. I did look into it but when running several tasks in parallel using timeslicing causes all kinds of thread synchronisation issues for shared data. Those are difficult to control without planning an application properly.I usually run high priority processes from a timer or hardware interrupt. An interrupt does more or less the same (save the state and go to a different process) as when an OS halts a process and hands over the next timeslice to a different process.Many realtime OSses can be configured to do scheduling which means running a process until it decides it no longer needs the CPU. This makes it easier to do thread synchronisation for shared data but it still needs attention. So far calling a run function from a loop in main for each software module has served me well. The only time I could have used an OS was when a particular calculation too long and I was not able to divert some of the CPU load into an interrupt.

author: Simon
author_rank: Unknown
timestamp: September 15, 2014, 01:19:16 pm
content: My thinking is sort of along the same lines

author: legacy
author_rank: Super Contributor
timestamp: September 15, 2014, 02:29:43 pm
content: me, too

author: Kjelt
author_rank: Super Contributor
timestamp: September 15, 2014, 03:03:28 pm
content: If you have only a few simple tasks or a slow microcontroller (8 bits) you can use a superloop and ISRs.If you have a powerfull 32 bits microcontroller that has a lot of tasks or apps to run and some can take a long time to run an RTOS is the (only) smart way to go.All in between suit yourself.I personally think it is a waste if you are using fast 32 bit microcontrollers and do not (want to) know about RTOSs.We have a saying here in the Netherlands: "a farmer won't eat anything he does not know", so at least take some good bites of it and see how it tastes.

author: coppice
author_rank: Super Contributor
timestamp: September 15, 2014, 03:04:55 pm
content: Go for the clear market leader - NoOS!

author: Simon
author_rank: Unknown
timestamp: September 15, 2014, 03:08:23 pm
content: Quote from: coppice on September 15, 2014, 03:04:55 pmhaha, well at the moment that seems best but there may come a time.

author: Marco
author_rank: Super Contributor
timestamp: September 15, 2014, 03:14:21 pm
content: The OS probably won't help much, the code to access the peripherals might if it's good quality.

author: tggzzz
author_rank: Super Contributor
timestamp: September 15, 2014, 03:47:43 pm
content: Quote from: nctnico on September 15, 2014, 01:15:37 pmAn RTOS will be of zero help there, and at best might allow you to believe the problems have gone away.A key is to get the very high level application structure stable and predictable. There are many real time "design patterns" which have stood the test of time - use them and don't reinvent a (square) wheel.Good starting points are to considerall inputs as discrete events,inter-task communication consisting of one task depositing a discrete message in a queue (with capacity=1 is called a mailbox), and another task (or tasks) pulling messages from the queue as they become availableeach task takes an event from a queue/mailbox, processes it, then goes back to sleep until there is another event in the queuewhen the RTOS detects a queue/mailbox contains an event then it schedules the task waiting for the eventQuoteRule of thumb: if correct (albeit untimely) behaviour depends on high/low priorities, then there's almost certainly a problem lurking and waiting to be discovered. Beware "priority inversion" e.g.http://en.wikipedia.org/wiki/Mars_Pathfinder#On-board_computerAll an interrupt should do is respond to the input stimulus and deposit the corresponding event in a queue/mailbox, so that a task can act on it.QuoteToo simplisitic. You need to understand the relative advantages of cooperative multitasking and preemptive multitasking.Curiously hardware bods are usually in a better position to "think in parallel" than traditional software weenies.

author: Jeroen3
author_rank: Super Contributor
timestamp: September 15, 2014, 04:51:06 pm
content: An operating system might help modularise your application. However, the lines between the modules become more complex.It's quite easy to share a GUI task from a control loop task since they only produce and consume data one way relative to each other.But, what happens when you want both tasks to write data to the serial bus?In general, using anoswith plenty of time in idle-loop is not that hard, but whenever a task requires (or is able to consume) more than 100% of the assigned cpu time, your software design, priorities and preemption are all that sit between hanging and running. Here is were the RT (realtime) part of an RTOS moves in.With an RTOS you are able to guarantee (by design) that an action will be performed at least x time from the event. Such as:- An ADC conversion event will be given to the DSP task who will complete calculations within time for the output stage to react.- A user input event will reach the GUI task within a second.- A pin interrupt event (which are usually of the utmost importance) will be given to the safety task the at the next schedule or immediately if preemption is allowed.For example, in your average threaded blinky example. Replace in one of the threads the "sleep" function for a for-loop delay and increase the priority with 1.

author: Kremmen
author_rank: Super Contributor
timestamp: September 15, 2014, 05:38:34 pm
content: Quote from: Simon on September 15, 2014, 08:27:22 amSome OSes will include a HAL (Hardware Abstraction Layer). ChibiOS is one. They will help you operate some or all of the MCU peripherals as abstract entities on the OS level without messing with the actual iron.As to timing, all RTOSes have some kinds of timing functions, at least various non-busy waits.The OS code does not really "run alongside" your code, instead the OS provides a library of functions managing creation and manipulation of what is usually called tasks, and communication between those tasks. Simple as it sounds, it is a very powerful concept when done properly.Basically your code is divided into tasks, each one handling a specific feature or function of the application Thus there might be input and output tasks, a user interface task, various communication tasks to connect the application to the outside world, and signal processing tasks doing the number crunching or similar stuff. All of these tasks need to exchange information with each other and sometimes control the execution of things by putting tasks to sleep or waking them up. For this purpose all OSes implement a set of intertask communication methods such as queues, semaphores and mutexes and there are others.A decent RTOS will also definitely include interrupts in the supported features such that communication from interrupt context to the scheduler is possible. A scheduler is the "core" of the RTOS, and it is the scheduler that grabs control from an executing task, switches the processor context to some other task and restarts (or continues) that task from where it left off last time. As a rule control is given to the highest priority non-blocked task or, if there are multiple such tasks then they are alternated round robin or some other "fair" priority rule.The context switch can be either cooperative or pre-emptive. In the first case a task must explicitly yield either directly or by issuing an OS call that results in a context switch. A pre-emptive scheduler has a master clock ticking at a predetermined rate. Each tick wakes the scheduler that will then switch context all by itself if the switching conditions are met.The end result is that you implement the app as a set of procedures that become the tasks under the OS once they have been "created". Usually you also create a set of OS queues and hand them to the tasks so they can talk to each other. Upon task creation (usually but not necessarily in the main program) the OS core allocates a stack for each task an initializes that stack (creates the initial running context in that stack). This way the tasks are allocated one by one and when the scheduler is started it switches the running context to the first task and the application proper starts from there.Additionally, OSes always have functions to allocate and free dynamic memory (yes yes, but let's not go there). Some understand about memory protection and so on and so on.While you can get a long way with the NoOS option, getting to know at least one common RTOS is decidedly a clever move if you ask me. Basic usage is if not trivial then entirely easy and produces predictable results as long as certain minimum sanity measures are kept in place (stack size for tasks and similar)QuoteFreeRTOS and/or ChibiOS. There is a learning curve (reasonable). The code complexity and size will start at some nonzero level but the growth rate will be slower than for the NoOS option. In the end yes, they do give you simplicity but not at the trivial low end. The blink-a-led app won't get that much from an OS.

author: nctnico
author_rank: Super Contributor
timestamp: September 15, 2014, 05:50:17 pm
content: @Kremmen: if I want all that I use an embedded Linux board.

author: Jeroen3
author_rank: Super Contributor
timestamp: September 15, 2014, 08:52:36 pm
content: I'm not familiar with freertos(due to it being free with *'s).But I have with ChibiOS. Which is a quality piece of C code. It's hard to follow at first, because of the highly portable and objectified implementation. And the inheritance method it's using. Yes, class inheritance in C. A real challenge for your IDE to follow as well.But when you're used to the style used, it is a high quality versatile tool to put in your toolbox. And your inspiration box.Note that you're not obligated to use the HAL (hardware drivers). You can work with only the kernel.Our university let us play with lubuntu, threading ,forking and semaphore stuff etc.. and "nice" values. Which is difficult at first, but essential to know.Oh, and never go Dining with Philosophers.Please also note that an RTOS isn't by default realtime. You're design must provide this, the OS is just the tool.

author: tszaboo
author_rank: Super Contributor
timestamp: September 15, 2014, 09:55:04 pm
content: I really suggest, if you really want to work with RTOSes, than cook your own RTOS. It is really not that much science. Just take the features that you want. Code them or use someones code snippets. You are done, it can take maybe a few weeks. But if you spend that time writing the scheduler, the messaging system, the memory allocation, the hardware allocation, starting tasks, making coherent memory... You will understand it.Without it, you will be like the newbee standing in front of a power supply, not understanding how it works. "But I always use batteries, they work fine". Sure.There is a golden line where the RTOS is needed, some never have to cross it. I've seen people cross it, and then fail miserably, because they didn't adopt. You will know this, when you hear theprogrammercode monkey say, that they need weeks to implement this new function, because they did not think about it when they made the software architecture. Implementing it in RTOS is starting a new task. In a hard-coded timing environment, it is indeed, more difficult.I put that fine line somewhere at the axis of 40Mhz, Ethernet, touchscreen, printing, more than one programmer. If any of these is present, I would go for an RTOS.

author: westfw
author_rank: Super Contributor
timestamp: September 15, 2014, 10:35:44 pm
content: I think... If you want to use a multitasking OS on a MCU, you should first become familiar with the issues of multitasking by working on some multi-process desktop or server applications. "Real time" is a distraction that you shouldn't worry about at first (and maybe not ever.)For basics OS principles, there are lots of books and classes. and stuff. There are fewer specifically aimed at small microcontroller RTOSes (other than those aimed at specific implementations. I have a big set of Micrium uC/OS books that were given away (previous edition/version?) at a trade show a few years ago. It was claimed to be meant as coursework as well as describing the specific OS. (Um...http://www.amazon.com/MicroC-OS-II-Kernel-CD-ROM/dp/1578201039/ref=la_B001ITVJ02_1_1?s=books&ie=UTF8&qid=1410820124&sr=1-1)QuoteWhich is great way to spend a lot more time context-switching than you would have if you had a slightly more complex ISR. Complex ISRs interfere with "real time" latency, but not with the amount of overall processing that needs to happen. Which is one of the reasons that paying too much attention to "real time" may be a mistake for many systems. (I remember when BBN proudly announced that their Butteryfly packet switch could guarantee packet switching in less than 1ms. At the time, we were switching more than 10000pps, and I was very unimpressed. It wasn't until later that I understood that we were FAR away from guaranteeing ANY maximum switching time. (and others; someone got a thesis out of measuring/analyzing the variance.) (and guess which method, "fast" or "guaranteed", turned out to be a more useful/profitable product.)

author: tggzzz
author_rank: Super Contributor
timestamp: September 15, 2014, 11:30:15 pm
content: Quote from: westfw on September 15, 2014, 10:35:44 pmIt isn't just about speed. It is also about the ability to:mentally think through what isand isn'tgoing to happen when an interrupt occurstracably mapping the higher-level application models and abstractions into codesimulating application and operation in a hosted environment before the hardware and device drivers are availableeasy non-intrusive instrumentation, logging and debugging of the application running in alivesysteminstrumentation: monitor the queue lengthslogging: keep record of key bits of messages put and taken from queuesdebugging: display and/or halt when messages put and taken from queuesAll that is a damn sight more difficult if the ISRs can contain arbitrarily complex code with arbitrarily complex coupling with other system components.But hey, if the code doesn't have to be correct then it is trivial to make it arbirtarily fast.

author: andyturk
author_rank: Frequent Contributor
timestamp: September 16, 2014, 02:22:34 am
content: Quote from: NANDBlog on September 15, 2014, 09:55:04 pmUh, I'll take the other side of that argument. The problem with rolling your own RTOS is that you may end up with something that works on simple examples, but contains bugs that cause more complicated things to fail. Writing code against a known working RTOS (e.g., ChibiOS) is a great way to learn how they're supposed to work without hitting a brick wall of debugging too early.

author: westfw
author_rank: Super Contributor
timestamp: September 16, 2014, 04:19:45 am
content: Writing your own primitive OS is a great way to learn more about them (and get an appreciation of how much overhead is involved) (and how much work they are to write/debug.) After you've gotten somewhere, you'll certainly be able to have a better idea how to evaluate commercial or OSSW offerings.Some operating systems are essentially just kernels, around which you have to build nearly everything. Other OSs feature standard drivers for popular peripherals and major features (TCP/IP, USB, Displays, graphics, etc)...

author: Kremmen
author_rank: Super Contributor
timestamp: September 16, 2014, 05:00:05 am
content: Quote from: nctnico on September 15, 2014, 05:50:17 pmSure, go ahead thenI would'n for a second consider Linux any kind of alternative or competitor to a true RTOS. There are realtime extensions to Linux such as used in the popular LinuxCNC machine controller. But by that time all resemblance to an embedded small system are totally lost. And good luck porting Linux to a random HW platform you design into the latest project.Quote from: NANDBlog on September 15, 2014, 09:55:04 pmJesus, NO! That is like saying that if you want to drive a car, a good way to begin is by building one from iron ore. Writing a good, bug free (sic) OS is anything but an exercise to do at your leisure.Granted you will learn a lot if you do write one but that is absolutely not necessary or even desirable if you actually mean to produce a working application before the end of the century. I did it first time in the 80s but only because at that time practically none existed in the world and there were these complex manufacturing centers to program.Instead you should understand the principle of scheduling but that can be accomplished without implementing one.QuoteMy practice is, if the hardware at hand will take it, then always use an OS. So the logic goes the other way around - only in exceptional cases where you are desperately short on something that really prevents you from reasonably fitting in a RTOS, then don't. In all other cases just use it and be done. The applications tend to adopt similar high level structure, similar ways to handle similar things and there is predictable logic in how things are handled due to the OS guiding the implementation into a repeatable pattern. All big bonuses for debugging and later code changes or extensions.Quote from: westfw on September 15, 2014, 10:35:44 pmWell, maybe the "real time" is not strictly measured in nano- or microseconds in all cases. What _is_ important is that the OS has a deterministic response time or as close to one as possible. In that respect the desktop OSes suck. They may be like greased lightning only to suddenly fail miserably when they get stuck in a disk I/O exercise or something similar.And if you ask me, there is nothing to gain from rehearsing on a desktop machine. They obfuscate the multiprocessing behind so many veils of unnecessary stuff that i say the opposite: if you wish to quickly understand multitasking, then implement a toy app on an embedded platform and debug the hell out of it. All of the code sits directly there instead of being encased in some opaque device drivers or protected kernels.P.S. Pay attention to tggzzz, he has got it right.

author: miguelvp
author_rank: Super Contributor
timestamp: September 16, 2014, 05:19:14 am
content: There is such a thing as OS-9 for ARM but Microware has lost so much ground since the 68000 VME boards and their site and distributors can be counted with just one hand.But it was a great RTOS, maybe still is but no one uses it that I know of, and apparently they support x86 and some other chips.Then again being now so small I wonder if their price went down accordingly.

author: Kjelt
author_rank: Super Contributor
timestamp: September 16, 2014, 06:48:34 am
content: Quote from: NANDBlog on September 15, 2014, 09:55:04 pmThe only valid reason I can think off to write your own RTOS is if you study RTOS or it is your job.For the rest there are only good reasons NOT to write it your self such as that the code has been around for years, is tested and proven on millions of devices and users. If there were significant bugs they have been found and solved. Your own code could take years to become as mature.Most important the freeRTOS is open source software, you can learn by stepping/reading through it and if you come across something you do not likeyou can even change it, now that's programmers heaven and it does not become any better than that.If your micro is tiny and has not the capabilities of running an RTOS then I can imagine (and did it myself) that instead of using a superloop you write a small scheduler. Nothing wrong with that and you learn a lot from that too.QuoteAgreed with the first two, maybe three. But more than one programmer is IMHO not a requirement for a RTOS but for configuration management, using good tools and communication between the programmers can solve that easily. You can even let each programmer work on seperate branches and integrate as a final task for a single person.RAM is a big constraint though, I would myself use RTOS on devices >= 32 kB RAM not less, but it is an arbitrary line and depends on what has to be done.

author: Kremmen
author_rank: Super Contributor
timestamp: September 16, 2014, 07:10:34 am
content: Quote from: Kjelt on September 16, 2014, 06:48:34 amI won't argue against that but let me offer a datapoint: A lowly Mega328 with just 2kB of RAM will do 4 simple tasks and 3-4 queues on FreeRTOS with no issues whatever. Sure, the task stacks were relatively tight but not unresonably so, and the queues were only supposed to handle a few simple messages at a time. Still the system hums along rock solid. Some care is advisable to predict the stack depth based on local variables and control nesting but that is doable (or traceable at least) if only you avoid purposeful deep recursion algorithms.

author: nctnico
author_rank: Super Contributor
timestamp: September 16, 2014, 07:43:10 am
content: Quote from: tggzzz on September 15, 2014, 11:30:15 pmSince interrupts are nothing more than asynchronous processes debugging them is just as easy. See interrupts as seperate processes and all the problems you describe go away.I see many programmers go through this cycle:- make simple programs- make more complex programs- divide programs into many seperate parallel processes and chase race conditions forever- go back to single threaded programs because they are easier to debug & maintain@Kremmen: Linux in a realtime environment: been there, done that. With Linux it is pretty easy to make a user application wait until a hardware interrupt occurs. You can make a device driver between hardware and a user application extremely thin.

author: Simon
author_rank: Unknown
timestamp: September 16, 2014, 07:50:12 am
content: Right so let me get this bit straight, is an RTOS more useful when you need human interaction and need that to be real time to humans or does an RTOS make sense for applications where there is virtually no human interaction but it needs to be rock solid and easy to develop a large system.As an example my last project (well current) is to control a motor, I have a speed i want it to achieve and maintain with varying loads and i have a tacho output from the motor. So my program structure involves 2 interrupts. I have the chip running on 8MHz and I have one of the counters running at 1MHz and firing an interrupt every 50 counts and counting up a variable up so that I have a "clock" that ticks every 50uS. So every time a tacho signal is received it looks up the current "time" and stores it, so I have 2 variables storing tacho "times" and at each time the tacho interrupt fires I shift the current value into a "last time" variable and store the new value in the current one so that at any time i can with a separate function called from my main program loop do the math to work out the time between pulses and deduce motor speed and decide what to do about it.Does an application like this benefit from an OS of any sort or am i already doing the best I can do ?unless i can find an ARM based chip that will run at low and high temperatures (125+C) I'm stuck with something like atmels AVR32 which has only one part that is automotive rated.

author: nctnico
author_rank: Super Contributor
timestamp: September 16, 2014, 08:01:51 am
content: I'd put all the code for controlling the speed inside the timer interrupt. In that case there is only one variable that needs to be transferred from one process to another: the required speed. If you put that variable in an integer (declare it volatile just to make sure) which is equal to the size of the registers of the CPU then you don't even need to complicate things with using a mutex. This way your project is a no-brainer.

author: Simon
author_rank: Unknown
timestamp: September 16, 2014, 08:10:02 am
content: Well either way I need to share data between interrupts and I have 100-400 instruction cycles between each tick of my clock, during that time my tacho will also go off so I've tried to keep as much code as possible out of the interrupts.

author: tggzzz
author_rank: Super Contributor
timestamp: September 16, 2014, 09:04:13 am
content: Quote from: Simon on September 16, 2014, 07:50:12 amNo, although that is a perfectly reasonable application domain for an RTOS.QuoteYes, but there are many other perfectly reasonable application domains for an RTOS.QuotePet peeve: do you really mean microSiemens, or informally microSamples? I suspect you mean "us".QuoteIf that is theentirespecification and your solution is sufficient, then the added complexity of an RTOS would not have a benefit. OTOH, if you also have to receive commands and report status to another system, then an RTOS might just help. In general any system which has multiple activities that are asynchronous w.r.t. each other is a candidate for an RTOS.Fundamentally, you need to define the pain points in your current (and, if relevant, future) solution.Thenconsider whether an RTOS might be able to help.One non-functional pain point might be that complex communication libraries and/or device drivers are available, but cannot easily be merged with your current application structure. Another pain point might be debugging, logging and monitoring - see my earlier post.

author: nctnico
author_rank: Super Contributor
timestamp: September 16, 2014, 09:38:07 am
content: Quote from: Simon on September 16, 2014, 08:10:02 amThe problem with that method is that it won't work. You only have X time and you can only do one thing at a time. Giving more priority to one process automatically means you are eating time away from another process. I think a different approach is better for what you try to achieve:1) use a timer capture interrupt when the tacho signal 'hits' and process the result in an interrupt2) use interrupts based on the tacho signal and calculate the time between interrupts with a free running timerI think 1 is better because it relaxes the latency between the tacho signal and the actual processing. The actual measurement is done in hardware. And remember: life really gets a lot easier if you let go of the 'interrupt handlers should be short' dogma. If you transfer the events to your main loop then the main loop which probably also does some housekeeping must be fast as well; the entire software becomes time critical.

author: Jeroen3
author_rank: Super Contributor
timestamp: September 16, 2014, 10:01:25 am
content: QuoteDoes the software need to be automotive as well? If so, you're probably entering a world of certifications if you want an OS. Even worse when you prepend RT.Quote3) sample the tacho signal with at least twice the maximum tacho speed and derive the time from the buffer once every x samples. Fully dma-ed until dma-finish event, which will go into an interrupt or an rtos event queue.Notice both method 1 and 2 require approximately equal time in interrupt state. Unless the timer has a buffered capture.- Interrupt prologue- Validate if timer value is within acceptable range.- Put a timer value into a filter.- Interrupt epilogueAn os is only useful with option 3, or with the further processing. option 1 and 2 are all interrupts, and operating systems tend not to interfere between them on small embedded systems. However, you can use the os the schedule the interrupt to a better time. If you want it to. For example, I don't care if the RTC alarm is a second later, but I do care if the motor current overload interrupt triggers.

author: Kremmen
author_rank: Super Contributor
timestamp: September 16, 2014, 10:08:54 am
content: Quote from: Simon on September 16, 2014, 07:50:12 amAn OS lets you (for example) isolate human interaction into a single task hygienically separated from the rest of the system. That task then communicates with other tasks depending on what needs to happen based on human input.But equally a completely automated solution benefits from an OS because a human is only an input/output "device" same as any nonliving actor. The key is that you identify the activities of the application and the channels of comunication they need agaist each other. In this kind of thinking the point is to largely avoid global variables that only create access conflicts.QuoteOK, just some quick thoughts, your mileage may vary.1. Get rid of the timer interrupt in this form. Do the counting in a hardware counter and only interupt on overflow. Maintain overflow count in SW but the rest of the count in HW that you read only when you actually need the count.2. You only need the tacho count when you are going to also do something about it. So in principle you should decide on the speed controller cycle time and get your input in sync with that cycle. Anything faster is busy work that gets you nowhere.I don't wish to design this thing for you but assuming you have a regular PID type speed controller, then this task is reduced to something like this:- The RTOS scheduler clock is a natural base for the controller cycle time. At least in FreeRTOS you can hook up a tick procedure to run at every scheduler tick regardless of what task is otherwise selected to run. The tick procedure is a natural place to put your PID controller(s) so they run once every tick without exception. Thus your controller cycle time is the same as your OS tick time.- set up one HW counter to be your timebase for the speed measurement. That counter can increment _real_fast_ to provide good time resolution (in a recent rev counter project i had the timebase at 50 ns, i.e. counting the 20MHz xtal straight). Use counter overflow interrupts only to update a RAM variable to maintain the high word of the count when tacho speed is slow. The low word count is incremented in HW directly.- tacho pulses you can either count in SW or HW depending on the max pulse frequency and what HW you have available (some AVRs have HW event pipelines and DMA channels that could dramatically speed up processing by delegating stuff to HW). Also some MCUs such as Atmel XMega have a quadrature encoder input built in. You can decrease the interupt load by reading the counts mainly synced to the scheduler ticks but also by interrupting on a tacho pulse and only then reading the timebase counter. There are various ways to do it and to trade off processor load to accuracy or the other way around.So you will be using interrupts, OS or no OS, but the usage will perhaps be a bit more coordinated and definitely supported by the OS if you know how to do it "right".QuoteI hope you got from the above that the way you do it now is far from optimal whether you have an OS or not. Again it is just me but i would definitely consider one of the OSes i have mentioned.QuoteGood news is that an official FreeRTOS port exists for AVR32 MCUs, at least UC3A.

author: Kjelt
author_rank: Super Contributor
timestamp: September 16, 2014, 10:28:58 am
content: Quote from: Kremmen on September 16, 2014, 07:10:34 amwow, ok I stand corrected then, I never imagined it working properly with those low resources.

author: Kjelt
author_rank: Super Contributor
timestamp: September 16, 2014, 10:40:42 am
content: Quote from: Simon on September 16, 2014, 07:50:12 amSTM32L051C8 and STM32L053R8 have an operating temp of -40oC to +125oC but they are cortex M0, still could do the job,

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 11:07:47 am
content: QuoteIt depends on what you mean by "OS" - the simplest would be a switch-case statement.I think there exists an OS for PIC16 chips - published by Microchip?

author: Kjelt
author_rank: Super Contributor
timestamp: September 16, 2014, 11:13:00 am
content: Quote from: dannyf on September 16, 2014, 11:07:47 amHe said "FreeRTOS" not a simple scheduler

author: Kremmen
author_rank: Super Contributor
timestamp: September 16, 2014, 11:15:57 am
content: Quote from: Kjelt on September 16, 2014, 10:28:58 amInfo on FreeRTOS resource consumption as well as other FAQs here:http://www.freertos.org/FAQ.htmlQuote from: dannyf on September 16, 2014, 11:07:47 amWell, call it a microkernel then if OS is too grand a word... Scheduling and intertask comms is the point however.A switch case is not a scheduler because it all runs in one context with no concept of priority or other scheduling rules/methods.

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 11:18:20 am
content: QuoteThat's probably dicey -> most due to its ram space. You probably don't have much mips left, either.

author: Kremmen
author_rank: Super Contributor
timestamp: September 16, 2014, 12:01:30 pm
content: Quote from: dannyf on September 16, 2014, 11:18:20 amJust read the link i gave and think again.At the risk of becoming labeled as a RTOS fanboy, let me ask: how come not much mips left? Where would they go then?Seriously - this is one of the most typical gripes coming from those who are not really in the loop. I'm not saying you aren't, this is a generic observation. What these guys fail to get is that one way or the other you end up doing the same things anyway. In specific cases hand coding may result in somewhat faster or otherwise optimized code but generally there is no penalty and more often than not the benefit goes to the OS. A RTOS is not the end-all of program control but neither is it a black hole sucking all available resources. Like fire, it is a good servant but you don't want it to be your master. So use it where it makes sense and skip it were it doesn't. When exactly that is depends on what you want of it.OS newbies should use it in a non demanding test case whether a toy or a real application, to get the hang of it and get first hand experience of the strengths and weaknesses of each particular product.@Simon: if you decide to give it a try, you won't find yourself alone. Plenty of people able to lend a hand here & elsewhere.

author: eurofox
author_rank: Unknown
timestamp: September 16, 2014, 12:45:20 pm
content: Quote from: Kremmen on September 16, 2014, 12:01:30 pmI fully agree and add a few points:1) Most programs in a CPU from 8 bits to 32 bits CPU/Applications spend time waiting, looping but not really doing something useful unless you and a lot of math or other very demanding process power.2) It is wrong to think that a RTOS is taking most on the CPU resources unless it is very badly coded3) When people start writing interrupt routines to create tasks and checking in the main loop the status of the task they already duplicate one of the features of an RTOS, all those features are build in a ways it is strutured and easy to manage if you understand how it work4) Again since I aleady write it for a simple application you don't need an RTOS but as soon task need to run in the background it will make the code better and more transparent to develop and maintaineurofox

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 12:50:26 pm
content: QuoteTo the overhead? task switching? mailbox management? ....A simple way to test it would be if you open up 10 identical jobs blinking an led, compare that vs. blinking an led without OS.The difference goes to the RTOS.

author: tggzzz
author_rank: Super Contributor
timestamp: September 16, 2014, 12:59:38 pm
content: Quote from: Kremmen on September 16, 2014, 10:08:54 amPrecisely.This kind of issue has been around for over half a century, and many useful and practical techniques have evolved. I hope the OP has time and inclination to read and understand such realtime "design patterns". (Yes, that's a suitable search term!)If the OP has neither time nor inclination then posts on this forum won't help.

author: Kjelt
author_rank: Super Contributor
timestamp: September 16, 2014, 02:12:44 pm
content: Quote from: dannyf on September 16, 2014, 12:50:26 pmThere is little to no difference if your blinkrate is a multiple of a ms (usual RTOS timetick).

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 02:16:58 pm
content: That's the time slot allotted to each task. If the N tasks are blinking the same LED, over a given period of time, the numbers of times the LED is blinked in a naked environment vs. the RTOS environment would tell you the cost of the RTOS.

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 02:19:11 pm
content: QuoteMore precisely, it would tell you the lower bound of the RTOS cost -> such a simple set-up does not need information to be transmitted from one task to another. Costs associated with messaging / mailbox management would not be reflected in this test.Only task switching is.

author: Kjelt
author_rank: Super Contributor
timestamp: September 16, 2014, 02:27:35 pm
content: What is the use of a theoretical test that has no use in practice?Are you also complaining about your car not being able to do 300mph where there is no road anywhere you will need that?Yeah a RTOS may take a few % overhead but it offers a lot in return.

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 02:44:41 pm
content: QuoteAny test would be theoretical, by definition.Its purpose is really to get a sense of what performance hit you are going to get, not precisely what performance hit you are going to get.Quoteyes, if it is advertised to do 300mph. That's why options / capabilities are expensive.

author: tszaboo
author_rank: Super Contributor
timestamp: September 16, 2014, 03:19:54 pm
content: Quote from: westfw on September 16, 2014, 04:19:45 am(For the others): Yes, this is exacly what I'm saying.Going through an existing RTOS code is not something every programmer can do, I definetly wouldnt try it. It has too many features, the code is obfuscated, unreadable, it contains ASM, etc... If you look at the individual features, take for exapmle a not pre-emptive task manager. The code for this is about one hundred lines, with comments. It doesnt need to work with eight different arhitechtures, timer setings, etc... just handle the stacks and the registers, memory allocation.It is really simple, even I understood it how it works.If you write this basic features, you will undoubtedly think about how would you use it. And one you know what the features are and how to benefit from them, that is a good moment to decide to develop the OS, or change to a finished product. I've seen, I've used systems with both, both had upsides and downsides.I'm not sure why people say that it would take years to do this. I mean yes, an average programmer writes like 7 line of code every day. If an OS doesnt have that many features, we are still talking about a few hundred lines of code.

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 03:31:01 pm
content: Many of the "RTOSs" are well understood. Particularly uCOS: there is even a book on it, with older versions of code available from its maker.Another example would be ARM's rtos for the cortex chips -> it is freely distributed with CMSIS.The complexity varies depending on what you features are trying to implement, and what "assumptions" you have to make, and mostly important of all, what you think an RTOS is.The simplest "RTOS" can be done by practically any programmer. The most complex cannot by done by 99% of the programmers out there.

author: tszaboo
author_rank: Super Contributor
timestamp: September 16, 2014, 03:54:41 pm
content: Quote from: dannyf on September 16, 2014, 03:31:01 pmThere should not be any confusion about the basic functions of an RTOS. It is defined."IEEE Portable Operating System Interface for Computer Environments, POSIX 1003.1b, provides a list of basic services an RTOS must support:Asynchronous Input/Output (I/O)Synchronous I/OMemory lockingSemaphoresShared memoryExecution schedulingTimersInterprocess communication (IPC)Real-time filesReal-time threads"If you do half of this by yourself, than you are halfway there.

author: westfw
author_rank: Super Contributor
timestamp: September 16, 2014, 04:14:03 pm
content: QuoteBTW: humans are a fine example of something that does NOT need "real-time" support. Humans are terribly slow, and tolerate wide variations in response times of the software (up to a couple hundred milliseconds, at least.) To keep humans happy, your system should respond quickly, but it does not need the sort of deterministic "real time" response given to you by an RTOS.That said, one of the features you'll get "easily" from an OS, as opposed to single-threaded code, is better coordination between slow tasks (like interacting with a user) and tasks that require faster response. The famous "blink without delay" arduino code is one example. Without an OS, your code can deteriorate into a confusing mess as you check multiple timers and take appropriate actions. With a multitasking OS, you just put your blink in a separate task, and the OS handles all the timing issues.Sort of - a multitasking OS gives you the illusion of doing multiple things at once (which is often requested.) A real-time OS quantifies the performance of the illusion...

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 04:19:23 pm
content: QuoteOnly if you follow that definition, under which many well known "RTOSs" would be excluded, including FreeRTOS and the old RTX, to just name a couple.I think uCOS is on that list of non-compliance as well - arguably so.

author: tggzzz
author_rank: Super Contributor
timestamp: September 16, 2014, 04:34:24 pm
content: Quote from: westfw on September 16, 2014, 04:14:03 pmRubbish, as your last sentence appears to sort-of imply.Real time is not about speed. Real time is about meeting a defined timing specification, where the definition is application dependent.More formally a computational system is real-time if the usefulness of the computation result depends not only on the actual result but also on the time at which the result is delivered.For a silly example, consider producing a cinema schedule so that patrons are able to watch the film of their choice - that's a real-time process. The latency between producing the schedule and the film being projected can be weeks or months. But if the schedule is produced too late for patrons to get to the cinema, then it is valueless.

author: nctnico
author_rank: Super Contributor
timestamp: September 16, 2014, 04:56:35 pm
content: Quote from: NANDBlog on September 16, 2014, 03:19:54 pmIf you need to look at the sourcecode from an RTOS to use it, the documentation is severly lacking. The RTOSes I've looked at had a decent explaination of the various (supported) task scheduling options and their pros and cons.

author: Kjelt
author_rank: Super Contributor
timestamp: September 16, 2014, 05:46:23 pm
content: You can build everything yourself ofcourse, the rtos, the ip stack, the filesystem, the hardware layer, and ofcourse the extensive testsuites and documentation. perhaps if you are unemployed you can do it within three years and if you work fulltime within 10 years and then finally you can do what all others are doing today, write the application software.

author: dannyf
author_rank: Super Contributor
timestamp: September 16, 2014, 07:24:23 pm
content: With so many RTOS available, often free for non-profit and sometimes commercial uses, writing an RTOS is some of the least value-add activities one can take on.Writing application software is much better, in my view.

author: legacy
author_rank: Super Contributor
timestamp: September 16, 2014, 07:37:23 pm
content: Quote from: Kjelt on September 16, 2014, 05:46:23 pmthe-"i will do everything by myself because i can!"-philosophy could be excellent if you plan something to do for your long time (probably never finished) hobby

author: legacy
author_rank: Super Contributor
timestamp: September 16, 2014, 07:41:19 pm
content: ucOS/2anducOS/3are good kernels which came with an excellent documentation!I mean you could buy a book from Amazon that describes the kernel and its components in details!It was a good hints for me, when i was a student! I have learned a lot with a learning-by-examples approach!

author: SirNick
author_rank: Frequent Contributor
timestamp: September 16, 2014, 11:20:14 pm
content: The FreeRTOS site sells PDF guides at a discount to the printed material, with the added benefit that it funds continued development. They have a few variants: Generic (PC-centric), Cortex-specific, some microcontroller-specific... I'm vollying back and forth with Barry ATM due to a shopping cart bug that seems to fail with certain postal addresses (which shouldn't apply with an e-book -- hence the cart bug), so if you try to buy a copy and it complains that you haven't selected a shipping method, a fix is in the works. Again, this only seems to apply to certain addresses.Anything that uses a chip beyond a bare-bones M0 could probably stand to benefit from an RTOS just by nature of its inherent complexity. Whether it's required or not is debatable, but as others have said -- having this skill in your toolbox is not a bad thing.

author: SirNick
author_rank: Frequent Contributor
timestamp: September 16, 2014, 11:23:40 pm
content: Oh, and WRT rolling your own: If you have the time and the interest, there's always a benefit to reinventing the wheel. You just don't get the same experience as an end-user. To understand and appreciate how it works, what it does, and what it took to do -- for that, you need to get your hands dirty. Now, if you onlyneedto understand how to use it, then the API docs ought to be sufficient. But, a more in-depth understanding can only help. The value of this exercise is up to the individual. It's on my bucket list, for sure.

author: legacy
author_rank: Super Contributor
timestamp: September 17, 2014, 03:31:34 am
content: guys, the most important thing (perhaps for me):how do you debug kernel drivers and applications ?which tools, and which methods do you use ?

author: westfw
author_rank: Super Contributor
timestamp: September 17, 2014, 06:26:08 am
content: QuoteExcept in the case of obscure interactions, debugging a multitasking system can be easier that debugging monolithic large applications.Because one or more of your tasks can essentially be a debugger, monitoring the state of the task you are trying to debug.

author: legacy
author_rank: Super Contributor
timestamp: September 17, 2014, 07:01:21 am
content: good point, a debug-task is able to monitor shared global variablesbut what if you have to set breakpoint inside a task, or if you have to debug an ISR, or something that is "kernel driver" ?you have to deal with a lot of other functions which are called by the kernel, so … your call tree and your stack may go very complexi supposealso, imagine you have 16 tasks and you have a concurrency issue, how could you debug it ?never done a real kernel/RTOS debugging, i am asking because i am new, i usually write a lot of bareboard OS-less code

author: tggzzz
author_rank: Super Contributor
timestamp: September 17, 2014, 07:56:30 am
content: Quote from: legacy on September 17, 2014, 07:01:21 amFirstly by structuring your design by only theappropriateusing design patterns. These will help you avoid ad-hoc solutions that lead to ad-hoc problems.Frequently it is helpful to...avoid the use of individual "random" mutexes and semaphores; that way often leads to livelock/deadlockthink in terms of discrete-time events that are passed between tasks. An event represents an input, or a unit of work to be done, or an outputcommunicate via tasks using mailboxes or queuesstructure a task so that it takes an event from a queue, processes it optionally creating events sent to other tasks, suspends itself until another event is waiting in the queue. Analogy: clerks in an office with an in-tray and an out-tray, where one clerk's out tray is another's in-traystructure the design in terms of a number of finite state machines, and don't obscure the FSM in the way you write your codedon't use priority as a means of getting the system logic correct; do use two priority levels to ensure timelinessThe RTOS will then provide a number of APIs that can help you observe the tasks and RTOS data structures, especially queues/mailboxes, so thatDesign debugging can start with observing events and how they propagate through the system.Real-timein-serviceload monitoring can start with observing the length of the queuesReal-timein-servicefault finding can start with keeping a log of the events that lead up to the observed problemThe high level-design can be debugged on workstationsbefore the hardware is available(or when hardware is considered untrustworthy) by simulating events and watching them propagate through the system.Those techniques have proven their worth over the decades; there's no need to reinvent that wheel!Quote

author: nctnico
author_rank: Super Contributor
timestamp: September 17, 2014, 08:30:07 am
content: You forgot rule number one: don't use parallel processes unless absolutely necessary.I see a lot of programmers go through this cycle:- make simple programs- make more complex programs- divide programs into many parallel processen thinking that it makes programming easier but end up hunting dead locks and race conditions- go back to single threaded applications

author: Jeroen3
author_rank: Super Contributor
timestamp: September 17, 2014, 09:00:04 am
content: Some operating systems keep track of tasks. They keep count how many slices a task has been in, and they keep a ringbuffer of context switches.Also, you're able to create a simple ps view over the debug interface. What state they are, and what they are waiting for. Yes, this sacrifices some resources.http://en.wikipedia.org/wiki/Ps_(Unix)Also, runtime debugging without trace points (expensive debugger) using the uart is a potential timing issue. Since you have to wait until another task releases the uart. But even after that, the output can be a mess. I've created a tool for that.https://github.com/Jeroen6/MultiTerminal

author: westfw
author_rank: Super Contributor
timestamp: September 17, 2014, 09:19:15 am
content: One way to lessen reduce concurrency bugs is to use a non-preemptive (and thus also not "real time") OS. :-)(It won't eliminate them; things like printf() will relinquish control in the middle of printing a data structure that someone else ends up deleting, for example.) In general, I (and others) have found it a toss-up when it comes to whether it is more difficult to discipline yourself to a cooperative scheduler, or to properly implement and manage the locking needed in a fully preemptive system. Assuming you don't NEED "hard real time."I'll moderate nctnico's comment some - mutiltasking works best if each process is independent of the other processes. One user's command processor need not have much to do with another user's command processor, for instance. Trying to do one function (say, processing a large table via some kind of divide-and-conquer algorithm) in multiple processes (hoping for multi-core, for example) is MUCH more difficult.

author: mrflibble
author_rank: Super Contributor
timestamp: September 17, 2014, 09:23:15 am
content: Quote from: nctnico on September 17, 2014, 08:30:07 amBy which of course you meant: don't use parallel processes unless the cost of not doing so becomes significantly higher than doing so.Because"absolutely necessary"is such a strong constraint.You can make loads of things in a non-parallel fashion, long after doing so stopped making any practical sense.edit: fix typo

author: tggzzz
author_rank: Super Contributor
timestamp: September 17, 2014, 11:37:18 am
content: Quote from: nctnico on September 17, 2014, 08:30:07 amMaking your application simpler, easier to understand/debug/monitor is, IMNSHO, a good reason for having multiple tasks (which may or may not run in parallel).But that does depend on choosing the granularity of parallelism and computation carefully. I believe the techniques I noted are a good starting point, but with any technique the problems you list below are possible.If you know of a way of instilling taste and elegance into programmers' minds, please let me knowIn the absence of that, design patterns are the bet set of pointers we have available.Quote

author: tggzzz
author_rank: Super Contributor
timestamp: September 17, 2014, 11:40:53 am
content: Quote from: westfw on September 17, 2014, 09:19:15 amThere is a good argument that it is easier to ensure a non-preemptive OSis(hard) real time. Key point: the set of possible cross-process timing interactions is much much simpler. to analyse.