在对接项目时,发现对方的串口协议是:数据位8、停止位1、无校验,但是有一个附加位,附加位规则如下:发送的第一个字节附加位是1,剩余字节附加位是0。
but,RT-Thread的串口发送目前似乎没有那么灵活,因此需要手改一些代码,实际操作如下:
1. RTT串口初始化设置串口数据位为9,给附加位留出空间
/* 设置串口参数 */
struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
config.baud_rate = baud_rate;
config.data_bits = DATA_BITS_9;
config.stop_bits = STOP_BITS_1;
config.parity = PARITY_NONE;//PARITY_NONE
2. 增加“第一个字节附加位是1,其余字节附加位0”的判断逻辑
文件: 工程 / rt-thread / components / drivers / serial / serial.c
由于我使用的协议中,发送的固定长度就是4,所以这里简单判断了
rt_inline int _serial_poll_tx(struct rt_serial_device *serial, const rt_uint8_t *data, int length)
{
int size;
RT_ASSERT(serial != RT_NULL);
size = length;
while (length)
{
/*
* to be polite with serial console add a line feed
* to the carriage return character
*/
if (*data == '\n' && (serial->parent.open_flag & RT_DEVICE_FLAG_STREAM))
{
serial->ops->putc(serial, '\r', 0);
}
if(length == 4){
serial->ops->putc(serial, *data, 1);
}
else {
serial->ops->putc(serial, *data, 0);
}
++ data;
-- length;
}
return size - length;
}
3. 操作DR寄存器
文件:工程 / drivers / drv_usart.c
static int stm32_putc(struct rt_serial_device *serial, char c,uint8_t writeFlg)
{
struct stm32_uart *uart;
RT_ASSERT(serial != RT_NULL);
uart = rt_container_of(serial, struct stm32_uart, serial);
UART_INSTANCE_CLEAR_FUNCTION(&(uart->handle), UART_FLAG_TC);
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32F0) \
|| defined(SOC_SERIES_STM32L0) || defined(SOC_SERIES_STM32G0) || defined(SOC_SERIES_STM32H7) \
|| defined(SOC_SERIES_STM32G4)
uart->handle.Instance->TDR = c;
#else
if(writeFlg){
uart->handle.Instance->DR = c | ((uint16_t)0x0100);
}
else {
uart->handle.Instance->DR = c & ((uint16_t)0x01ff);
}
#endif
while (__HAL_UART_GET_FLAG(&(uart->handle), UART_FLAG_TC) == RESET);
return 1;
}
4. 由于增加了参数,需要在函数声明、结构体等处一并修改,这部分可以自行查找