对modbus中的包含下的mbconfig.h进行编辑,把Ascii码配置为0,我们只用用RTU
1.可以新建一个STM32工程,我这里是用的是例程串口232收发的例程,用的是串口2
2.主要先将freemodbus 1.5源码中的modbus文件夹和演示文件夹里的BARE文件复制到工程,然后添加文件到工程
3.配置串口使能函数vMBPortSerialEnable(BOOL xRxEnable,BOOL xTxEnable)
void
vMBPortSerialEnable( BOOL xRxEnable, BOOL xTxEnable )
{
/* If xRXEnable enable serial receive interrupts. If xTxENable enable
* transmitter empty interrupts.
*/
/* If xRXEnable enable serial receive interrupts. If xTxENable enable
* transmitter empty interrupts.
*/
if(TRUE==xRxEnable)
{
USART_ITConfig(RS232_USART, USART_IT_RXNE, ENABLE);
}
else
{
USART_ITConfig(RS232_USART, USART_IT_RXNE, DISABLE);
}
if(TRUE==xTxEnable)
{
USART_ITConfig(RS232_USART, USART_IT_TXE, ENABLE);
}
else
{
USART_ITConfig(RS232_USART, USART_IT_TXE, DISABLE);
}
}
串口初始化函数xMBPortSerialInit(UCHAR ucPORT,ULONG ulBaudRate,UCHAR ucDataBits,eMBParity eParity)
可以将232串口初始化的例程复制到这个函数
BOOL
xMBPortSerialInit( UCHAR ucPORT, ULONG ulBaudRate, UCHAR ucDataBits, eMBParity eParity )
{
(void)ucPORT; //不修改串口
(void)ucDataBits; //不修改数据长度
(void)eParity; //不修改格式
//
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_AHB1PeriphClockCmd( RS232_USART_RX_GPIO_CLK|RS232_USART_TX_GPIO_CLK, ENABLE);
/*使用UART时钟*/
RCC_APB1PeriphClockCmd(RS232_USART_CLK, ENABLE);
/*连接PXx到USARTx_Tx*/
GPIO_PinAFConfig(RS232_USART_RX_GPIO_PORT,RS232_USART_RX_SOURCE, RS232_USART_RX_AF);
/*连接PXx到USARTx_Rx*/
GPIO_PinAFConfig(RS232_USART_TX_GPIO_PORT,RS232_USART_TX_SOURCE,RS232_USART_TX_AF);
/*配置Tx引脚为复用功能*/
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Pin = RS232_USART_TX_PIN ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(RS232_USART_TX_GPIO_PORT, &GPIO_InitStructure);
/*配置Rx引脚为复用功能*/
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Pin = RS232_USART_RX_PIN;
GPIO_Init(RS232_USART_RX_GPIO_PORT, &GPIO_InitStructure);
/* 配置串口RS232_USART模式*/
USART_InitStructure.USART_BaudRate = RS232_USART_BAUDRATE;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_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(RS232_USART, &USART_InitStructure);
USART_ITConfig(RS232_USART, USART_IT_RXNE, ENABLE);
USART_Cmd(RS232_USART, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
/* Configure one bit for preemption priority */
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
/*中断初始化 */
//设置NVIC优先级分组为Group2:0-3抢占优先级,0-3的响应优先级
NVIC_InitStructure.NVIC_IRQChannel = RS232_USART_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
return TRUE;
}
注意:
1- 我这里用的例程串口的.H文件的波特率RS2