在移植Modbus到STM32F103(2):移植FreeModbus到usart3并运行示例代码里,为了方便,没有移植数据位和校验位。这两个其实是很容易移植的。
先说数据位,官方宣称STM32F103支持8位和9位数据位,但因为其把校验位也算为数据位,所以其实能支持的是带校验位的7位、8位数据位和不带校验位的8位、9位数据位。所以只要在串口初始化中做如下判断即可:
if ( ( ucDataBits == 7 ) && ( eParity != MB_PAR_NONE ) )
{
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
is_7databits = 1;
}
else if ( ( ucDataBits == 8 ) && ( eParity == MB_PAR_NONE ) )
{
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
is_7databits = 0;
}
else if ( ( ucDataBits == 8 ) && ( eParity != MB_PAR_NONE ) )
{
USART_InitStructure.USART_WordLength = USART_WordLength_9b;
is_7databits = 0;
}
这里多了一个静态全局变量is_7databits,因为当STM32F103的串口工作在带校验位的7位数据位时,DR寄存器的最高位依然会被库函数读出,这样可能会造成数据错误。所以要把读取串口的代码也修改一下:
static is_7databits = 0;
BOOL
xMBPortSerialGetByte( CHAR * pucByte )
{
/* Return the byte in the UARTs receive buffer. This function is called
* by the protocol stack after pxMBFrameCBByteReceived( ) has been called.
*/
char temp;
temp = USART_ReceiveData(USART3);
*pucByte = is_7databits ? ( temp & 0x7F ) : temp ;
return TRUE;
}
校验位更简单,只要用一个带参数的宏即可:
/* ----------------------- Modbus parity to stm32 parity --------------------*/
#define usartParity(eParity) ( ( eParity == MB_PAR_NONE ) ? USART_Parity_No : ( ( eParity == MB_PAR_EVEN ) ? USART_Parity_Even : USART_Parity_Odd ) )
修改demo.c、mbascii.c和mbrtu.c,然后用Modbus Poll验证一下,应该没问题了。
来源:oschina
链接:https://my.oschina.net/u/4076592/blog/3017207