没有收发使能的485通讯的S485 隔离收发模块,在STM32下的通信代码实现,发一份
时间: 2024-03-09 18:44:35 浏览: 13
以下是一个基于STM32的S485隔离收发模块通信示例代码:
```c
#include "stm32f10x.h"
#define S485_GPIO_PORT GPIOA
#define S485_GPIO_TX_PIN GPIO_Pin_9
#define S485_GPIO_RX_PIN GPIO_Pin_10
#define S485_USART USART1
void S485_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
// 使能GPIOA和USART1的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
// 配置GPIOA的Pin9(TX)和Pin10(RX)为推挽输出和浮空输入
GPIO_InitStructure.GPIO_Pin = S485_GPIO_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(S485_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = S485_GPIO_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(S485_GPIO_PORT, &GPIO_InitStructure);
// 配置USART1的参数:波特率、数据位、停止位、校验位等
USART_InitStructure.USART_BaudRate = 9600;
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(S485_USART, &USART_InitStructure);
// 使能USART1
USART_Cmd(S485_USART, ENABLE);
}
// 发送一个字节
void S485_SendByte(uint8_t byte)
{
USART_SendData(S485_USART, byte);
while (USART_GetFlagStatus(S485_USART, USART_FLAG_TXE) == RESET);
}
// 发送一串数据
void S485_SendData(uint8_t *buf, uint16_t len)
{
uint16_t i;
for (i = 0; i < len; i++)
{
S485_SendByte(buf[i]);
}
}
// 接收一个字节
uint8_t S485_ReceiveByte(void)
{
while (USART_GetFlagStatus(S485_USART, USART_FLAG_RXNE) == RESET);
return USART_ReceiveData(S485_USART);
}
// 接收一串数据
void S485_ReceiveData(uint8_t *buf, uint16_t len)
{
uint16_t i;
for (i = 0; i < len; i++)
{
buf[i] = S485_ReceiveByte();
}
}
```
使用时,先调用 `S485_Init()` 初始化 S485 隔离收发模块,然后就可以使用 `S485_SendData()` 和 `S485_ReceiveData()` 函数发送和接收数据了。注意在发送数据之前需要先设置 RS485 芯片为发送模式,在接收数据之前需要先设置 RS485 芯片为接收模式。具体实现可以参考 RS485 芯片的数据手册。