Skip to content

Commit b1b8191

Browse files
committed
Support configuration of the scheduler tick source by client
1 parent 2c1e8ea commit b1b8191

File tree

6 files changed

+349
-69
lines changed

6 files changed

+349
-69
lines changed

doc/tick_sources.md

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
# Scheduler tick sources
2+
3+
## Configuration
4+
Tick source is selected by (un)defining values `portUSE_WDTO` and `portUSE_TIMER0` in file `FreeRTOSVariant.h`. Default in Arduino_FreeRTOS is Watchdog timer (WDT), it contains all code needed for this and works out-of-the-box.
5+
6+
For alternative tick source, pieces of code must be provided by the application. Arduino_FreeRTOS expects you to provide function `void prvSetupTimerInterrupt(void)` responsible for the initialization of your tick source. This function is called after the Arduino's initialization and before the FreeRTOS scheduler is launched.
7+
8+
NOTE: Reconfiguring Timer0 for FreeRTOS will break Arduino `millis()` and `micros()`, as these functions rely on Timer0. Functions relying on these Arduino features need to be overridden.
9+
10+
11+
12+
## WDT (default)
13+
Time slices can be selected from 15ms up to 500ms. Slower time slicing can allow the Arduino MCU to sleep for longer, without the complexity of a Tickless idle.
14+
15+
Watchdog period options:
16+
* `WDTO_15MS` (default)
17+
* `WDTO_30MS`
18+
* `WDTO_60MS`
19+
* `WDTO_120MS`
20+
* `WDTO_250MS`
21+
* `WDTO_500MS`
22+
* `WDTO_1S`
23+
* `WDTO_2S`
24+
25+
### WDT precision limitations
26+
The frequency of the Watchdog Oscillator is voltage and temperature dependent as shown in “Typical Characteristics” on corresponding figures:
27+
28+
![WDT limitations](https://user-images.githubusercontent.com/35344069/224619444-3c0b634c-f460-40d2-8a73-256bad0d5ba1.png)
29+
30+
Timing consistency may vary as much as 20% between two devices in same setup due to individual device differences, or between a prototype and production device due to setup differences.
31+
32+
## Alternative tick sources
33+
For applications requiring high precision timing, the Ticks can be sourced from a hardware timer or external clock.
34+
35+
First, you switch it in `FreeRTOSVariant.h` header by removing or undefining `portUSE_WDTO` and defining `portUSE_TIMER0`.
36+
```cpp
37+
#undef portUSE_WDTO
38+
#define portUSE_TIMER0
39+
#define portTICK_PERIOD_MS 16
40+
```
41+
42+
Next, in your app you provide two pieces of code: the initialization function and the ISR hook. Their implementation depends of what is your tick source.
43+
44+
45+
## Hardware timer Timer0
46+
### Timer initialization function
47+
_NOTE: This code snippet is verified to work on Atmega2560. Full code avaialable [here](./tick_sources_timer0.cpp)._
48+
```cpp
49+
// Formula for the frequency is:
50+
// f = F_CPU / (PRESCALER * (1 + COUNTER_TOP)
51+
//
52+
// Assuming the MCU clock of 16MHz, prescaler 1024 and counter top 249, the resulting tick period is 16 ms (62.5 Hz).
53+
//
54+
#define TICK_PERIOD_16MS 249
55+
#define PRESCALER 1024
56+
#if (portTICK_PERIOD_MS != (PRESCALER * (1 + TICK_PERIOD_16MS) * 1000 / F_CPU))
57+
#warning portTICK_PERIOD_MS defined in FreeRTOSVariant.h differs from your timer configuration
58+
#endif
59+
60+
// For register TCCR0A:
61+
#define NO_PWM (0 << COM0A1) | (0 << COM0A0) | (0 << COM0B1) | (0 << COM0B0)
62+
#define MODE_CTC_TCCR0A (1 << WGM01) | (0 << WGM00)
63+
64+
// For register TCCR0B:
65+
#define MODE_CTC_TCCR0B (0 << WGM02)
66+
#define PRESCALER_1024 (1 << CS02) | (0 << CS01) | (1 << CS00)
67+
68+
// For register TIMSK0:
69+
#define INTERRUPT_AT_TOP (1 << OCIE0A)
70+
71+
extern "C"
72+
void prvSetupTimerInterrupt( void )
73+
{
74+
// In case Arduino platform has pre-configured the timer,
75+
// disable it before re-configuring here to avoid unpredicted results:
76+
TIMSK0 = 0;
77+
78+
// Now configure the timer:
79+
TCCR0A = NO_PWM | MODE_CTC_TCCR0A;
80+
TCCR0B = MODE_CTC_TCCR0B | PRESCALER_1024;
81+
OCR0A = TICK_PERIOD_16MS;
82+
83+
// Prevent missing the top and going into a possibly long wait until wrapping around:
84+
TCNT0 = 0;
85+
86+
// At this point the global interrupt flag is NOT YET enabled,
87+
// so you're NOT starting to get the ISR calls until FreeRTOS enables it just before launching the scheduler.
88+
TIMSK0 = INTERRUPT_AT_TOP;
89+
}
90+
```
91+
92+
Though Timer0 is given as example here, any timer can be used. A 16-bit timer (e.g., Timer1) is needed for time slices longer than ~20 milliseconds.
93+
94+
### ISR hook
95+
For **preemptive** scheduler use `naked` attribute to reduce the call overhead:
96+
```cpp
97+
ISR(TIMER0_COMPA_vect, ISR_NAKED) __attribute__ ((hot, flatten));
98+
ISR(TIMER0_COMPA_vect) {
99+
portSchedulerTick();
100+
__asm__ __volatile__ ( "reti" );
101+
}
102+
```
103+
104+
The context is saved at the start of `portSchedulerTick()`, then the tick count is incremented, finally the new context is loaded - so no dirtying occurs.
105+
106+
107+
For **cooperative** scheduler, the context is not saved because no switching is intended; therefore `naked` attribute cannot be applied because cooperative `portSchedulerTick()` dirties the context.
108+
```cpp
109+
ISR(TIMER0_COMPA_vect) __attribute__ ((hot, flatten));
110+
ISR(TIMER0_COMPA_vect) {
111+
portSchedulerTick();
112+
}
113+
```
114+
115+
Use ISR_NOBLOCK where there is an important timer running, that should preempt the scheduler:
116+
```cpp
117+
ISR(portSCHEDULER_ISR, ISR_NAKED ISR_NOBLOCK) __attribute__ ((hot, flatten));
118+
```
119+
120+
Attributes `hot` and `flatten` help inlining all the code found inside your ISR thus reducing the call overhead.
121+
122+
123+
## External clock
124+
### Input configuration function
125+
_NOTE: This code snippet was not verified on actual MCU._
126+
127+
Assuming the external clock is connected to data pin 21 (function INT0):
128+
```cpp
129+
// For register EICRA:
130+
#define TICK_ON_RISING_EDGE_D21 (1 << ISC01) | (1 << ISC00)
131+
132+
// For register EIMSK:
133+
#define TICK_INPUT_PIN_D21 (1 << INT0)
134+
135+
extern "C"
136+
void prvSetupTimerInterrupt( void )
137+
{
138+
EICRA = TICK_ON_RISING_EDGE_D21;
139+
140+
// At this point the global interrupt flag is NOT YET enabled,
141+
// so you're NOT starting to get the ISR calls until FreeRTOS enables it just before launching the scheduler.
142+
EIMSK = TICK_INPUT_PIN_D21;
143+
144+
// Configure the pin
145+
pinMode(21, INPUT);
146+
}
147+
```
148+
149+
150+
### ISR hook
151+
Similar to Timer0 ISR, for **preemptive** scheduler:
152+
```cpp
153+
ISR(INT0_vect, ISR_NAKED) __attribute__ ((hot, flatten));
154+
ISR(INT0_vect) {
155+
portSchedulerTick();
156+
__asm__ __volatile__ ( "reti" );
157+
}
158+
```
159+
160+
For **cooperative** scheduler:
161+
```cpp
162+
ISR(INT0_vect) __attribute__ ((hot, flatten));
163+
ISR(INT0_vect) {
164+
portSchedulerTick();
165+
}
166+
```
167+
168+
169+
170+
## Performance considerations
171+
When selecting the duration for the time slice, the following should be kept in mind.
172+
173+
### Granularity
174+
Note that Timer resolution (or granularity) is affected by integer math division and the time slice selected. For example, trying to measure 50ms using a 120ms time slice won't work.
175+
176+
### Context switching
177+
In preemptive mode, tasks which are actively executing (i.e., those not waiting for a semaphore or queue) might be switched every time tick, depending on their priority. Switching the context involves pushing all CPU's registers of old task and poping all registers of new task. The shorter your time slice is, the bigger of overhead this becomes.
178+
179+
In cooperative mode, context overhead is not a factor.
180+
181+
### Calculations
182+
On MCUs lacking the hardware division operation like AVR, a special care should be taken to avoid division operations. Where unavoidable, operations with divisor of power of 2 work best because they are performed with bitwise shifting, whereas an arbitrary value results in a software division operation taking ~200 clock cycles (for a uint16 operand).
183+
184+
You might encounter a division when calculating delays, e.g. converting milliseconds to ticks:
185+
```cpp
186+
TickType_t ticks = delay_millis / portTICK_PERIOD_MS
187+
```
188+
189+
If your application needs to do this sort of conversion a lot, consider making your time slice a power-of-2 value (16 ms, 32 ms, 64 ms etc.).
190+

doc/tick_sources_timer0.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <FreeRTOSVariant.h>
2+
3+
/*
4+
* Formula for the frequency is:
5+
* f = F_CPU / (PRESCALER * (1 + COUNTER_TOP)
6+
*
7+
* Assuming the MCU clock of 16MHz, prescaler 1024 and counter top 249, the resulting tick period is 16 ms (62.5 Hz).
8+
*/
9+
#define TICK_PERIOD_16MS 249
10+
#define PRESCALER 1024
11+
#if (portTICK_PERIOD_MS != (PRESCALER * (1 + TICK_PERIOD_16MS) * 1000 / F_CPU))
12+
#warning portTICK_PERIOD_MS defined in FreeRTOSVariant.h differs from your timer configuration
13+
#endif
14+
15+
// For register TCCR0A:
16+
#define NO_PWM (0 << COM0A1) | (0 << COM0A0) | (0 << COM0B1) | (0 << COM0B0)
17+
#define MODE_CTC_TCCR0A (1 << WGM01) | (0 << WGM00)
18+
19+
// For register TCCR0B:
20+
#define MODE_CTC_TCCR0B (0 << WGM02)
21+
#define PRESCALER_1024 (1 << CS02) | (0 << CS01) | (1 << CS00)
22+
23+
// For register TIMSK0:
24+
#define INTERRUPT_AT_TOP (1 << OCIE0A)
25+
26+
extern "C"
27+
void prvSetupTimerInterrupt( void )
28+
{
29+
// In case Arduino platform has pre-configured the timer,
30+
// disable it before re-configuring here to avoid unpredicted results:
31+
TIMSK0 = 0;
32+
33+
// Now configure the timer:
34+
TCCR0A = NO_PWM | MODE_CTC_TCCR0A;
35+
TCCR0B = MODE_CTC_TCCR0B | PRESCALER_1024;
36+
OCR0A = TICK_PERIOD_16MS;
37+
38+
// Prevent missing the top and going into a possibly long wait until wrapping around:
39+
TCNT0 = 0;
40+
41+
// At this point the global interrupt flag is NOT YET enabled,
42+
// so you're NOT starting to get the ISR calls until FreeRTOS enables it just before launching the scheduler.
43+
TIMSK0 = INTERRUPT_AT_TOP;
44+
}
45+
46+
47+
ISR(TIMER0_COMPA_vect, ISR_NAKED) __attribute__ ((hot, flatten));
48+
ISR(TIMER0_COMPA_vect)
49+
{
50+
portSchedulerTick();
51+
__asm__ __volatile__ ( "reti" );
52+
}

readme.md

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,9 @@ Over the past few years freeRTOS development has become increasingly 32-bit orie
2121
FreeRTOS has a multitude of configuration options, which can be specified from within the FreeRTOSConfig.h file.
2222
To keep commonality with all of the Arduino hardware options, some sensible defaults have been selected. Feel free to change these defaults as you gain experience with FreeRTOS.
2323

24-
The AVR Watchdog Timer is used to generate 15ms time slices (Ticks), but Tasks that finish before their allocated time will hand execution back to the Scheduler.
24+
Normally, the AVR Watchdog Timer is used to generate 15ms time slices (Ticks). For applications requiring high precision timing, the Ticks can be sourced from a hardware timer or external clock. See chapter [Scheduler Tick Sources](./doc/tick_sources.md) for the configuration details.
2525

26-
Time slices can be selected from 15ms up to 500ms. Slower time slicing can allow the Arduino MCU to sleep for longer, without the complexity of a Tickless idle.
27-
28-
Watchdog period options:
29-
* `WDTO_15MS`
30-
* `WDTO_30MS`
31-
* `WDTO_60MS`
32-
* `WDTO_120MS`
33-
* `WDTO_250MS`
34-
* `WDTO_500MS`
35-
* `WDTO_1S`
36-
* `WDTO_2S`
37-
38-
Note that Timer resolution (or granularity) is affected by integer math division and the time slice selected. Trying to measure 50ms, using a 120ms time slice for example, won't work.
26+
Tasks that finish before their allocated time will hand execution back to the Scheduler.
3927

4028
The Arduino `delay()` function has been redefined to automatically use the FreeRTOS `vTaskDelay()` function when the delay required is one Tick or longer, by setting `configUSE_PORT_DELAY` to `1`, so that simple Arduino example sketches and tutorials work as expected. If you would like to measure a short millisecond delay of less than one Tick, then preferably use [`millis()`](https://www.arduino.cc/reference/en/language/functions/time/millis/) (or with greater granularity use [`micros()`](https://www.arduino.cc/reference/en/language/functions/time/micros/)) to achieve this outcome (for example see [BlinkWithoutDelay](https://docs.arduino.cc/built-in-examples/digital/BlinkWithoutDelay)). However, when the delay requested is less than one Tick then the original Arduino `delay()` function will be automatically selected.
4129

src/FreeRTOSVariant.h

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,89 @@ extern "C" {
5353
/* Watchdog Timer is 128kHz nominal, but 120 kHz at 5V DC and 25 degrees is actually more accurate, from data sheet. */
5454
#define configTICK_RATE_HZ ( (TickType_t)( (uint32_t)128000 >> (portUSE_WDTO + 11) ) ) // 2^11 = 2048 WDT scaler for 128kHz Timer
5555

56+
#undef portUSE_WDTO
57+
#define portUSE_TIMER0
58+
#define portTICK_PERIOD_MS 16
59+
/*
60+
* When a tick source other than WDT is used, configuring the tick source becomes the user's responsibility.
61+
* E.g., when using Timer0 for the tick source, you can use the following snippet:
62+
*
63+
* // Formula for the frequency is:
64+
* // f = F_CPU / (PRESCALER * (1 + COUNTER_TOP)
65+
* //
66+
* // Assuming the MCU clock of 16MHz, prescaler 1024 and counter top 249, the resulting tick period is 16 ms (62.5 Hz).
67+
* //
68+
* #define TICK_PERIOD_16MS 249
69+
* #define PRESCALER 1024
70+
* #if (portTICK_PERIOD_MS != (PRESCALER * (1 + TICK_PERIOD_16MS) * 1000 / F_CPU))
71+
* #warning portTICK_PERIOD_MS defined in FreeRTOSVariant.h differs from your timer configuration
72+
* #endif
73+
*
74+
* // For register TCCR0A:
75+
* #define NO_PWM (0 << COM0A1) | (0 << COM0A0) | (0 << COM0B1) | (0 << COM0B0)
76+
* #define MODE_CTC_TCCR0A (1 << WGM01) | (0 << WGM00)
77+
*
78+
* // For register TCCR0B:
79+
* #define MODE_CTC_TCCR0B (0 << WGM02)
80+
* #define PRESCALER_1024 (1 << CS02) | (0 << CS01) | (1 << CS00)
81+
*
82+
* // For register TIMSK0:
83+
* #define INTERRUPT_AT_TOP (1 << OCIE0A)
84+
*
85+
* extern "C"
86+
* void prvSetupTimerInterrupt( void )
87+
* {
88+
* // In case Arduino platform has pre-configured the timer,
89+
* // disable it before re-configuring here to avoid unpredicted results:
90+
* TIMSK0 = 0;
91+
*
92+
* // Now configure the timer:
93+
* TCCR0A = NO_PWM | MODE_CTC_TCCR0A;
94+
* TCCR0B = MODE_CTC_TCCR0B | PRESCALER_1024;
95+
* OCR0A = TICK_PERIOD_16MS;
96+
*
97+
* // Prevent missing the top and going into a possibly long wait until wrapping around:
98+
* TCNT0 = 0;
99+
*
100+
* // At this point the global interrupt flag is NOT YET enabled,
101+
* // so you're NOT starting to get the ISR calls until FreeRTOS enables it just before launching the scheduler.
102+
* TIMSK0 = INTERRUPT_AT_TOP;
103+
* }
104+
*/
105+
void prvSetupTimerInterrupt( void );
106+
107+
/*
108+
* When a tick source other than WDT is used, calling the scheduler becomes the user's responsibility.
109+
* E.g., when using Timer0 for the tick source, you'll have a timer compare IRS wherein you call portSCHEDULER_ISR().
110+
*
111+
* Implement your ISR handler efficiently:
112+
*
113+
* For PREEMPTIVE scheduler use a `naked` attribute to reduce the call overhead:
114+
*
115+
* ISR(portSCHEDULER_ISR, ISR_NAKED) __attribute__ ((hot, flatten)) {
116+
* portSchedulerTick();
117+
* __asm__ __volatile__ ( "reti" );
118+
* }
119+
*
120+
* The context is saved at the start of `portSchedulerTick()`, then the tick count is incremented, finally
121+
* the new context is loaded - so no dirtying occurs.
122+
*
123+
*
124+
* For COOPERATIVE scheduler, the context is not saved because no switching is intended; therefore `naked` attribute
125+
* cannot be applied because cooperative `portSchedulerTick()` dirties the context.
126+
*
127+
* ISR(portSCHEDULER_ISR) __attribute__ ((hot, flatten)) {
128+
* portSCHEDULER_ISR();
129+
* }
130+
*
131+
* Use ISR_NOBLOCK where there is an important timer running, that should preempt the scheduler:
132+
*
133+
* ISR(portSCHEDULER_ISR, ISR_NAKED ISR_NOBLOCK) __attribute__ ((hot, flatten));
134+
*
135+
* Attributes `hot` and `flatten` help inlining all the code found inside your ISR thus reducing the call overhead.
136+
*/
137+
void portSchedulerTick( void ) __attribute__ ((hot, flatten));
138+
56139
/*-----------------------------------------------------------*/
57140

58141
#ifndef INC_TASK_H

0 commit comments

Comments
 (0)