简易版裸机多任务调度框架


框架建模

框架抽象

image-20241126093047180

模块划分

image-20241126094329449

Scheduler

//
// Created by 86157 on 2024/11/25.
//

#ifndef __SCHEDULER_H
#define __SCHEDULER_H

#include "gd32f4xx.h"
#include "stdbool.h"

typedef void (*task_function_t)(void);

typedef enum {
    TASK_READY,
    TASK_RUNNING,
    TASK_WAITING
} task_state_t;

typedef struct {
    task_state_t  task_state;
    uint16_t task_interval_ms;
    uint16_t task_time_waiting_ms;
    task_function_t task_function;
} task_t;

void task_update(void);
void task_execute(void);

#endif//__SCHEDULER_H
//
// Created by 86157 on 2024/11/25.
//

#include "scheduler.h"
#include "app.h"

static task_t tasks[] = {
        TASK_READY, 400, 0, app_ui_led_flow,
        TASK_READY, 20, 0, app_debug_key_scan};

static const uint8_t TASK_SIZE = sizeof(tasks) / sizeof(tasks[0]);

void task_update(void) {
    for (uint16_t i = 0; i < TASK_SIZE; ++i) {
        tasks[i].task_time_waiting_ms++;
        if (tasks[i].task_time_waiting_ms >= tasks[i].task_interval_ms) {
            tasks[i].task_state = TASK_READY;
            tasks[i].task_time_waiting_ms = 0;
        }
    }
}

void task_execute(void) {
    for (uint16_t i = 0; i < TASK_SIZE; ++i) {
        if (tasks[i].task_state == TASK_READY) {
            tasks[i].task_state = TASK_RUNNING;
            tasks[i].task_function();
            tasks[i].task_state = TASK_WAITING;
        }
    }
}

App

任务接口管理

//
// Created by 86157 on 2024/11/25.
//

#ifndef APP_H
#define APP_H

#include "logger.h"

void app_init(void);
void app_ui_led_flow(void);
void app_debug_key_scan(void);

#endif//APP_H

应用初始化

//
// Created by 86157 on 2024/11/25.
//
#include "app.h"
#include "int_led.h"
#include "int_key.h"

void app_init(void) {
    int_led_init();
    int_key_init();
    LOG_DEBUG("app_init done")
}

流水灯任务实现

//
// Created by 86157 on 2024/11/25.
//
#include "app.h"
#include "int_led.h"

void app_ui_led_flow(void) {
//    LOG_DEBUG("app_ui_led_flow invoke")
    static uint8_t led_index = LED1;
    int_led_on(led_index, 0);
    led_index++;
    if (led_index == LED_SIZE) {
        int_led_off_all(0);
        led_index = LED1;
    }
}

按键扫描任务实现

//
// Created by 86157 on 2024/11/25.
//
#include "app.h"
#include "int_key.h"

void app_debug_key_scan(void) {
    int_key_scan();
}

void key_up_callback(KEY_NO key_no) {
    LOG_DEBUG("key up")
}
void key_down_callback(KEY_NO key_no) {
    LOG_DEBUG("key down")
}

定时器更新任务状态

void hal_timer5_update_callback() {
    task_update();
}

文章作者: 安文
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 安文 !
  目录