1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#include "timers.h"
// 传感器数据结构
typedef struct {
uint8_t sensor_id;
float value;
uint32_t timestamp;
} SensorData_t;
// 句柄定义
QueueHandle_t xSensorQueue;
SemaphoreHandle_t xI2CMutex;
TimerHandle_t xSampleTimer;
// 数据采样回调(定时器)
void vSampleTimerCallback(TimerHandle_t xTimer) {
static uint8_t sensor_id = 0;
SensorData_t data;
data.sensor_id = sensor_id;
data.value = read_sensor(sensor_id);
data.timestamp = xTaskGetTickCount();
xQueueSendFromISR(xSensorQueue, &data, NULL);
sensor_id = (sensor_id + 1) % 4;
}
// 数据处理任务
void vDataProcessTask(void *pvParameters) {
SensorData_t data;
while (1) {
if (xQueueReceive(xSensorQueue, &data, portMAX_DELAY) == pdPASS) {
printf("Sensor %d: %.2f @ %lu\n",
data.sensor_id, data.value, data.timestamp);
}
}
}
// 显示任务
void vDisplayTask(void *pvParameters) {
while (1) {
update_display();
vTaskDelay(pdMS_TO_TICKS(100));
}
}
int main(void) {
// 创建队列
xSensorQueue = xQueueCreate(20, sizeof(SensorData_t));
// 创建互斥量
xI2CMutex = xSemaphoreCreateMutex();
// 创建定时器
xSampleTimer = xTimerCreate(
"SampleTimer",
pdMS_TO_TICKS(50),
pdTRUE,
NULL,
vSampleTimerCallback
);
if (xSensorQueue && xI2CMutex && xSampleTimer) {
// 创建任务
xTaskCreate(vDataProcessTask, "Process", 256, NULL, 2, NULL);
xTaskCreate(vDisplayTask, "Display", 128, NULL, 1, NULL);
// 启动定时器
xTimerStart(xSampleTimer, 0);
// 启动调度器
vTaskStartScheduler();
}
while (1);
return 0;
}
|