在配置好串口的基础上完成RS485的配置
一、使能RS485的发送和接收模式引脚
__HAL_RCC_GPIOG_CLK_ENABLE();//高电平是发送模式,低电平是接收模式,默认是接收模式HAL_GPIO_WritePin(PG4_RS485_DIR1_Port, PG4_RS485_DIR1_Pin, GPIO_PIN_RESET);GPIO_InitStruct.Pin = PG4_RS485_DIR1_Pin;GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;GPIO_InitStruct.Pull = GPIO_PULLUP;GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;HAL_GPIO_Init(PG4_RS485_DIR1_Port, &GPIO_InitStruct);
#define RS485_Receive() HAL_GPIO_WritePin(PG4_RS485_DIR1_Port, PG4_RS485_DIR1_Pin, GPIO_PIN_RESET);
#define RS485_Send() HAL_GPIO_WritePin(PG4_RS485_DIR1_Port, PG4_RS485_DIR1_Pin, GPIO_PIN_SET);
二、编写RS485发送函数
/*** @description: 控制rs485发送数据* @param {uint8_t} *data 要发送的数据* @param {size_t} len 要发送数据的长度* @return {*} 0 :发送成功;-1:发送失败;*/
int Rs485_SendData(uint8_t *data, size_t len)
{HAL_StatusTypeDef status;RS485_Receive();status = HAL_UART_Transmit(&huart1, data, len, 0xffff);RS485_Send();return status == HAL_OK ? 0 : -1;
}
三、编写RS485接收函数
RS485默认是接收模式,在函数的初始化时会设置为接收函数,然后每次发送完数据也配置为接收
#define RXBUFFERSIZE 1 /* 缓存大小 */
uint8_t g_usart_rx_buf[200]; //接收缓冲,最大200个字节
uint16_t g_usart_rx_len; //接收长度
uint8_t g_usart_rx_flag=0; //接收完成标志
uint8_t g_rx_buffer[RXBUFFERSIZE]; /* HAL库USART接收Buffer */在串口初始化函数中使能接收中断
/* 该函数会开启接收中断:标志位UART_IT_RXNE,并且设置接收缓冲以及接收缓冲接收最大数据量 */
HAL_UART_Receive_IT(&huart1, (uint8_t *)g_rx_buffer, RXBUFFERSIZE);void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{ if(huart->Instance == USART1) {g_usart_rx_buf[g_usart_rx_len] = g_rx_buffer[0] ;g_usart_rx_len++;if(g_rx_buffer[0]==0x0a){g_usart_rx_flag=1;}HAL_UART_Receive_IT(&huart1, (uint8_t *)g_rx_buffer, RXBUFFERSIZE);}
}