usart初始化
void usart_init(void)
{
rcu_periph_clock_enable(RCU_USART0);
usart_deinit(USART0);
usart_baudrate_set(USART0, 115200U);
usart_parity_config(USART0, USART_PM_NONE);
usart_word_length_set(USART0, USART_WL_8BIT);
usart_stop_bit_set(USART0, USART_STB_1BIT);
usart_receive_config(USART0, USART_RECEIVE_ENABLE);
usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
usart_data_first_config(USART0,USART_MSBF_LSB);
usart_wakeup_mode_config(USART0,USART_WUM_RBNE);
nvic_irq_enable(USART0_IRQn,0);
usart_enable(USART0);
usart_interrupt_enable(USART0, USART_INT_RBNE);
usart_interrupt_enable(USART0, USART_INT_IDLE);
usart_receiver_timeout_enable (USART0);
}
usart接收中断
void USART0_IRQHandler(void)
{
#if 1
if(SET == usart_interrupt_flag_get(USART0, USART_INT_FLAG_RBNE))
{
recv_ch = usart_data_receive(USART0);
receiver[receiver_num]=recv_ch;
receiver_num++;
if(receiver_num>=200)
{
memset(receiver,0,sizeof(receiver));
recevie_flag = 2;
receiver_num=0;
}
}
else if(usart_interrupt_flag_get(USART0, USART_INT_FLAG_IDLE) != RESET)
{
usart_interrupt_flag_clear(USART0, USART_INT_FLAG_IDLE);
recevie_flag=1;
temp_num=receiver_num;
receiver_num=0;
}
if(SET == usart_interrupt_flag_get(USART0, USART_INT_FLAG_RBNE_ORERR))
{
usart_interrupt_flag_clear(USART0, USART_INT_FLAG_RBNE_ORERR);
usart_flag_clear(USART0,USART_FLAG_ORERR);
}
#endif
}
重点封装函数
void SendCmd(char* cmd, char* result, int timeOut)
{
uint8_t i = 0;
memset(receiver, 0, sizeof(receiver));
receiver_num = 0;
delay_1ms(timeOut);
for(i = 0;i < 5; i++)
{
if(strstr(receiver,result))
{
receiver_num=0;
memset(receiver, 0, sizeof(receiver));
break;
}
else
{
receiver_num = 0;
memset(receiver, 0, sizeof(receiver));
printf("%s",cmd);
delay_1ms(timeOut);
}
}
}
main.c例子
SendCmd("AT\r\n", "OK", 100);
SendCmd("ATE0\r\n", "OK", 250);
SendCmd("AT+CPIN\?\r\n", "OK", 250);
SendCmd("AT+CGATT\?\r\n","1", 250);