C语言应用场景:嵌入式系统开发

C语言在嵌入式系统开发中占据着核心地位,其高效性、可移植性和对硬件的直接控制能力使其成为嵌入式开发的首选语言。本文将深入探讨C语言在嵌入式系统中的各种应用场景和关键技术。

1. 嵌入式系统概述

1.1 嵌入式系统特点

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
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

// 嵌入式系统的典型特征
typedef struct {
uint32_t cpu_frequency; // CPU频率 (Hz)
uint32_t ram_size; // RAM大小 (字节)
uint32_t flash_size; // Flash大小 (字节)
bool real_time_required; // 是否需要实时性
bool low_power_required; // 是否需要低功耗
uint8_t gpio_pins; // GPIO引脚数量
} EmbeddedSystemSpec;

// 典型的嵌入式系统规格
EmbeddedSystemSpec microcontroller_specs[] = {
// Arduino Uno (ATmega328P)
{16000000, 2048, 32768, false, false, 14},

// STM32F103 (ARM Cortex-M3)
{72000000, 20480, 131072, true, true, 37},

// ESP32 (双核)
{240000000, 520192, 4194304, false, true, 34},

// Raspberry Pi Pico (RP2040)
{133000000, 264192, 2097152, false, true, 26}
};

void print_system_specs() {
printf("=== 典型嵌入式系统规格 ===\n");

const char* names[] = {
"Arduino Uno", "STM32F103", "ESP32", "Raspberry Pi Pico"
};

for (int i = 0; i < 4; i++) {
EmbeddedSystemSpec* spec = &microcontroller_specs[i];
printf("\n%s:\n", names[i]);
printf(" CPU频率: %.1f MHz\n", spec->cpu_frequency / 1000000.0);
printf(" RAM: %.1f KB\n", spec->ram_size / 1024.0);
printf(" Flash: %.1f KB\n", spec->flash_size / 1024.0);
printf(" 实时性: %s\n", spec->real_time_required ? "是" : "否");
printf(" 低功耗: %s\n", spec->low_power_required ? "是" : "否");
printf(" GPIO引脚: %d\n", spec->gpio_pins);
}
printf("\n");
}

int main() {
print_system_specs();
return 0;
}

1.2 C语言在嵌入式开发中的优势

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdio.h>
#include <stdint.h>
#include <string.h>

// 演示C语言的内存效率
void memory_efficiency_demo() {
printf("=== C语言内存效率演示 ===\n");

// 基本数据类型大小
printf("基本数据类型大小:\n");
printf(" char: %zu 字节\n", sizeof(char));
printf(" int: %zu 字节\n", sizeof(int));
printf(" float: %zu 字节\n", sizeof(float));
printf(" double: %zu 字节\n", sizeof(double));
printf(" 指针: %zu 字节\n", sizeof(void*));

// 结构体内存布局
typedef struct {
uint8_t status; // 1字节
uint16_t value; // 2字节
uint32_t timestamp; // 4字节
} SensorData;

typedef struct __attribute__((packed)) {
uint8_t status; // 1字节
uint16_t value; // 2字节
uint32_t timestamp; // 4字节
} PackedSensorData;

printf("\n结构体内存使用:\n");
printf(" 普通结构体: %zu 字节\n", sizeof(SensorData));
printf(" 紧凑结构体: %zu 字节\n", sizeof(PackedSensorData));

// 数组vs指针
char array[100];
char* pointer = array;

printf("\n数组vs指针:\n");
printf(" 数组大小: %zu 字节\n", sizeof(array));
printf(" 指针大小: %zu 字节\n", sizeof(pointer));

printf("\n");
}

// 演示直接硬件访问
#define GPIO_BASE_ADDR 0x40020000
#define GPIO_MODER_OFFSET 0x00
#define GPIO_ODR_OFFSET 0x14

// 模拟寄存器访问(实际开发中会是真实的硬件地址)
static uint32_t simulated_gpio_moder = 0;
static uint32_t simulated_gpio_odr = 0;

// 寄存器访问宏
#define REG32(addr) (*((volatile uint32_t*)(addr)))

// 模拟寄存器读写(用于演示)
uint32_t read_register(uint32_t addr) {
if (addr == GPIO_BASE_ADDR + GPIO_MODER_OFFSET) {
return simulated_gpio_moder;
} else if (addr == GPIO_BASE_ADDR + GPIO_ODR_OFFSET) {
return simulated_gpio_odr;
}
return 0;
}

void write_register(uint32_t addr, uint32_t value) {
if (addr == GPIO_BASE_ADDR + GPIO_MODER_OFFSET) {
simulated_gpio_moder = value;
} else if (addr == GPIO_BASE_ADDR + GPIO_ODR_OFFSET) {
simulated_gpio_odr = value;
}
}

// GPIO控制函数
void gpio_set_mode(uint8_t pin, uint8_t mode) {
uint32_t moder_addr = GPIO_BASE_ADDR + GPIO_MODER_OFFSET;
uint32_t moder_value = read_register(moder_addr);

// 清除对应位
moder_value &= ~(0x3 << (pin * 2));
// 设置新模式
moder_value |= (mode << (pin * 2));

write_register(moder_addr, moder_value);

printf("设置GPIO%d模式为%d,MODER寄存器值: 0x%08X\n",
pin, mode, moder_value);
}

void gpio_set_output(uint8_t pin, bool state) {
uint32_t odr_addr = GPIO_BASE_ADDR + GPIO_ODR_OFFSET;
uint32_t odr_value = read_register(odr_addr);

if (state) {
odr_value |= (1 << pin); // 设置位
} else {
odr_value &= ~(1 << pin); // 清除位
}

write_register(odr_addr, odr_value);

printf("设置GPIO%d输出%s,ODR寄存器值: 0x%08X\n",
pin, state ? "高" : "低", odr_value);
}

void hardware_access_demo() {
printf("=== 直接硬件访问演示 ===\n");

// 配置GPIO引脚为输出模式
gpio_set_mode(5, 1); // 模式1 = 输出
gpio_set_mode(6, 1);

// 控制GPIO输出
gpio_set_output(5, true); // 点亮LED
gpio_set_output(6, false); // 熄灭LED

printf("\n");
}

int main() {
memory_efficiency_demo();
hardware_access_demo();
return 0;
}

2. 硬件抽象层(HAL)设计

2.1 GPIO抽象层

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

// GPIO引脚模式枚举
typedef enum {
GPIO_MODE_INPUT,
GPIO_MODE_OUTPUT,
GPIO_MODE_ALTERNATE,
GPIO_MODE_ANALOG
} gpio_mode_t;

// GPIO引脚状态枚举
typedef enum {
GPIO_STATE_LOW = 0,
GPIO_STATE_HIGH = 1
} gpio_state_t;

// GPIO引脚配置结构体
typedef struct {
uint8_t port; // 端口号 (A, B, C...)
uint8_t pin; // 引脚号 (0-15)
gpio_mode_t mode; // 引脚模式
bool pull_up; // 是否启用上拉
bool pull_down; // 是否启用下拉
uint8_t speed; // 输出速度 (0-3)
} gpio_config_t;

// GPIO HAL接口
typedef struct {
void (*init)(const gpio_config_t* config);
void (*set_output)(uint8_t port, uint8_t pin, gpio_state_t state);
gpio_state_t (*read_input)(uint8_t port, uint8_t pin);
void (*toggle)(uint8_t port, uint8_t pin);
} gpio_hal_t;

// 模拟的GPIO状态存储
static uint16_t gpio_output_states[8] = {0}; // 支持8个端口
static uint16_t gpio_input_states[8] = {0};

// STM32 GPIO HAL实现
void stm32_gpio_init(const gpio_config_t* config) {
printf("[STM32] 初始化GPIO %c%d,模式: %d\n",
'A' + config->port, config->pin, config->mode);

if (config->pull_up) {
printf("[STM32] 启用上拉电阻\n");
}
if (config->pull_down) {
printf("[STM32] 启用下拉电阻\n");
}
}

void stm32_gpio_set_output(uint8_t port, uint8_t pin, gpio_state_t state) {
if (state == GPIO_STATE_HIGH) {
gpio_output_states[port] |= (1 << pin);
} else {
gpio_output_states[port] &= ~(1 << pin);
}

printf("[STM32] 设置GPIO %c%d = %s\n",
'A' + port, pin, state ? "HIGH" : "LOW");
}

gpio_state_t stm32_gpio_read_input(uint8_t port, uint8_t pin) {
gpio_state_t state = (gpio_input_states[port] & (1 << pin)) ?
GPIO_STATE_HIGH : GPIO_STATE_LOW;
printf("[STM32] 读取GPIO %c%d = %s\n",
'A' + port, pin, state ? "HIGH" : "LOW");
return state;
}

void stm32_gpio_toggle(uint8_t port, uint8_t pin) {
gpio_output_states[port] ^= (1 << pin);
gpio_state_t new_state = (gpio_output_states[port] & (1 << pin)) ?
GPIO_STATE_HIGH : GPIO_STATE_LOW;
printf("[STM32] 翻转GPIO %c%d = %s\n",
'A' + port, pin, new_state ? "HIGH" : "LOW");
}

// Arduino GPIO HAL实现
void arduino_gpio_init(const gpio_config_t* config) {
printf("[Arduino] 初始化数字引脚 %d,模式: %s\n",
config->pin,
config->mode == GPIO_MODE_OUTPUT ? "OUTPUT" : "INPUT");
}

void arduino_gpio_set_output(uint8_t port, uint8_t pin, gpio_state_t state) {
printf("[Arduino] digitalWrite(%d, %s)\n",
pin, state ? "HIGH" : "LOW");
}

gpio_state_t arduino_gpio_read_input(uint8_t port, uint8_t pin) {
// 模拟读取
gpio_state_t state = GPIO_STATE_LOW;
printf("[Arduino] digitalRead(%d) = %s\n",
pin, state ? "HIGH" : "LOW");
return state;
}

void arduino_gpio_toggle(uint8_t port, uint8_t pin) {
printf("[Arduino] 翻转数字引脚 %d\n", pin);
}

// HAL实例
gpio_hal_t stm32_gpio_hal = {
.init = stm32_gpio_init,
.set_output = stm32_gpio_set_output,
.read_input = stm32_gpio_read_input,
.toggle = stm32_gpio_toggle
};

gpio_hal_t arduino_gpio_hal = {
.init = arduino_gpio_init,
.set_output = arduino_gpio_set_output,
.read_input = arduino_gpio_read_input,
.toggle = arduino_gpio_toggle
};

// 应用层LED控制
typedef struct {
uint8_t port;
uint8_t pin;
gpio_hal_t* hal;
bool is_on;
} led_t;

void led_init(led_t* led, uint8_t port, uint8_t pin, gpio_hal_t* hal) {
led->port = port;
led->pin = pin;
led->hal = hal;
led->is_on = false;

gpio_config_t config = {
.port = port,
.pin = pin,
.mode = GPIO_MODE_OUTPUT,
.pull_up = false,
.pull_down = false,
.speed = 2
};

hal->init(&config);
}

void led_on(led_t* led) {
led->hal->set_output(led->port, led->pin, GPIO_STATE_HIGH);
led->is_on = true;
}

void led_off(led_t* led) {
led->hal->set_output(led->port, led->pin, GPIO_STATE_LOW);
led->is_on = false;
}

void led_toggle(led_t* led) {
led->hal->toggle(led->port, led->pin);
led->is_on = !led->is_on;
}

void gpio_hal_demo() {
printf("=== GPIO硬件抽象层演示 ===\n");

// STM32平台LED控制
printf("\nSTM32平台LED控制:\n");
led_t stm32_led;
led_init(&stm32_led, 0, 5, &stm32_gpio_hal); // GPIOA5

led_on(&stm32_led);
led_off(&stm32_led);
led_toggle(&stm32_led);

// Arduino平台LED控制
printf("\nArduino平台LED控制:\n");
led_t arduino_led;
led_init(&arduino_led, 0, 13, &arduino_gpio_hal); // 数字引脚13

led_on(&arduino_led);
led_off(&arduino_led);
led_toggle(&arduino_led);

printf("\n");
}

int main() {
gpio_hal_demo();
return 0;
}

2.2 串口通信抽象层

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>

// 串口配置参数
typedef enum {
UART_BAUD_9600 = 9600,
UART_BAUD_115200 = 115200,
UART_BAUD_230400 = 230400
} uart_baudrate_t;

typedef enum {
UART_DATABITS_8 = 8,
UART_DATABITS_9 = 9
} uart_databits_t;

typedef enum {
UART_PARITY_NONE,
UART_PARITY_EVEN,
UART_PARITY_ODD
} uart_parity_t;

typedef enum {
UART_STOPBITS_1,
UART_STOPBITS_2
} uart_stopbits_t;

// 串口配置结构体
typedef struct {
uint8_t uart_id;
uart_baudrate_t baudrate;
uart_databits_t databits;
uart_parity_t parity;
uart_stopbits_t stopbits;
bool flow_control;
} uart_config_t;

// 串口HAL接口
typedef struct {
bool (*init)(const uart_config_t* config);
bool (*send_byte)(uint8_t uart_id, uint8_t data);
bool (*send_data)(uint8_t uart_id, const uint8_t* data, size_t length);
bool (*receive_byte)(uint8_t uart_id, uint8_t* data, uint32_t timeout_ms);
size_t (*receive_data)(uint8_t uart_id, uint8_t* buffer, size_t max_length, uint32_t timeout_ms);
bool (*is_tx_complete)(uint8_t uart_id);
size_t (*get_rx_count)(uint8_t uart_id);
} uart_hal_t;

// 模拟串口缓冲区
#define UART_BUFFER_SIZE 256
static uint8_t uart_tx_buffer[4][UART_BUFFER_SIZE];
static uint8_t uart_rx_buffer[4][UART_BUFFER_SIZE];
static size_t uart_tx_count[4] = {0};
static size_t uart_rx_count[4] = {0};

// STM32 UART HAL实现
bool stm32_uart_init(const uart_config_t* config) {
printf("[STM32] 初始化UART%d:\n", config->uart_id);
printf(" 波特率: %d\n", config->baudrate);
printf(" 数据位: %d\n", config->databits);
printf(" 校验位: %s\n",
config->parity == UART_PARITY_NONE ? "无" :
config->parity == UART_PARITY_EVEN ? "偶" : "奇");
printf(" 停止位: %d\n", config->stopbits + 1);
printf(" 流控制: %s\n", config->flow_control ? "启用" : "禁用");

// 清空缓冲区
uart_tx_count[config->uart_id] = 0;
uart_rx_count[config->uart_id] = 0;

return true;
}

bool stm32_uart_send_byte(uint8_t uart_id, uint8_t data) {
if (uart_tx_count[uart_id] < UART_BUFFER_SIZE) {
uart_tx_buffer[uart_id][uart_tx_count[uart_id]++] = data;
printf("[STM32] UART%d发送: 0x%02X ('%c')\n",
uart_id, data, (data >= 32 && data < 127) ? data : '.');
return true;
}
return false;
}

bool stm32_uart_send_data(uint8_t uart_id, const uint8_t* data, size_t length) {
printf("[STM32] UART%d发送数据 (%zu字节): ", uart_id, length);
for (size_t i = 0; i < length; i++) {
if (stm32_uart_send_byte(uart_id, data[i])) {
printf("%02X ", data[i]);
} else {
printf("\n[STM32] 发送缓冲区满\n");
return false;
}
}
printf("\n");
return true;
}

bool stm32_uart_receive_byte(uint8_t uart_id, uint8_t* data, uint32_t timeout_ms) {
// 模拟接收(实际中会从硬件FIFO读取)
if (uart_rx_count[uart_id] > 0) {
*data = uart_rx_buffer[uart_id][--uart_rx_count[uart_id]];
printf("[STM32] UART%d接收: 0x%02X\n", uart_id, *data);
return true;
}
printf("[STM32] UART%d接收超时\n", uart_id);
return false;
}

size_t stm32_uart_receive_data(uint8_t uart_id, uint8_t* buffer, size_t max_length, uint32_t timeout_ms) {
size_t received = 0;
printf("[STM32] UART%d接收数据 (最大%zu字节)\n", uart_id, max_length);

// 模拟接收一些数据
const char* test_data = "Hello";
size_t test_len = strlen(test_data);
size_t copy_len = (test_len < max_length) ? test_len : max_length;

memcpy(buffer, test_data, copy_len);
received = copy_len;

printf("[STM32] 实际接收: %zu字节\n", received);
return received;
}

bool stm32_uart_is_tx_complete(uint8_t uart_id) {
return true; // 模拟发送完成
}

size_t stm32_uart_get_rx_count(uint8_t uart_id) {
return uart_rx_count[uart_id];
}

// Arduino串口HAL实现
bool arduino_uart_init(const uart_config_t* config) {
printf("[Arduino] Serial.begin(%d)\n", config->baudrate);
return true;
}

bool arduino_uart_send_byte(uint8_t uart_id, uint8_t data) {
printf("[Arduino] Serial.write(0x%02X)\n", data);
return true;
}

bool arduino_uart_send_data(uint8_t uart_id, const uint8_t* data, size_t length) {
printf("[Arduino] Serial.write(data, %zu)\n", length);
return true;
}

bool arduino_uart_receive_byte(uint8_t uart_id, uint8_t* data, uint32_t timeout_ms) {
printf("[Arduino] Serial.read()\n");
*data = 'A'; // 模拟接收
return true;
}

size_t arduino_uart_receive_data(uint8_t uart_id, uint8_t* buffer, size_t max_length, uint32_t timeout_ms) {
printf("[Arduino] Serial.readBytes(buffer, %zu)\n", max_length);
return 0; // 模拟无数据
}

bool arduino_uart_is_tx_complete(uint8_t uart_id) {
return true;
}

size_t arduino_uart_get_rx_count(uint8_t uart_id) {
return 0;
}

// HAL实例
uart_hal_t stm32_uart_hal = {
.init = stm32_uart_init,
.send_byte = stm32_uart_send_byte,
.send_data = stm32_uart_send_data,
.receive_byte = stm32_uart_receive_byte,
.receive_data = stm32_uart_receive_data,
.is_tx_complete = stm32_uart_is_tx_complete,
.get_rx_count = stm32_uart_get_rx_count
};

uart_hal_t arduino_uart_hal = {
.init = arduino_uart_init,
.send_byte = arduino_uart_send_byte,
.send_data = arduino_uart_send_data,
.receive_byte = arduino_uart_receive_byte,
.receive_data = arduino_uart_receive_data,
.is_tx_complete = arduino_uart_is_tx_complete,
.get_rx_count = arduino_uart_get_rx_count
};

// 应用层串口通信
typedef struct {
uint8_t uart_id;
uart_hal_t* hal;
uart_config_t config;
} serial_port_t;

bool serial_init(serial_port_t* port, uint8_t uart_id, uart_baudrate_t baudrate, uart_hal_t* hal) {
port->uart_id = uart_id;
port->hal = hal;
port->config.uart_id = uart_id;
port->config.baudrate = baudrate;
port->config.databits = UART_DATABITS_8;
port->config.parity = UART_PARITY_NONE;
port->config.stopbits = UART_STOPBITS_1;
port->config.flow_control = false;

return hal->init(&port->config);
}

bool serial_print(serial_port_t* port, const char* str) {
return port->hal->send_data(port->uart_id, (const uint8_t*)str, strlen(str));
}

bool serial_println(serial_port_t* port, const char* str) {
bool result = serial_print(port, str);
result &= port->hal->send_data(port->uart_id, (const uint8_t*)"\r\n", 2);
return result;
}

size_t serial_read_line(serial_port_t* port, char* buffer, size_t max_length, uint32_t timeout_ms) {
return port->hal->receive_data(port->uart_id, (uint8_t*)buffer, max_length - 1, timeout_ms);
}

void uart_hal_demo() {
printf("=== 串口通信抽象层演示 ===\n");

// STM32串口通信
printf("\nSTM32串口通信:\n");
serial_port_t stm32_serial;
serial_init(&stm32_serial, 1, UART_BAUD_115200, &stm32_uart_hal);

serial_println(&stm32_serial, "Hello from STM32!");
serial_print(&stm32_serial, "Temperature: ");
serial_println(&stm32_serial, "25.6C");

char rx_buffer[64];
size_t received = serial_read_line(&stm32_serial, rx_buffer, sizeof(rx_buffer), 1000);
if (received > 0) {
rx_buffer[received] = '\0';
printf("接收到: %s\n", rx_buffer);
}

// Arduino串口通信
printf("\nArduino串口通信:\n");
serial_port_t arduino_serial;
serial_init(&arduino_serial, 0, UART_BAUD_9600, &arduino_uart_hal);

serial_println(&arduino_serial, "Hello from Arduino!");

printf("\n");
}

int main() {
uart_hal_demo();
return 0;
}

3. 实时系统编程

3.1 任务调度器

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

// 任务状态枚举
typedef enum {
TASK_STATE_READY,
TASK_STATE_RUNNING,
TASK_STATE_BLOCKED,
TASK_STATE_SUSPENDED
} task_state_t;

// 任务优先级
typedef enum {
TASK_PRIORITY_IDLE = 0,
TASK_PRIORITY_LOW = 1,
TASK_PRIORITY_NORMAL = 2,
TASK_PRIORITY_HIGH = 3,
TASK_PRIORITY_CRITICAL = 4
} task_priority_t;

// 任务控制块
#define TASK_STACK_SIZE 512
#define MAX_TASKS 8

typedef struct task_control_block {
uint8_t task_id;
char name[16];
task_state_t state;
task_priority_t priority;
uint32_t stack_pointer;
uint8_t stack[TASK_STACK_SIZE];
uint32_t run_time_us; // 运行时间(微秒)
uint32_t period_ms; // 周期(毫秒)
uint32_t last_run_time; // 上次运行时间
void (*task_function)(void*); // 任务函数
void* task_parameter; // 任务参数
struct task_control_block* next; // 链表指针
} tcb_t;

// 调度器状态
typedef struct {
tcb_t* current_task;
tcb_t* ready_queue[5]; // 按优先级分组的就绪队列
tcb_t task_pool[MAX_TASKS];
uint8_t task_count;
uint32_t system_tick;
bool scheduler_running;
} scheduler_t;

static scheduler_t scheduler = {0};

// 模拟系统时钟
static uint32_t system_time_ms = 0;

uint32_t get_system_time_ms(void) {
return system_time_ms;
}

void advance_system_time(uint32_t ms) {
system_time_ms += ms;
}

// 任务创建
bool task_create(uint8_t task_id, const char* name,
task_priority_t priority, uint32_t period_ms,
void (*task_function)(void*), void* parameter) {

if (scheduler.task_count >= MAX_TASKS) {
printf("错误: 任务数量已达上限\n");
return false;
}

tcb_t* task = &scheduler.task_pool[scheduler.task_count];
task->task_id = task_id;
strncpy(task->name, name, sizeof(task->name) - 1);
task->name[sizeof(task->name) - 1] = '\0';
task->state = TASK_STATE_READY;
task->priority = priority;
task->stack_pointer = (uint32_t)&task->stack[TASK_STACK_SIZE - 1];
task->run_time_us = 0;
task->period_ms = period_ms;
task->last_run_time = 0;
task->task_function = task_function;
task->task_parameter = parameter;
task->next = NULL;

// 添加到就绪队列
if (scheduler.ready_queue[priority] == NULL) {
scheduler.ready_queue[priority] = task;
} else {
tcb_t* current = scheduler.ready_queue[priority];
while (current->next != NULL) {
current = current->next;
}
current->next = task;
}

scheduler.task_count++;

printf("创建任务: %s (ID=%d, 优先级=%d, 周期=%dms)\n",
name, task_id, priority, period_ms);

return true;
}

// 获取最高优先级就绪任务
tcb_t* get_highest_priority_task(void) {
for (int priority = TASK_PRIORITY_CRITICAL; priority >= TASK_PRIORITY_IDLE; priority--) {
if (scheduler.ready_queue[priority] != NULL) {
return scheduler.ready_queue[priority];
}
}
return NULL;
}

// 从就绪队列移除任务
void remove_from_ready_queue(tcb_t* task) {
tcb_t** queue = &scheduler.ready_queue[task->priority];

if (*queue == task) {
*queue = task->next;
} else {
tcb_t* current = *queue;
while (current && current->next != task) {
current = current->next;
}
if (current) {
current->next = task->next;
}
}
task->next = NULL;
}

// 添加到就绪队列
void add_to_ready_queue(tcb_t* task) {
task->state = TASK_STATE_READY;
task->next = scheduler.ready_queue[task->priority];
scheduler.ready_queue[task->priority] = task;
}

// 任务调度
void task_schedule(void) {
if (!scheduler.scheduler_running) {
return;
}

tcb_t* next_task = get_highest_priority_task();

if (next_task == NULL) {
printf("警告: 没有就绪任务\n");
return;
}

// 检查周期性任务是否到期
uint32_t current_time = get_system_time_ms();
if (next_task->period_ms > 0) {
if (current_time - next_task->last_run_time < next_task->period_ms) {
// 任务未到期,移到队列末尾
remove_from_ready_queue(next_task);
add_to_ready_queue(next_task);
return;
}
}

// 上下文切换
if (scheduler.current_task != next_task) {
tcb_t* prev_task = scheduler.current_task;

if (prev_task && prev_task->state == TASK_STATE_RUNNING) {
prev_task->state = TASK_STATE_READY;
}

scheduler.current_task = next_task;
next_task->state = TASK_STATE_RUNNING;
next_task->last_run_time = current_time;

printf("[%dms] 切换到任务: %s\n", current_time, next_task->name);

// 执行任务
if (next_task->task_function) {
uint32_t start_time = get_system_time_ms();
next_task->task_function(next_task->task_parameter);
uint32_t end_time = get_system_time_ms();
next_task->run_time_us += (end_time - start_time) * 1000;
}

// 任务执行完成,移除或重新调度
remove_from_ready_queue(next_task);
if (next_task->period_ms > 0) {
add_to_ready_queue(next_task); // 周期性任务重新加入队列
}
}
}

// 启动调度器
void scheduler_start(void) {
printf("=== 启动任务调度器 ===\n");
scheduler.scheduler_running = true;
scheduler.system_tick = 0;
}

// 系统滴答中断处理
void system_tick_handler(void) {
scheduler.system_tick++;
advance_system_time(1); // 每次滴答1ms

// 每10ms调度一次
if (scheduler.system_tick % 10 == 0) {
task_schedule();
}
}

// 示例任务函数
void led_blink_task(void* param) {
static bool led_state = false;
led_state = !led_state;
printf(" LED闪烁任务: LED %s\n", led_state ? "ON" : "OFF");
}

void sensor_read_task(void* param) {
static int temperature = 20;
temperature += (rand() % 5) - 2; // 模拟温度变化
printf(" 传感器读取任务: 温度 = %d°C\n", temperature);
}

void data_process_task(void* param) {
printf(" 数据处理任务: 处理传感器数据\n");
}

void communication_task(void* param) {
printf(" 通信任务: 发送数据到服务器\n");
}

void idle_task(void* param) {
printf(" 空闲任务: CPU休眠\n");
}

void print_task_statistics(void) {
printf("\n=== 任务统计信息 ===\n");
for (int i = 0; i < scheduler.task_count; i++) {
tcb_t* task = &scheduler.task_pool[i];
printf("任务: %-15s 运行时间: %6d us\n",
task->name, task->run_time_us);
}
printf("\n");
}

void rtos_demo() {
printf("=== 实时任务调度演示 ===\n");

// 创建任务
task_create(1, "LED_Blink", TASK_PRIORITY_LOW, 500, led_blink_task, NULL);
task_create(2, "Sensor_Read", TASK_PRIORITY_NORMAL, 100, sensor_read_task, NULL);
task_create(3, "Data_Process", TASK_PRIORITY_HIGH, 200, data_process_task, NULL);
task_create(4, "Communication", TASK_PRIORITY_NORMAL, 1000, communication_task, NULL);
task_create(5, "Idle", TASK_PRIORITY_IDLE, 0, idle_task, NULL);

// 启动调度器
scheduler_start();

// 模拟系统运行
printf("\n=== 系统运行 ===\n");
for (int i = 0; i < 50; i++) {
system_tick_handler();

// 模拟其他系统活动
if (i % 20 == 0) {
printf("[%dms] 系统检查点\n", get_system_time_ms());
}
}

print_task_statistics();
}

int main() {
rtos_demo();
return 0;
}

3.2 中断处理

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

// 中断向量表大小
#define MAX_INTERRUPTS 32

// 中断优先级
typedef enum {
IRQ_PRIORITY_LOWEST = 0,
IRQ_PRIORITY_LOW = 1,
IRQ_PRIORITY_NORMAL = 2,
IRQ_PRIORITY_HIGH = 3,
IRQ_PRIORITY_HIGHEST = 4
} irq_priority_t;

// 中断类型
typedef enum {
IRQ_TYPE_TIMER = 0,
IRQ_TYPE_UART = 1,
IRQ_TYPE_GPIO = 2,
IRQ_TYPE_ADC = 3,
IRQ_TYPE_SPI = 4,
IRQ_TYPE_I2C = 5
} irq_type_t;

// 中断处理函数类型
typedef void (*irq_handler_t)(void);

// 中断描述符
typedef struct {
irq_type_t type;
uint8_t irq_number;
irq_priority_t priority;
irq_handler_t handler;
bool enabled;
uint32_t trigger_count;
uint32_t max_execution_time_us;
char name[16];
} irq_descriptor_t;

// 中断控制器
typedef struct {
irq_descriptor_t interrupts[MAX_INTERRUPTS];
uint8_t interrupt_count;
bool global_interrupt_enabled;
uint32_t nested_level;
uint32_t total_interrupt_time_us;
} interrupt_controller_t;

static interrupt_controller_t irq_controller = {0};

// 模拟硬件状态
static volatile bool timer_flag = false;
static volatile bool uart_rx_flag = false;
static volatile bool gpio_flag = false;
static volatile uint8_t uart_rx_data = 0;

// 中断注册
bool irq_register(irq_type_t type, uint8_t irq_number,
irq_priority_t priority, irq_handler_t handler,
const char* name) {

if (irq_controller.interrupt_count >= MAX_INTERRUPTS) {
printf("错误: 中断向量表已满\n");
return false;
}

irq_descriptor_t* irq = &irq_controller.interrupts[irq_controller.interrupt_count];
irq->type = type;
irq->irq_number = irq_number;
irq->priority = priority;
irq->handler = handler;
irq->enabled = false;
irq->trigger_count = 0;
irq->max_execution_time_us = 0;
strncpy(irq->name, name, sizeof(irq->name) - 1);
irq->name[sizeof(irq->name) - 1] = '\0';

irq_controller.interrupt_count++;

printf("注册中断: %s (类型=%d, 号码=%d, 优先级=%d)\n",
name, type, irq_number, priority);

return true;
}

// 中断使能/禁用
void irq_enable(uint8_t irq_number) {
for (int i = 0; i < irq_controller.interrupt_count; i++) {
if (irq_controller.interrupts[i].irq_number == irq_number) {
irq_controller.interrupts[i].enabled = true;
printf("使能中断: %s\n", irq_controller.interrupts[i].name);
break;
}
}
}

void irq_disable(uint8_t irq_number) {
for (int i = 0; i < irq_controller.interrupt_count; i++) {
if (irq_controller.interrupts[i].irq_number == irq_number) {
irq_controller.interrupts[i].enabled = false;
printf("禁用中断: %s\n", irq_controller.interrupts[i].name);
break;
}
}
}

// 全局中断控制
void global_irq_enable(void) {
irq_controller.global_interrupt_enabled = true;
printf("全局中断使能\n");
}

void global_irq_disable(void) {
irq_controller.global_interrupt_enabled = false;
printf("全局中断禁用\n");
}

// 中断处理函数
void timer_irq_handler(void) {
printf(" [中断] 定时器中断处理\n");
timer_flag = false; // 清除标志

// 模拟定时器中断处理
static uint32_t timer_counter = 0;
timer_counter++;

if (timer_counter % 10 == 0) {
printf(" [定时器] 10次中断,执行周期性任务\n");
}
}

void uart_irq_handler(void) {
printf(" [中断] UART接收中断处理\n");

// 读取接收到的数据
uint8_t data = uart_rx_data;
printf(" [UART] 接收数据: 0x%02X ('%c')\n",
data, (data >= 32 && data < 127) ? data : '.');

uart_rx_flag = false; // 清除标志
}

void gpio_irq_handler(void) {
printf(" [中断] GPIO外部中断处理\n");
printf(" [GPIO] 检测到按键按下\n");

gpio_flag = false; // 清除标志
}

void adc_irq_handler(void) {
printf(" [中断] ADC转换完成中断\n");

// 模拟ADC读取
uint16_t adc_value = 2048 + (rand() % 100) - 50;
float voltage = (adc_value * 3.3f) / 4096.0f;
printf(" [ADC] 转换结果: %d (%.2fV)\n", adc_value, voltage);
}

// 中断触发模拟
void trigger_interrupt(irq_type_t type, uint8_t irq_number) {
if (!irq_controller.global_interrupt_enabled) {
return;
}

// 查找中断描述符
irq_descriptor_t* irq = NULL;
for (int i = 0; i < irq_controller.interrupt_count; i++) {
if (irq_controller.interrupts[i].type == type &&
irq_controller.interrupts[i].irq_number == irq_number) {
irq = &irq_controller.interrupts[i];
break;
}
}

if (!irq || !irq->enabled) {
return;
}

printf("[中断触发] %s (优先级=%d)\n", irq->name, irq->priority);

// 模拟中断嵌套检查
irq_controller.nested_level++;
if (irq_controller.nested_level > 3) {
printf("警告: 中断嵌套层数过深 (%d)\n", irq_controller.nested_level);
}

// 执行中断处理函数
uint32_t start_time = get_system_time_ms() * 1000; // 转换为微秒
if (irq->handler) {
irq->handler();
}
uint32_t end_time = get_system_time_ms() * 1000;

uint32_t execution_time = end_time - start_time;
if (execution_time > irq->max_execution_time_us) {
irq->max_execution_time_us = execution_time;
}

irq->trigger_count++;
irq_controller.total_interrupt_time_us += execution_time;
irq_controller.nested_level--;

printf("[中断完成] %s (执行时间: %d us)\n", irq->name, execution_time);
}

// 中断统计
void print_interrupt_statistics(void) {
printf("\n=== 中断统计信息 ===\n");
printf("总中断时间: %d us\n", irq_controller.total_interrupt_time_us);
printf("最大嵌套层数: %d\n", irq_controller.nested_level);

printf("\n中断详细统计:\n");
for (int i = 0; i < irq_controller.interrupt_count; i++) {
irq_descriptor_t* irq = &irq_controller.interrupts[i];
printf(" %-15s: 触发%3d次, 最大执行时间%4d us, %s\n",
irq->name, irq->trigger_count, irq->max_execution_time_us,
irq->enabled ? "使能" : "禁用");
}
printf("\n");
}

// 临界区保护宏
#define ENTER_CRITICAL_SECTION() \
do { \
global_irq_disable(); \
printf("[临界区] 进入\n"); \
} while(0)

#define EXIT_CRITICAL_SECTION() \
do { \
printf("[临界区] 退出\n"); \
global_irq_enable(); \
} while(0)

// 临界区保护示例
void critical_section_demo(void) {
printf("\n=== 临界区保护演示 ===\n");

static volatile int shared_counter = 0;

printf("修改共享变量(无保护):\n");
shared_counter++;
printf("共享计数器: %d\n", shared_counter);

printf("\n修改共享变量(临界区保护):\n");
ENTER_CRITICAL_SECTION();
shared_counter++;
printf("共享计数器: %d\n", shared_counter);
EXIT_CRITICAL_SECTION();
}

void interrupt_demo() {
printf("=== 中断处理演示 ===\n");

// 注册中断处理函数
irq_register(IRQ_TYPE_TIMER, 0, IRQ_PRIORITY_HIGH, timer_irq_handler, "Timer0");
irq_register(IRQ_TYPE_UART, 1, IRQ_PRIORITY_NORMAL, uart_irq_handler, "UART1_RX");
irq_register(IRQ_TYPE_GPIO, 2, IRQ_PRIORITY_HIGH, gpio_irq_handler, "GPIO_EXTI");
irq_register(IRQ_TYPE_ADC, 3, IRQ_PRIORITY_LOW, adc_irq_handler, "ADC_Complete");

// 使能中断
global_irq_enable();
irq_enable(0);
irq_enable(1);
irq_enable(2);
irq_enable(3);

printf("\n=== 模拟中断触发 ===\n");

// 模拟各种中断触发
trigger_interrupt(IRQ_TYPE_TIMER, 0);
advance_system_time(1);

uart_rx_data = 'A';
trigger_interrupt(IRQ_TYPE_UART, 1);
advance_system_time(1);

trigger_interrupt(IRQ_TYPE_GPIO, 2);
advance_system_time(1);

trigger_interrupt(IRQ_TYPE_ADC, 3);
advance_system_time(1);

// 模拟连续定时器中断
for (int i = 0; i < 5; i++) {
trigger_interrupt(IRQ_TYPE_TIMER, 0);
advance_system_time(1);
}

// 临界区演示
critical_section_demo();

// 打印统计信息
print_interrupt_statistics();
}

int main() {
interrupt_demo();
return 0;
}

4. 内存管理

4.1 静态内存池

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

// 内存块大小定义
#define SMALL_BLOCK_SIZE 32
#define MEDIUM_BLOCK_SIZE 128
#define LARGE_BLOCK_SIZE 512

// 内存池配置
#define SMALL_POOL_COUNT 16
#define MEDIUM_POOL_COUNT 8
#define LARGE_POOL_COUNT 4

// 内存块状态
typedef enum {
BLOCK_FREE,
BLOCK_ALLOCATED
} block_state_t;

// 内存块头部
typedef struct {
block_state_t state;
uint16_t size;
uint32_t magic; // 魔数,用于检测内存损坏
uint32_t alloc_time; // 分配时间
} block_header_t;

// 内存池描述符
typedef struct {
uint8_t* pool_start;
uint16_t block_size;
uint16_t block_count;
uint16_t free_count;
uint32_t* free_bitmap; // 空闲块位图
const char* name;
} memory_pool_t;

// 内存管理器
typedef struct {
memory_pool_t pools[3];
uint8_t pool_count;
uint32_t total_allocated;
uint32_t peak_allocated;
uint32_t allocation_count;
uint32_t free_count;
} memory_manager_t;

// 魔数定义
#define MEMORY_MAGIC 0xDEADBEEF

// 静态内存池存储
static uint8_t small_pool_memory[SMALL_POOL_COUNT * (SMALL_BLOCK_SIZE + sizeof(block_header_t))];
static uint8_t medium_pool_memory[MEDIUM_POOL_COUNT * (MEDIUM_BLOCK_SIZE + sizeof(block_header_t))];
static uint8_t large_pool_memory[LARGE_POOL_COUNT * (LARGE_BLOCK_SIZE + sizeof(block_header_t))];

// 位图存储
static uint32_t small_pool_bitmap[(SMALL_POOL_COUNT + 31) / 32];
static uint32_t medium_pool_bitmap[(MEDIUM_POOL_COUNT + 31) / 32];
static uint32_t large_pool_bitmap[(LARGE_POOL_COUNT + 31) / 32];

static memory_manager_t mem_manager = {0};

// 位图操作函数
void set_bit(uint32_t* bitmap, uint16_t bit) {
bitmap[bit / 32] |= (1U << (bit % 32));
}

void clear_bit(uint32_t* bitmap, uint16_t bit) {
bitmap[bit / 32] &= ~(1U << (bit % 32));
}

bool is_bit_set(uint32_t* bitmap, uint16_t bit) {
return (bitmap[bit / 32] & (1U << (bit % 32))) != 0;
}

// 查找空闲块
int find_free_block(uint32_t* bitmap, uint16_t count) {
for (uint16_t i = 0; i < count; i++) {
if (!is_bit_set(bitmap, i)) {
return i;
}
}
return -1;
}

// 内存池初始化
void memory_pool_init(void) {
printf("=== 初始化内存池 ===\n");

// 初始化小块内存池
mem_manager.pools[0].pool_start = small_pool_memory;
mem_manager.pools[0].block_size = SMALL_BLOCK_SIZE;
mem_manager.pools[0].block_count = SMALL_POOL_COUNT;
mem_manager.pools[0].free_count = SMALL_POOL_COUNT;
mem_manager.pools[0].free_bitmap = small_pool_bitmap;
mem_manager.pools[0].name = "Small";

// 初始化中块内存池
mem_manager.pools[1].pool_start = medium_pool_memory;
mem_manager.pools[1].block_size = MEDIUM_BLOCK_SIZE;
mem_manager.pools[1].block_count = MEDIUM_POOL_COUNT;
mem_manager.pools[1].free_count = MEDIUM_POOL_COUNT;
mem_manager.pools[1].free_bitmap = medium_pool_bitmap;
mem_manager.pools[1].name = "Medium";

// 初始化大块内存池
mem_manager.pools[2].pool_start = large_pool_memory;
mem_manager.pools[2].block_size = LARGE_BLOCK_SIZE;
mem_manager.pools[2].block_count = LARGE_POOL_COUNT;
mem_manager.pools[2].free_count = LARGE_POOL_COUNT;
mem_manager.pools[2].free_bitmap = large_pool_bitmap;
mem_manager.pools[2].name = "Large";

mem_manager.pool_count = 3;

// 清空所有位图
memset(small_pool_bitmap, 0, sizeof(small_pool_bitmap));
memset(medium_pool_bitmap, 0, sizeof(medium_pool_bitmap));
memset(large_pool_bitmap, 0, sizeof(large_pool_bitmap));

printf("内存池初始化完成:\n");
printf(" 小块池: %d块 x %d字节\n", SMALL_POOL_COUNT, SMALL_BLOCK_SIZE);
printf(" 中块池: %d块 x %d字节\n", MEDIUM_POOL_COUNT, MEDIUM_BLOCK_SIZE);
printf(" 大块池: %d块 x %d字节\n", LARGE_POOL_COUNT, LARGE_BLOCK_SIZE);
printf("\n");
}

// 选择合适的内存池
memory_pool_t* select_pool(size_t size) {
if (size <= SMALL_BLOCK_SIZE) {
return &mem_manager.pools[0];
} else if (size <= MEDIUM_BLOCK_SIZE) {
return &mem_manager.pools[1];
} else if (size <= LARGE_BLOCK_SIZE) {
return &mem_manager.pools[2];
}
return NULL;
}

// 内存分配
void* pool_malloc(size_t size) {
if (size == 0) {
return NULL;
}

memory_pool_t* pool = select_pool(size);
if (!pool) {
printf("错误: 请求的内存大小 %zu 超过最大块大小\n", size);
return NULL;
}

if (pool->free_count == 0) {
printf("错误: %s内存池已满\n", pool->name);
return NULL;
}

int block_index = find_free_block(pool->free_bitmap, pool->block_count);
if (block_index < 0) {
printf("错误: 无法找到空闲块\n");
return NULL;
}

// 标记块为已分配
set_bit(pool->free_bitmap, block_index);
pool->free_count--;

// 计算块地址
size_t block_total_size = pool->block_size + sizeof(block_header_t);
uint8_t* block_addr = pool->pool_start + (block_index * block_total_size);

// 设置块头部
block_header_t* header = (block_header_t*)block_addr;
header->state = BLOCK_ALLOCATED;
header->size = size;
header->magic = MEMORY_MAGIC;
header->alloc_time = get_system_time_ms();

// 更新统计信息
mem_manager.total_allocated += size;
mem_manager.allocation_count++;
if (mem_manager.total_allocated > mem_manager.peak_allocated) {
mem_manager.peak_allocated = mem_manager.total_allocated;
}

void* user_ptr = block_addr + sizeof(block_header_t);

printf("分配内存: %zu字节 从%s池 (块%d, 地址%p)\n",
size, pool->name, block_index, user_ptr);

return user_ptr;
}

// 内存释放
void pool_free(void* ptr) {
if (!ptr) {
return;
}

// 获取块头部
block_header_t* header = (block_header_t*)((uint8_t*)ptr - sizeof(block_header_t));

// 检查魔数
if (header->magic != MEMORY_MAGIC) {
printf("错误: 内存损坏或无效指针\n");
return;
}

if (header->state != BLOCK_ALLOCATED) {
printf("错误: 重复释放内存\n");
return;
}

// 查找对应的内存池
memory_pool_t* pool = NULL;
int block_index = -1;

for (int i = 0; i < mem_manager.pool_count; i++) {
uint8_t* pool_start = mem_manager.pools[i].pool_start;
size_t block_total_size = mem_manager.pools[i].block_size + sizeof(block_header_t);
uint8_t* pool_end = pool_start + (mem_manager.pools[i].block_count * block_total_size);

if ((uint8_t*)header >= pool_start && (uint8_t*)header < pool_end) {
pool = &mem_manager.pools[i];
block_index = ((uint8_t*)header - pool_start) / block_total_size;
break;
}
}

if (!pool || block_index < 0) {
printf("错误: 无法确定内存池\n");
return;
}

// 标记块为空闲
clear_bit(pool->free_bitmap, block_index);
pool->free_count++;

// 清除块头部
header->state = BLOCK_FREE;
header->magic = 0;

// 更新统计信息
mem_manager.total_allocated -= header->size;
mem_manager.free_count++;

printf("释放内存: %d字节 从%s池 (块%d)\n",
header->size, pool->name, block_index);
}

// 内存池状态
void print_memory_status(void) {
printf("\n=== 内存池状态 ===\n");

for (int i = 0; i < mem_manager.pool_count; i++) {
memory_pool_t* pool = &mem_manager.pools[i];
uint16_t used_blocks = pool->block_count - pool->free_count;
float usage_percent = (float)used_blocks / pool->block_count * 100.0f;

printf("%s池: %d/%d块使用 (%.1f%%)\n",
pool->name, used_blocks, pool->block_count, usage_percent);
}

printf("\n总体统计:\n");
printf(" 当前分配: %d 字节\n", mem_manager.total_allocated);
printf(" 峰值分配: %d 字节\n", mem_manager.peak_allocated);
printf(" 分配次数: %d\n", mem_manager.allocation_count);
printf(" 释放次数: %d\n", mem_manager.free_count);
printf("\n");
}

void memory_pool_demo() {
printf("=== 静态内存池演示 ===\n");

memory_pool_init();

// 分配不同大小的内存
void* ptr1 = pool_malloc(20); // 小块
void* ptr2 = pool_malloc(100); // 中块
void* ptr3 = pool_malloc(300); // 大块
void* ptr4 = pool_malloc(16); // 小块

print_memory_status();

// 释放部分内存
pool_free(ptr2);
pool_free(ptr4);

print_memory_status();

// 重新分配
void* ptr5 = pool_malloc(80); // 中块

print_memory_status();

// 清理
pool_free(ptr1);
pool_free(ptr3);
pool_free(ptr5);

print_memory_status();
}

int main() {
memory_pool_demo();
return 0;
}

5. 低功耗设计

5.1 电源管理

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

// 电源模式枚举
typedef enum {
POWER_MODE_RUN, // 运行模式
POWER_MODE_SLEEP, // 睡眠模式
POWER_MODE_STOP, // 停止模式
POWER_MODE_STANDBY // 待机模式
} power_mode_t;

// 唤醒源枚举
typedef enum {
WAKEUP_SOURCE_TIMER,
WAKEUP_SOURCE_GPIO,
WAKEUP_SOURCE_UART,
WAKEUP_SOURCE_RTC
} wakeup_source_t;

// 电源管理配置
typedef struct {
power_mode_t current_mode;
uint32_t sleep_duration_ms;
wakeup_source_t wakeup_sources[4];
uint8_t wakeup_source_count;
bool low_power_enabled;
uint32_t total_sleep_time_ms;
uint32_t wakeup_count;
} power_manager_t;

static power_manager_t power_mgr = {
.current_mode = POWER_MODE_RUN,
.low_power_enabled = true
};

// 模拟功耗数据 (mA)
static const float power_consumption[] = {
[POWER_MODE_RUN] = 50.0f,
[POWER_MODE_SLEEP] = 5.0f,
[POWER_MODE_STOP] = 0.5f,
[POWER_MODE_STANDBY] = 0.05f
};

// 进入低功耗模式
void enter_low_power_mode(power_mode_t mode, uint32_t duration_ms) {
if (!power_mgr.low_power_enabled) {
printf("低功耗模式已禁用\n");
return;
}

const char* mode_names[] = {
"运行", "睡眠", "停止", "待机"
};

printf("进入%s模式 (持续%dms)\n", mode_names[mode], duration_ms);

power_mgr.current_mode = mode;
power_mgr.sleep_duration_ms = duration_ms;

// 模拟低功耗状态
printf(" 当前功耗: %.2f mA\n", power_consumption[mode]);

// 禁用不必要的外设
switch (mode) {
case POWER_MODE_SLEEP:
printf(" CPU停止,外设继续运行\n");
break;
case POWER_MODE_STOP:
printf(" CPU和大部分外设停止\n");
break;
case POWER_MODE_STANDBY:
printf(" 仅保持最小功能\n");
break;
default:
break;
}

// 模拟睡眠时间
advance_system_time(duration_ms);
power_mgr.total_sleep_time_ms += duration_ms;
}

// 从低功耗模式唤醒
void wakeup_from_low_power(wakeup_source_t source) {
const char* source_names[] = {
"定时器", "GPIO", "UART", "RTC"
};

printf("从%s唤醒\n", source_names[source]);

power_mgr.current_mode = POWER_MODE_RUN;
power_mgr.wakeup_count++;

printf(" 恢复到运行模式\n");
printf(" 当前功耗: %.2f mA\n", power_consumption[POWER_MODE_RUN]);
}

// 配置唤醒源
void configure_wakeup_sources(void) {
printf("配置唤醒源:\n");

power_mgr.wakeup_sources[0] = WAKEUP_SOURCE_TIMER;
power_mgr.wakeup_sources[1] = WAKEUP_SOURCE_GPIO;
power_mgr.wakeup_sources[2] = WAKEUP_SOURCE_RTC;
power_mgr.wakeup_source_count = 3;

printf(" 定时器唤醒: 启用\n");
printf(" GPIO唤醒: 启用\n");
printf(" RTC唤醒: 启用\n");
}

// 动态电压频率调节
void dvfs_adjust(uint8_t cpu_load_percent) {
printf("\n动态电压频率调节 (CPU负载: %d%%):\n", cpu_load_percent);

if (cpu_load_percent < 20) {
printf(" 降低CPU频率到48MHz\n");
printf(" 降低电压到1.2V\n");
printf(" 功耗降低30%%\n");
} else if (cpu_load_percent < 50) {
printf(" CPU频率保持72MHz\n");
printf(" 电压保持1.8V\n");
} else {
printf(" 提升CPU频率到168MHz\n");
printf(" 提升电压到3.3V\n");
printf(" 功耗增加50%%\n");
}
}

// 外设电源控制
void peripheral_power_control(bool enable_wifi, bool enable_bluetooth, bool enable_sensors) {
printf("\n外设电源控制:\n");

float total_power = power_consumption[power_mgr.current_mode];

if (enable_wifi) {
printf(" WiFi: 启用 (+20mA)\n");
total_power += 20.0f;
} else {
printf(" WiFi: 禁用\n");
}

if (enable_bluetooth) {
printf(" 蓝牙: 启用 (+10mA)\n");
total_power += 10.0f;
} else {
printf(" 蓝牙: 禁用\n");
}

if (enable_sensors) {
printf(" 传感器: 启用 (+5mA)\n");
total_power += 5.0f;
} else {
printf(" 传感器: 禁用\n");
}

printf(" 总功耗: %.1f mA\n", total_power);
}

// 电池电量监控
void battery_monitor(void) {
// 模拟电池电压读取
static float battery_voltage = 3.7f;
battery_voltage -= 0.01f; // 模拟电池消耗

float battery_percent = ((battery_voltage - 3.0f) / (4.2f - 3.0f)) * 100.0f;
if (battery_percent < 0) battery_percent = 0;
if (battery_percent > 100) battery_percent = 100;

printf("\n电池监控:\n");
printf(" 电池电压: %.2fV\n", battery_voltage);
printf(" 电池电量: %.1f%%\n", battery_percent);

if (battery_percent < 20) {
printf(" 警告: 电池电量低,进入省电模式\n");
power_mgr.low_power_enabled = true;
} else if (battery_percent < 10) {
printf(" 严重: 电池电量极低,准备关机\n");
enter_low_power_mode(POWER_MODE_STANDBY, 0);
}
}

// 功耗统计
void print_power_statistics(void) {
printf("\n=== 功耗统计 ===\n");
printf("当前模式: %s\n",
power_mgr.current_mode == POWER_MODE_RUN ? "运行" :
power_mgr.current_mode == POWER_MODE_SLEEP ? "睡眠" :
power_mgr.current_mode == POWER_MODE_STOP ? "停止" : "待机");
printf("总睡眠时间: %d ms\n", power_mgr.total_sleep_time_ms);
printf("唤醒次数: %d\n", power_mgr.wakeup_count);

uint32_t total_time = get_system_time_ms();
uint32_t active_time = total_time - power_mgr.total_sleep_time_ms;
float sleep_ratio = (float)power_mgr.total_sleep_time_ms / total_time * 100.0f;

printf("活跃时间: %d ms (%.1f%%)\n", active_time, 100.0f - sleep_ratio);
printf("睡眠比例: %.1f%%\n", sleep_ratio);

// 估算平均功耗
float avg_power = (active_time * power_consumption[POWER_MODE_RUN] +
power_mgr.total_sleep_time_ms * power_consumption[POWER_MODE_SLEEP]) / total_time;
printf("平均功耗: %.2f mA\n", avg_power);
printf("\n");
}

void power_management_demo() {
printf("=== 电源管理演示 ===\n");

configure_wakeup_sources();

// 正常运行
printf("\n正常运行阶段:\n");
dvfs_adjust(30);
peripheral_power_control(true, false, true);
advance_system_time(1000);

// 进入睡眠模式
printf("\n进入低功耗阶段:\n");
peripheral_power_control(false, false, false);
enter_low_power_mode(POWER_MODE_SLEEP, 5000);

// 定时器唤醒
wakeup_from_low_power(WAKEUP_SOURCE_TIMER);

// 短暂活动
peripheral_power_control(false, false, true);
advance_system_time(500);

// 再次睡眠
enter_low_power_mode(POWER_MODE_STOP, 10000);

// GPIO唤醒
wakeup_from_low_power(WAKEUP_SOURCE_GPIO);

// 高负载运行
dvfs_adjust(80);
peripheral_power_control(true, true, true);
advance_system_time(2000);

// 电池监控
battery_monitor();

print_power_statistics();
}

int main() {
power_management_demo();
return 0;
}

总结

C语言在嵌入式系统开发中具有不可替代的地位,其优势包括:

技术优势:

  1. 高效性:直接编译为机器码,执行效率高
  2. 可控性:精确控制内存使用和硬件资源
  3. 实时性:支持确定性的实时响应
  4. 可移植性:跨平台兼容性好
  5. 资源占用小:适合资源受限的环境

应用领域:

  1. 单片机开发:Arduino、STM32、PIC等
  2. 实时操作系统:FreeRTOS、RT-Thread等
  3. 物联网设备:传感器节点、智能家居
  4. 工业控制:PLC、自动化设备
  5. 汽车电子:ECU、车载系统

关键技术:

  1. 硬件抽象层:提高代码可移植性
  2. 实时调度:保证系统响应性
  3. 中断处理:高效的事件响应机制
  4. 内存管理:静态分配和内存池技术
  5. 低功耗设计:延长设备续航时间

最佳实践:

  1. 合理设计软件架构
  2. 使用标准化的HAL层
  3. 实施严格的代码审查
  4. 进行充分的测试验证
  5. 优化功耗和性能

掌握这些技术和实践,你将能够开发出高质量、高可靠性的嵌入式系统。

//

版权所有,如有侵权请联系我