框架建模
框架抽象
模块划分
Scheduler
#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
#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
任务接口管理
#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
应用初始化
#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")
}
流水灯任务实现
#include "app.h"
#include "int_led.h"
void app_ui_led_flow(void) {
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;
}
}
按键扫描任务实现
#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();
}