SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
hrt/example.cpp
Go to the documentation of this file.
1/*
2 * SuperTinyKernel(TM) RTOS: Lightweight High-Performance Deterministic C++ RTOS for Embedded Systems.
3 *
4 * Source: https://github.com/SuperTinyKernel-RTOS
5 *
6 * Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com>. All Rights Reserved.
7 * License: MIT License, see LICENSE for a full text.
8 */
9
15
16/*
17 * Periodic tasks with a period, a deadline and a start delay are scheduled by an EDF (or RM) scheduler.
18 * Hardware LED tasks have the highest priority and are triggered by a control task through pipes (non-blocking
19 * TryRead()/TryWrite() as HRT tasks must never block). The example checks the schedulability of the task set
20 * before starting the kernel and shows how to react on a deadline miss with the
21 * IPlatform::IEventOverrider (the RED LED is switched on).
22 */
23
24#include <stk.h>
25#include <time/stk_time.h>
26#include "example.h"
27
28// for PipeT which is used as a non-blocking data pipe between Hard Real-Time (HRT) tasks which
29// should not block to avoid missing the deadline
30#include <sync/stk_sync_pipe.h>
31
32using namespace bsp;
33
34// R2350 requires larger stack due to stack-memory heavy SDK API
35#ifdef _PICO_H
36enum { TASK_STACK_SIZE = 1024 };
37#else
38enum { TASK_STACK_SIZE = 256 };
39#endif
40
41#define USE_EDF 0
42
43// One single-slot pipe per LED task. CtrlTask writes a command token; the
44// corresponding HwLedTask drains it with TryRead (non-blocking, HRT-safe).
45// Capacity = 1: CtrlTask produces at most one pending command per period.
47
48template <stk::EAccessMode _AccessMode>
49class HwLedTask final : public stk::Task<TASK_STACK_SIZE, _AccessMode>
50{
51 uint8_t m_task_id;
52
53public:
54 HwLedTask(uint8_t task_id) : m_task_id(task_id)
55 {}
56
57private:
58 void Run() override
59 {
60 for (;;)
61 {
62 // activation token here but could be used as a useful command
63 uint8_t cmd;
64
65 // TryRead (NO_WAIT): HRT tasks must never block — poll and proceed
66 if (g_LedPipe[m_task_id].TryRead(cmd))
67 {
68 // switch on corresponding LED
69 Led::SwitchOnExclusive(static_cast<LedId>(cmd));
70 }
71
72 // do some other work in the task
73 for (volatile uint32_t i = 0; i < 1000; ++i);
74
75 stk::Yield();
76 }
77 }
78
79 void OnDeadlineMissed(uint32_t duration)
80 {
81 (void)duration;
82 }
83};
84
85template <stk::EAccessMode _AccessMode>
86class CtrlTask final : public stk::Task<TASK_STACK_SIZE, _AccessMode>
87{
88 void Run() override
89 {
90 uint8_t led = 0;
91 stk::time::PeriodicTrigger trigger(1000, true);
92
93 for (;;)
94 {
95 // do some other work in the task
96 for (volatile uint32_t i = 0; i < 3000; ++i);
97
98 if (trigger.Poll())
99 {
100 led = (led + 1) % LED_MAX;
101
102 // TryWrite: sole producer into a depth-1 pipe; pipe is always
103 // empty here by design, so this never blocks
104 g_LedPipe[led].TryWrite(led);
105 }
106
107 // wait for a next turn
108 stk::Yield();
109 }
110 }
111
112 void OnDeadlineMissed(uint32_t duration)
113 {
114 // actual duration of missed task
115 (void)duration;
116 }
117};
118
119// optional: you can override sleep and hard fault default behaviors
121{
122 bool OnHardFault() override
123 {
124 // switch on Red LED as indication of the error
126
127 // if handled inside this function then return true, otherwise event will be handled by the driver
128 // note: prior a call to this function a task which had deadline missed had a call to OnDeadlineMissed
129 return false;
130 }
131};
132
134{
135 using namespace stk;
136
137 Led::InitAll(false);
138
139 enum { TASK_COUNT = 5 };
140
141#if USE_EDF
142 typedef sched::SwitchStrategyEDF SchedulerType;
143#else
144 typedef sched::SwitchStrategyRM SchedulerType;
145#endif
146
148
149 // assume that hardware LED tasks have highest priority
150 static HwLedTask<ACCESS_PRIVILEGED> hwt0(0), hwt1(1), hwt2(2), hwt3(3);
151
152 // control task is sending commands to hardware tasks
153 static CtrlTask<ACCESS_USER> ctrl;
154
155 kernel.Initialize();
156
157 // optional: you can override sleep and hard fault default behaviors
158 static PlatformEventHandler event_overrider;
159 kernel.GetPlatform()->SetEventOverrider(&event_overrider);
160
161#define MSEC(MS) GetTicksFromMs(MS, PERIODICITY_DEFAULT)
162
163 // periodicity deadline start delay
164 kernel.AddTask(&ctrl, MSEC(200), MSEC(100), MSEC(0));
165 kernel.AddTask(&hwt0, MSEC(200), MSEC(20), MSEC(0));
166 kernel.AddTask(&hwt1, MSEC(200), MSEC(20), MSEC(0));
167 kernel.AddTask(&hwt2, MSEC(200), MSEC(20), MSEC(0));
168 kernel.AddTask(&hwt3, MSEC(200), MSEC(20), MSEC(0));
169
170#if !USE_EDF
171 auto wcrt_sched = SchedulabilityCheck::IsSchedulableWCRT<TASK_COUNT>(kernel.GetSwitchStrategy());
172 STK_ASSERT(wcrt_sched == true);
173#endif
174
175 kernel.Start();
176
177 // shall not reach here
178 STK_ASSERT(false);
179}
180
LedId
Definition led.h:16
@ LED_MAX
Definition led.h:22
Top-level STK include. Provides the Kernel class template and all built-in task-switching strategies.
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
Implementation of synchronization primitives: stk::sync::Pipe - runtime-sized byte-stream pipe over a...
Collection of time-related primitives (stk::time namespace).
Namespace of STK package.
static void Yield()
Notify scheduler to switch to the next runnable task.
Definition stk_helper.h:562
SwitchStrategyMonotonic< MSS_TYPE_RATE > SwitchStrategyRM
Shorthand alias for SwitchStrategyMonotonic<MSS_TYPE_RATE>: Rate-Monotonic scheduling (shorter schedu...
Definition cpu.h:17
Concrete implementation of IKernel.
Definition stk.h:102
void Start() override
Start the scheduler. This call does not return until all tasks have exited (KERNEL_DYNAMIC mode) or i...
Definition stk.h:1999
EAddResult AddTask(ITask *user_task) override
Register task for a soft real-time (SRT) scheduling.
Definition stk.h:1465
IPlatform * GetPlatform() override
Get platform driver instance owned by this kernel.
Definition stk.h:2034
void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT) override
Initialize kernel.
Definition stk.h:1425
ITaskSwitchStrategy * GetSwitchStrategy() override
Get task-switching strategy instance owned by this kernel.
Definition stk.h:2039
virtual void SetEventOverrider(IEventOverrider *overrider, bool non_secure=false)=0
Set platform event overrider.
Interface for a platform event overrider.
Partial implementation of the user task.
Definition stk_helper.h:98
Earliest Deadline First (EDF) scheduling strategy: always selects the runnable task with the least ti...
Thread-safe, type-safe FIFO communication pipe with internal storage.
Lightweight periodic trigger: returns true once per configured period when polled.
bool Poll()
Check whether the scheduled trigger time has been reached.
bool OnHardFault() override
Called by Kernel when hard fault happens.
void OnDeadlineMissed(uint32_t duration)
Called by the scheduler if deadline of the task is missed when Kernel is operating in Hard Real-Time ...
void Run() override
Entry point of the user task.
static constexpr Id RED
Definition led.h:36
static void InitAll(bool init_state)
Definition led.h:40
static void SwitchOnExclusive(Id led)
Definition led.h:48
void OnDeadlineMissed(uint32_t duration)
Called by the scheduler if deadline of the task is missed when Kernel is operating in Hard Real-Time ...
void Run() override
Entry point of the user task.
uint8_t m_task_id
HwLedTask(uint8_t task_id)
static stk::sync::PipeT< uint8_t, 1 > g_LedPipe[LED_MAX]
#define MSEC(MS)
void RunExample()
#define TASK_STACK_SIZE