本文由RT-Thread论坛用户123原创发布,原文:https://club.rt-thread.org/ask/article/2904.html
应用层的串口问题
应用层使用串口时,需要先指定以何种方式(轮询、中断或者DMA)去打开串口,然后再进行串口的操作。这部分相关的内容在第一章已经说过,这里主要用来总结串口使用时遇到的一些问题。
串口注册时候的默认规则慢慢道来:
串口注册的默认规则
我们都知道,串口设备需要先注册,才能通过rt_device_open
API 去访问,那么串口注册时候的默认规则是什么呢?看串口驱动的注册代码如下所示:
int rt_hw_usart_init(void)
{
rt_size_t obj_num = sizeof(uart_obj) / sizeof(struct stm32_uart);
struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
rt_err_t result = 0;
stm32_uart_get_dma_config(); /* (1)*/
for (int i = 0; i < obj_num; i++)
{
/* init UART object */
uart_obj[i].config = &uart_config[i];
uart_obj[i].serial.ops = &stm32_uart_ops;
uart_obj[i].serial.config = config; /* (2) */
/* register UART device */
result = rt_hw_serial_register(&uart_obj[i].serial, uart_obj[i].config->name,
RT_DEVICE_FLAG_RDWR
| RT_DEVICE_FLAG_INT_RX
| RT_DEVICE_FLAG_INT_TX
| uart_obj[i].uart_dma_flag
, NULL); /* (3) */
RT_ASSERT(result == RT_EOK);
}
return result;
}
第(1)点:获取串口对应的dma配置,当配置串口支持dma发送或者dma接收时,在这个函数里面将会记录串口的模式配置,在后边初始化串口设备的时候,再对串口进行DMA配置。
第(2)点:配置默认的参数信息,例如波特率,停止位,奇偶校验等,这里选择的是统一配置默认的参数RT_SERIAL_CONFIG_DEFAULT
,该参数在serial.h
文件中定义,默认配置如下,在这里,其中有一个参数RT_SERIAL_RB_BUFSZ
,这个参数的意思是设置串口的接收缓冲区大小,它的默认值是64字节,需要注意的是,串口参数里面没有发送缓冲区的设置。
/* Default config for serial_configure structure */
#define RT_SERIAL_CONFIG_DEFAULT \
{ \
BAUD_RATE_115200, /* 115200 bits/s */ \
DATA_BITS_