USART — 接收超时
固件库: GD32F30x_Firmware_Library V3.0.3
芯片: GD32
源文件: GD32F30x_Firmware_Library_V3.0.3/Examples/USART/Receiver_timeout/main.c
功能简介
本示例演示 USART 串口通信。串口是最基本的通信接口,几乎每个嵌入式项目都会用到。
硬件准备
- USB 转串口模块(如 CH340、CP2102)
- 连接:开发板 TX → 模块 RX,开发板 RX → 模块 TX,共地
- 电脑端打开串口助手(如 SSCOM、XCOM),波特率与代码一致
完整代码
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
|
#include "gd32f30x.h"
#include <stdio.h>
#include "gd32f307c_eval.h"
void nvic_config(void);
/*!
\brief main function
\param[in] none
\param[out] none
\retval none
*/
int main(void)
{
uint32_t i = 0, j = 0;
nvic_config();
gd_eval_com_init(EVAL_COM0);
printf("a usart receive timeout test example!");
while(1){
if(0 == rxcount){
/* enable the USART receive interrupt */
usart_interrupt_enable(USART0, USART_INT_RBNE);
}else{
/* enable the USART receive timeout and configure the time of timeout */
usart_receiver_timeout_enable(USART0);
usart_receiver_timeout_threshold_config(USART0, 115200*3);
while(RESET == usart_flag_get(USART0, USART_FLAG_RT));
for(i=0; i<rxcount; i++){
txbuffer[i] = rxbuffer[j++];
}
/* disable the USART receive interrupt and enable the USART transmit interrupt */
usart_interrupt_disable(USART0, USART_INT_RBNE);
usart_interrupt_enable(USART0, USART_INT_TBE);
while(txcount < rxcount);
usart_flag_clear(USART0, USART_FLAG_RT);
txcount = 0;
rxcount = 0;
i = 0;
j = 0;
}
}
}
void nvic_config(void)
{
nvic_irq_enable(USART0_IRQn, 0, 1);
}
|
代码讲解
printf 输出:通过串口打印调试信息。需要先调用 uart_print_init 完成重定向。
中断优先级配置:NVIC 设置中断的抢占优先级和子优先级。数字越小优先级越高。
实验现象
- 串口助手收到开发板发送的数据
- 发送数据后开发板原样返回(回显)
注意事项
- 串口助手波特率必须与代码一致
- 检查 TX/RX 是否交叉连接
- 共地是必须的