嵌入式stm32f103 modbus RS232 校验码
时间: 2023-09-14 12:05:47 浏览: 61
Modbus协议规定了四种校验方式:无校验、奇校验、偶校验、和校验。在RS232通信中,常用的是无校验和奇偶校验。在嵌入式stm32f103中,可以通过串口配置寄存器(USART_CR1)来设置校验方式。具体代码如下:
无校验:
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //8位数据位
USART_InitStructure.USART_StopBits = USART_StopBits_1; //1位停止位
USART_InitStructure.USART_Parity = USART_Parity_No; //无校验
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //无硬件流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //接收和发送模式
USART_Init(USART1, &USART_InitStructure); //初始化USART1
奇校验:
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //8位数据位
USART_InitStructure.USART_StopBits = USART_StopBits_1; //1位停止位
USART_InitStructure.USART_Parity = USART_Parity_Odd; //奇校验
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //无硬件流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //接收和发送模式
USART_Init(USART1, &USART_InitStructure); //初始化USART1
偶校验:
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //8位数据位
USART_InitStructure.USART_StopBits = USART_StopBits_1; //1位停止位
USART_InitStructure.USART_Parity = USART_Parity_Even; //偶校验
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //无硬件流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //接收和发送模式
USART_Init(USART1, &USART_InitStructure); //初始化USART1
和校验:
和校验在RS232通信中较少使用,这里不做演示。