| 
 
| c #include "gd32f10x.h"
 #include "usart.h"
 #include "gpio.h"
 
 // 假设使用USART0作为485通信接口
 #define RS485_TX_EN_PIN GPIO_PIN_0
 #define RS485_RX_EN_PIN GPIO_PIN_1
 #define RS485_CTRL_PORT GPIOA
 
 void rs485_init(void) {
 // 初始化USART0
 usart_deinit(USART0);
 usart_baudrate_set(USART0, 9600U);
 usart_word_length_set(USART0, USART_WL_8BIT);
 usart_stop_bit_set(USART0, USART_STB_1BIT);
 usart_parity_config(USART0, USART_PM_NONE);
 usart_hardware_flow_rts_config(USART0, USART_RTS_DISABLE);
 usart_hardware_flow_cts_config(USART0, USART_CTS_DISABLE);
 usart_receive_config(USART0, USART_RECEIVE_ENABLE);
 usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
 usart_enable(USART0);
 
 // 初始化GPIO用于控制485收发器
 gpio_init(RS485_CTRL_PORT, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, RS485_TX_EN_PIN | RS485_RX_EN_PIN);
 gpio_bit_reset(RS485_CTRL_PORT, RS485_TX_EN_PIN); // 初始化为接收模式
 gpio_bit_set(RS485_CTRL_PORT, RS485_RX_EN_PIN);
 }
 
 void rs485_send_data(uint8_t *data, uint16_t len) {
 // 切换为发送模式
 gpio_bit_set(RS485_CTRL_PORT, RS485_TX_EN_PIN);
 gpio_bit_reset(RS485_CTRL_PORT, RS485_RX_EN_PIN);
 
 // 发送数据
 for (uint16_t i = 0; i < len; i++) {
 usart_data_transmit(USART0, data[i]);
 while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET);
 }
 
 // 切换回接收模式
 gpio_bit_reset(RS485_CTRL_PORT, RS485_TX_EN_PIN);
 gpio_bit_set(RS485_CTRL_PORT, RS485_RX_EN_PIN);
 }
 
 // 假设使用中断方式接收数据
 void USART0_IRQHandler(void) {
 if (usart_interrupt_flag_get(USART0, USART_INT_FLAG_RBNE) != RESET) {
 uint8_t data = usart_data_receive(USART0);
 // 将接收到的数据存储到缓冲区或进行转发处理
 }
 }
 
 int main(void) {
 rs485_init();
 // 使能USART0接收中断
 usart_interrupt_enable(USART0, USART_INT_RBNE);
 nvic_irq_enable(USART0_IRQn, 0, 0);
 
 while (1) {
 // 应用程序逻辑,包括指令发送和回复数据处理
 // 例如:rs485_send_data(指令数据, 指令长度);
 }
 }
 | 
 |