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
/*
* SuperTinyKernel(TM) RTOS: Lightweight High-Performance Deterministic C++ RTOS for Embedded Systems.
*
* Source: https://github.com/SuperTinyKernel-RTOS
*
* Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com>. All Rights Reserved.
* License: MIT License, see LICENSE for a full text.
*/
/*
* Periodic tasks with a period, a deadline and a start delay are scheduled by an EDF (or RM) scheduler.
* Hardware LED tasks have the highest priority and are triggered by a control task through pipes (non-blocking
* TryRead()/TryWrite() as HRT tasks must never block). The example checks the schedulability of the task set
* before starting the kernel and shows how to react on a deadline miss with the
* IPlatform::IEventOverrider (the RED LED is switched on).
*/
#include <stk.h>
#include <time/stk_time.h>
#include "example.h"
// for PipeT which is used as a non-blocking data pipe between Hard Real-Time (HRT) tasks which
// should not block to avoid missing the deadline
using namespace bsp;
// R2350 requires larger stack due to stack-memory heavy SDK API
#ifdef _PICO_H
enum { TASK_STACK_SIZE = 1024 };
#else
enum { TASK_STACK_SIZE = 256 };
#endif
#define USE_EDF 0
// One single-slot pipe per LED task. CtrlTask writes a command token; the
// corresponding HwLedTask drains it with TryRead (non-blocking, HRT-safe).
// Capacity = 1: CtrlTask produces at most one pending command per period.
template <stk::EAccessMode _AccessMode>
class HwLedTask final : public stk::Task<TASK_STACK_SIZE, _AccessMode>
{
uint8_t m_task_id;
public:
HwLedTask(uint8_t task_id) : m_task_id(task_id)
{}
private:
void Run() override
{
for (;;)
{
// activation token here but could be used as a useful command
uint8_t cmd;
// TryRead (NO_WAIT): HRT tasks must never block — poll and proceed
if (g_LedPipe[m_task_id].TryRead(cmd))
{
// switch on corresponding LED
Led::SwitchOnExclusive(static_cast<LedId>(cmd));
}
// do some other work in the task
for (volatile uint32_t i = 0; i < 1000; ++i);
}
}
void OnDeadlineMissed(uint32_t duration)
{
(void)duration;
}
};
template <stk::EAccessMode _AccessMode>
class CtrlTask final : public stk::Task<TASK_STACK_SIZE, _AccessMode>
{
void Run() override
{
uint8_t led = 0;
stk::time::PeriodicTrigger trigger(1000, true);
for (;;)
{
// do some other work in the task
for (volatile uint32_t i = 0; i < 3000; ++i);
if (trigger.Poll())
{
led = (led + 1) % LED_MAX;
// TryWrite: sole producer into a depth-1 pipe; pipe is always
// empty here by design, so this never blocks
g_LedPipe[led].TryWrite(led);
}
// wait for a next turn
}
}
void OnDeadlineMissed(uint32_t duration)
{
// actual duration of missed task
(void)duration;
}
};
// optional: you can override sleep and hard fault default behaviors
{
bool OnHardFault() override
{
// switch on Red LED as indication of the error
Led::SwitchOnExclusive(Led::RED);
// if handled inside this function then return true, otherwise event will be handled by the driver
// note: prior a call to this function a task which had deadline missed had a call to OnDeadlineMissed
return false;
}
};
void RunExample()
{
using namespace stk;
Led::InitAll(false);
enum { TASK_COUNT = 5 };
#if USE_EDF
typedef sched::SwitchStrategyEDF SchedulerType;
#else
typedef sched::SwitchStrategyRM SchedulerType;
#endif
// assume that hardware LED tasks have highest priority
static HwLedTask<ACCESS_PRIVILEGED> hwt0(0), hwt1(1), hwt2(2), hwt3(3);
// control task is sending commands to hardware tasks
static CtrlTask<ACCESS_USER> ctrl;
kernel.Initialize();
// optional: you can override sleep and hard fault default behaviors
static PlatformEventHandler event_overrider;
kernel.GetPlatform()->SetEventOverrider(&event_overrider);
#define MSEC(MS) GetTicksFromMs(MS, PERIODICITY_DEFAULT)
// periodicity deadline start delay
kernel.AddTask(&ctrl, MSEC(200), MSEC(100), MSEC(0));
kernel.AddTask(&hwt0, MSEC(200), MSEC(20), MSEC(0));
kernel.AddTask(&hwt1, MSEC(200), MSEC(20), MSEC(0));
kernel.AddTask(&hwt2, MSEC(200), MSEC(20), MSEC(0));
kernel.AddTask(&hwt3, MSEC(200), MSEC(20), MSEC(0));
#if !USE_EDF
auto wcrt_sched = SchedulabilityCheck::IsSchedulableWCRT<TASK_COUNT>(kernel.GetSwitchStrategy());
STK_ASSERT(wcrt_sched == true);
#endif
kernel.Start();
// shall not reach here
STK_ASSERT(false);
}
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.
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 void InitAll(bool init_state)
Definition led.h:40
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)
#define TASK_STACK_SIZE