Well, you can of course choose to run a real time operating system kernel (RTOS) on your micro, but that is probably not what most people her needs.
The second best solution is , as I see it, to run an efficient task swapper.
I have tried several schemes over the years, many like the things suggested above, and finally settled for one that I find highly efficient, flexible, and predictable.
It is based on a free-running STATE counter driven by ticks from a timer driven interrupt ( Frequency 1/T). The state vector is defined by a 16 bit WORD, so 16 TASKS can be handled. You could just as well use a BYTE for 8 tasks capacity or DWORD for 32 tasks.
Each STATE transition is tested in a tight main loop and compared to the previous state.
The only hardware resources needed are one timer, and two state WORD variables. Let us call them TASK and OLDTASK
OLDTASK is simply a copy of TASK, and is updated at the end of each round-robin
The following rules apply.
1. A state change is detected when TASK differs from OLDTASK (Which happens every timer tick)
Each state counter low to high transition will represent a state change, so each task will have a repetition rate from 2/T, 4/T, 8/T ... 65535/T
This allows you to apply many possible task rates in a binary time division fashion.
The difference in bit pattern between TASK and OLDTASK will tell us which task to run next.
2. Each task has maximum the time slot 2T to execute before next task calls for his slot.
If a task exceeds its slot it will "steal" next slot (There is a mechanism to check this during run)
3. If there are "holes" in the task list, this slot will not get wasted. The UNSCHEDULED task will use it instead.
The UNSCHEDULED task will run at the end of MAIN loop as soon as no task demands its slot.
4. PRIORITY is given in the order tasks appear in the task-list
Normally it is a good idea to let slow tasks get priority over fast tasks, but this is entirely up to you, and to what the application needs.
5. All task handling except for UNSCHEDULED is fully predictable. (Unless some task abuse its rights. See 2)
Does this sound complicated? Well in reality it is very easy to administrate.
Does it sound as a burden for the CPU? It certainly is NOT.
Interested? I could put an example in the "Put your working code here" or why not in the new Wiki?
Take care
Per
↧