最近在弄Lora 通信网关代码,用到了RS485发送接收数据,RS485半双工通信,芯片上有一发送接收使能引脚,PA8。高电平接收,低电平发送。
RS485接收发送使能主要代码如下
/*接收使能*/
void rs485_receive_enable(){
gpio_bit_set(GPIOA, GPIO_PIN_8);
}
/*发送使能*/
void rs485_send_enable(){
gpio_bit_reset(GPIOA, GPIO_PIN_8);
}
接下来是RS485硬件初始化,其主要代码如下:
void rs485_hw_init(){
/* enable the led clock */
rcu_periph_clock_enable(RCU_GPIOA);
/* connect port to USARTx_Tx */
gpio_af_set(GPIOA, GPIO_AF_1, GPIO_PIN_2);
/* connect port to USARTx_Rx */
gpio_af_set(GPIOA, GPIO_AF_1, GPIO_PIN_3);
/* configure USART Tx as alternate function push-pull */
gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_2);
gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, GPIO_PIN_2);
/* configure USART Rx as alternate function push-pull */
gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_3);
gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, GPIO_PIN_3);
//配置使能端口
gpio_mode_set(GPIOA, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN_8);
gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OTYPE_PP, GPIO_PIN_8);
//gpio_bit_reset(GPIOA, GPIO_PIN_8);
rs485_receive_enable();
}
紧接着RS485串口初始化:
/*串口1初始化*/
void rs485_usart_init(){
rcu_periph_clock_enable(RCU_USART1); //使能串口时钟
usart_disable(USART1);