STM32-串口超時(shí)判斷方式接收未知長度數(shù)據(jù)
本文引用地址:http://m.butianyuan.cn/article/201611/320443.htm
[cpp]view plaincopy
- voidUSART1_IRQHandler(void)
- {
- u8res;
- if(USART1->SR&(1<<5))//接收到數(shù)據(jù)
- {
- res=USART1->DR;
- if(USART1_Recv_Len
- {
- TIM3->CNT=0;//計(jì)數(shù)器清空
- if(Rec_Over_Flag==0)TIM3_Set(1);//使能定時(shí)器4的中斷
- USART1_RX_BUF[USART1_Recv_Len++]=res;//記錄接收到的值
- }else
- {
- Rec_Over_Flag=1;//強(qiáng)制標(biāo)記接收完成
- }
- }
- }
- timer.c定時(shí)器中斷函數(shù)
- //定時(shí)器3中斷服務(wù)程序
- voidTIM3_IRQHandler(void)
- {
- if(TIM3->SR&0X0001)//溢出中斷
- {
- Rec_Over_Flag=1;
- TIM3->SR&=~(1<<0);//清除中斷標(biāo)志位
- TIM3_Set(0);
- LED1=!LED1;//RxTimeout等于0,變換LED1表明該次發(fā)送結(jié)束
- }
- }
- //設(shè)置TIM4的開關(guān)
- //sta:0,關(guān)閉;1,開啟;
- voidTIM3_Set(u8sta)
- {
- if(sta)
- {
- TIM3->CNT=0;//計(jì)數(shù)器清空
- TIM3->CR1|=1<<0;//使能定時(shí)器3
- }elseTIM3->CR1&=~(1<<0);//關(guān)閉定時(shí)器3
- }
main.c主函數(shù)
[cpp]view plaincopy
- intmain(void)
- {
- u8t;
- u8Password[7]="123456";
- u8Tishi1[]="操作碼長度不對";
- u8Tishi2[]="操作碼不正確";
- u8Tishi3[]="指令成功執(zhí)行!";
- u16times=0;
- Stm32_Clock_Init(9);//系統(tǒng)時(shí)鐘設(shè)置
- delay_init(72);//延時(shí)初始化
- uart_init(72,57600);//串口初始化為57600
- LED_Init();//初始化與LED連接的硬件接口
- Timerx_Init(99,7199);//10kHz的技術(shù)頻率,計(jì)數(shù)到100為10ms
- while(1)
- {
- if(Rec_Over_Flag==1)
- {
- if(USART1_Recv_Len!=0x06)//USART1_Recv_Len接收數(shù)據(jù)的長度不等于6
- {
- Putstrings(Tishi1);
- }
- else//USART1_Recv_Len接收數(shù)據(jù)的長度等于6
- {
- for(t=0;t
- {
- if(USART1_RX_BUF[t]!=Password[t])
- {
- Putstrings(Tishi2);
- break;
- }
- elseif(t==(USART1_Recv_Len-1))
- {
- Putstrings(Tishi3);
- LED0=!LED0;
- }
- }
- }
- Rec_Over_Flag=0;
- USART1_Recv_Len=0;
- }
- else
- {
- times++;
- //if(times%30==0)LED1=!LED1;//閃爍LED,提示系統(tǒng)正在運(yùn)行.
- //if(times%30==0)RxTimeout--;
- delay_ms(10);
- }
- }
- }
- //------------輸出字符串到串口-------------------
- voidPutstrings(u8*ptr)
- {
- while(*ptr!=