Skip to content

Repository files navigation

RTOS Task Scheduler ⚙️

A minimal, preemptive Real-Time Operating System kernel built from scratch for ARM Cortex-M processors.

一个从零构建的、面向 ARM Cortex-M 处理器的极简抢占式实时操作系统内核。


Features / 功能特性

Kernel / 内核

  • Priority-based preemptive scheduling — 8 priority levels (0 = highest) 基于优先级的抢占式调度 — 8 个优先级(0 = 最高)
  • Round-robin for tasks at the same priority level 同优先级任务采用时间片轮转调度
  • Configurable time slicing — default 10ms per task 可配置时间片 — 默认每任务 10ms
  • Tick timer — 1kHz SysTick for precise timing 滴答定时器 — 1kHz SysTick 精确定时

Task Management / 任务管理

  • Create, delete, suspend, resume tasks 创建、删除、挂起、恢复任务
  • Task delay (blocking sleep) 任务延时(阻塞式睡眠)
  • Dynamic priority change 动态优先级调整
  • Stack overflow detection (via watermark) 栈溢出检测(水位标记法)
  • Up to 16 concurrent tasks 最多支持 16 个并发任务

Synchronization / 同步机制

  • Mutex with priority inheritance — prevents priority inversion 互斥锁(带优先级继承)— 防止优先级反转
  • Semaphore — binary and counting, with timeout 信号量 — 支持二值和计数模式,带超时
  • Message Queue — typed inter-task communication, blocking send/receive 消息队列 — 类型化任务间通信,阻塞式收发

Timers & Memory / 定时器与内存

  • Software timers — one-shot and periodic modes 软件定时器 — 单次和周期模式
  • Memory pool — fixed-size block allocator, O(1) alloc/free 内存池 — 固定大小块分配器,O(1) 分配/释放

Architecture / 架构

  • ARM Cortex-M3/M4 support
  • PendSV context switch (hardware-assisted)
  • SysTick tick timer
  • C++17 with zero-overhead abstractions
  • ~2KB Flash, ~256B RAM (minimal config)

System Architecture / 系统架构

┌──────────────────────────────────────┐
│           Application Tasks          │
│   (Producer, Consumer, Logger, ...)  │
│            应用任务层                 │
├──────────────────────────────────────┤
│          RTOS Kernel API             │
│  ┌────────┐ ┌──────┐ ┌──────────┐   │
│  │Scheduler│ │Mutex │ │ MsgQueue │   │
│  │(8-prio │ │ (PI) │ │ (FIFO)   │   │
│  │ RR)    │ │      │ │          │   │
│  └───┬────┘ └──┬───┘ └────┬─────┘   │
│      └─────────┼──────────┘         │
│           ┌────▼────┐               │
│           │ PendSV  │ Context       │
│           │ Handler │ Switch        │
│           └─────────┘               │
├──────────────────────────────────────┤
│    Hardware Abstraction Layer (HAL)  │
│    硬件抽象层                        │
│    SysTick (1kHz) | PendSV | WFI    │
├──────────────────────────────────────┤
│    ARM Cortex-M4 (STM32F4xx)        │
│    168MHz | FPU | NVIC | SysTick    │
└──────────────────────────────────────┘

Project Structure / 项目结构

rtos-task-scheduler/
├── include/
│   └── kernel.h              # Main API header (C++17) / 主API头文件
├── src/
│   └── kernel.cpp            # Kernel implementation / 内核实现
├── port/
│   └── arm_cortex_m/
│       ├── port.h            # Hardware registers / 硬件寄存器定义
│       └── port.cpp          # Context switch (PendSV ASM) / 上下文切换
├── examples/
│   ├── blink/                # LED blink (basic) / LED闪烁(基础)
│   │   └── main.cpp
│   └── multi_task/           # Producer-Consumer (advanced) / 生产者-消费者(进阶)
│       └── main.cpp
├── linker.ld                 # STM32F446RE linker script / 链接脚本
├── CMakeLists.txt            # Build system / 构建系统
├── toolchain-arm.cmake       # Cross-compilation toolchain / 交叉编译工具链
└── Makefile                  # Convenience build commands / 便捷构建命令

Quick Start / 快速开始

Prerequisites / 前置条件

# Install ARM GCC toolchain / 安装 ARM GCC 工具链
# Windows: download from arm.com
# Linux: sudo apt install gcc-arm-none-eabi

# Install ST-Link (for flashing) / 安装 ST-Link(用于烧录)
# https://github.com/stlink-org/stlink

Build / 编译

mkdir build && cd build
cmake -DCMAKE_TOOLCHAIN_FILE=../toolchain-arm.cmake ..
make -j4

Flash / 烧录

# Flash blink example / 烧录闪烁示例
st-flash write build/blink.bin 0x08000000

# Flash multi-task example / 烧录多任务示例
st-flash write build/multi_task.bin 0x08000000

Examples / 示例

1. LED Blink (Basic) / LED 闪烁(基础)

#include "kernel.h"

void taskBlink(void*) {
    while (true) {
        setLED(true);
        rtos::taskDelayMs(500);
        setLED(false);
        rtos::taskDelayMs(500);
    }
}

int main() {
    rtos::kernelInit();

    rtos::TaskConfig cfg;
    cfg.name = "blink";
    cfg.func = taskBlink;
    cfg.stackSize = 256;
    cfg.priority = 2;
    rtos::taskCreate(cfg);

    rtos::kernelStart(); // Never returns / 永不返回
}

2. Mutex (Priority Inheritance) / 互斥锁(优先级继承)

rtos::Mutex* mtx;
rtos::mutexCreate(&mtx);

void taskA(void*) {
    while (true) {
        rtos::mutexLock(mtx);
        // Critical section - priority automatically boosted
        // 临界区 — 如果有更高优先级任务在等待,优先级会自动提升
        rtos::mutexUnlock(mtx);
        rtos::taskDelayMs(100);
    }
}

3. Message Queue / 消息队列

struct Data { float temp; float hum; };
Data buffer[10];
rtos::MsgQueue* mq;
rtos::msgqCreate(&mq, buffer, sizeof(Data), 10);

void producer(void*) {
    Data d = {25.5f, 60.0f};
    rtos::msgqSend(mq, &d); // Blocks if full / 队列满时阻塞
}

void consumer(void*) {
    Data d;
    rtos::msgqReceive(mq, &d, 1000); // 1s timeout / 1秒超时
}

4. Software Timer / 软件定时器

void onTimer(void*) {
    // Runs every 1000ms / 每1000ms执行一次
    toggleLED();
}

rtos::Timer* tmr;
rtos::timerCreate(&tmr, onTimer, nullptr, 1000, rtos::TimerMode::PERIODIC);
rtos::timerStart(tmr);

API Reference / API 参考

Task / 任务

  • taskCreate(config, &id) — Create a new task / 创建新任务
  • taskDelete(id) — Delete a task / 删除任务
  • taskSuspend(id) — Suspend a task / 挂起任务
  • taskResume(id) — Resume a suspended task / 恢复任务
  • taskDelayMs(ms) — Sleep for N milliseconds / 睡眠 N 毫秒
  • taskSetPriority(id, prio) — Change task priority / 更改任务优先级

Mutex / 互斥锁

  • mutexCreate(&mtx) — Create mutex / 创建互斥锁
  • mutexLock(mtx, timeout) — Lock (with priority inheritance) / 加锁(带优先级继承)
  • mutexUnlock(mtx) — Unlock / 解锁

Semaphore / 信号量

  • semCreate(&sem, initial, max) — Create semaphore / 创建信号量
  • semWait(sem, timeout) — Wait (decrement) / 等待(减操作)
  • semPost(sem) — Signal (increment) / 释放(加操作)

Message Queue / 消息队列

  • msgqCreate(&mq, buf, size, cap) — Create queue / 创建队列
  • msgqSend(mq, msg, timeout) — Send message / 发送消息
  • msgqReceive(mq, msg, timeout) — Receive message / 接收消息

Timer / 定时器

  • timerCreate(&tmr, cb, ctx, ms, mode) — Create timer / 创建定时器
  • timerStart(tmr) — Start timer / 启动定时器
  • timerStop(tmr) — Stop timer / 停止定时器

Hardware Requirements / 硬件要求

  • STM32F4xx (tested on STM32F446RE) / STM32F4xx(在 STM32F446RE 上测试)
  • ARM Cortex-M4 with FPU / 带 FPU 的 ARM Cortex-M4
  • 168MHz clock / 168MHz 时钟
  • ST-Link debugger / ST-Link 调试器

License / 许可证

MIT License

Author / 作者

Isaac — Diploma in Electronic Engineering, TAR UMT

Built with ❤️ for learning RTOS internals 用 ❤️ 构建,用于学习 RTOS 内部原理

About

Custom RTOS Kernel for ARM Cortex-M | 自制 RTOS 内核

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages