#include "rs485_driver.h" #include static UART_HandleTypeDef *g_huart_485 = NULL; static GPIO_TypeDef* g_de_re_port = NULL; static uint16_t g_de_re_pin = 0; volatile uint8_t g_rs485_tx_busy = 0; void RS485_Init(UART_HandleTypeDef *huart, GPIO_TypeDef* de_re_port, uint16_t de_re_pin) { g_huart_485 = huart; g_de_re_port = de_re_port; g_de_re_pin = de_re_pin; g_rs485_tx_busy = 0; HAL_GPIO_WritePin(g_de_re_port, g_de_re_pin, GPIO_PIN_RESET); // 初始为接收模式 } HAL_StatusTypeDef RS485_SendData(uint8_t *pData, uint16_t Size) { HAL_StatusTypeDef ret; if (g_rs485_tx_busy) { return HAL_BUSY; } g_rs485_tx_busy = 1; HAL_GPIO_WritePin(g_de_re_port, g_de_re_pin, GPIO_PIN_SET); // 设置为发送模式 ret = HAL_UART_Transmit_IT(g_huart_485, pData, Size); // 注意:不能在这里立即切换回接收模式! // DMA传输是非阻塞的,需要在传输完成回调中切换 if (ret != HAL_OK) { // 如果启动DMA失败,需要清除忙标志并切换回接收模式 HAL_GPIO_WritePin(g_de_re_port, g_de_re_pin, GPIO_PIN_RESET); g_rs485_tx_busy = 0; } // 等待数据传输完成 while(g_rs485_tx_busy) { ; } return ret; } // UART DMA传输完成回调函数 void RS485_TxCpltCallback(UART_HandleTypeDef *huart) { if (huart == g_huart_485) { // DMA传输完成后切换回接收模式 HAL_GPIO_WritePin(g_de_re_port, g_de_re_pin, GPIO_PIN_RESET); g_rs485_tx_busy = 0; } }