最近在实现lora通信网关的代码,用到了RS485实现串口接收数据,其主要代码及完整代码如下:
RS485串口初始化:
/*串口1初始化*/
void rs485_usart_init(){
rcu_periph_clock_enable(RCU_USART1); //使能串口时钟
usart_disable(USART1);
usart_baudrate_set(USART1, baudrate); //波特率
usart_parity_config(USART1, parity); //奇偶校验位
usart_word_length_set(USART1, wlen); //数据位
usart_stop_bit_set(USART1, stblen); //停止位
usart_hardware_flow_rts_config(USART1, USART_RTS_DISABLE); //禁用RTS
usart_hardware_flow_cts_config(USART1, USART_CTS_DISABLE);//无硬件数据流控制
usart_receive_config(USART1, USART_RECEIVE_ENABLE); //使能接收
usart_transmit_config(USART1, USART_TRANSMIT_ENABLE);//使能发送
usart_enable(USART1);
drv_usart_nvic_init();
usart_interrupt_enable(USART1, USART_INT_RBNE);
}
定时器初始化
void Timer_init(void)
{
timer_parameter_struct timer_initpara;
/*使能时钟*/
rcu_periph_clock_enable(RCU_TIMER1);
timer_deinit(TIMER1);
/* TIMER0 configuration */
timer_initpara.prescaler = 99; //分频系数
timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
timer_initpara.counterdirection = TIMER_COUNTER_UP; //计数方式
timer_initpara.period = 7199; //重载周期
timer_initpara.clockdivision = TIMER_CKDIV_DIV1; //时钟分频因子
timer_initpara.repetitioncounter = 0;
timer_init(TIMER1,&timer_initpara); //初始化
timer_interrupt_enable(TIMER1,TIMER_INT_UP);//允许中断
nvic_irq_enable(TIMER1_IRQn , 1, 1);
timer_disable(TIMER1);
}
串口1中断服务函数
void USART1_IRQHandler(void)
{
uint32_t res;
if( RESET != usart_flag_get(USART1, USART_FLAG_RBNE)) //接收到数据
{
res=usart_data_receive(USART1);
if ((RS485_RX_STA & (1<<15)) == 0) //接收完的一批数据,还没有被处理,则不再接收其他数据
{
if (RS485_RX_STA <rs485_rx_max) //串口1接收缓冲区还没满,还可以接收数据
{
timer_counter_value_config(TIMER1,0); //计数器清空
if(RS485_RX_STA == 0) //一次接收的开始时USART3_RX_STA = 0;
{
timer_enable(TIMER1); //使能定时器1
}
RS485_RX_BUF[RS485_RX_CNT]=res; //记录接收到的值
RS485_RX_STA++; //接收数据增加 1
RS485_RX_CNT++;
}
else //定义的最大缓冲区满了
{
RS485_RX_STA |= 1<<15; //强制标记接收完成