串口通信模块的实现:C_UART.c
send_busy 用来判断是否发送繁忙
recv_timeout 用来检测一次数据是否接收完成
uart_buff 是串口数据缓存
str_buff 是接收的数据的缓存
UartReceived中会判断,如果recv_timeout>0,则代表接收到了数据,然后循环将数据存入str_buff中,直到对方发送结束,并返回1代表有数据
- #include "C_UART.h"
- #include "INTRINS.H"
-
- bit send_busy;
- uchar recv_timeout;
- struct BUFF_DATA xdata uart_buff,xdata str_buff;
-
- void Delay1ms(void) //@5.5296MHz
- {
- unsigned char data i, j;
-
- _nop_();
- _nop_();
- i = 8;
- j = 43;
- do
- {
- while (--j);
- } while (--i);
- }
-
- void Delay_ms(uint times) //@5.5296MHz
- {
- unsigned char data i, j;
- while (times-->0)
- {
- _nop_();
- _nop_();
- i = 8;
- j = 43;
- do
- {
- while (--j);
- } while (--i);
- }
- }
-
-
- void Uart1_Isr(void) interrupt 4
- {
- if (TI)
- {
- TI = 0;
- send_busy = 0;
- }
- if (RI)
- {
- RI = 0;
- BUFF_PUSH(uart_buff,SBUF);
- recv_timeout = 5;
- }
- }
-
- void Uart1_Init(void) //19200bps@5.5296MHz
- {
- SCON = 0x50; //8位数据,可变波特率
- AUXR &= 0xBF; //定时器时钟12T模式
- AUXR &= 0xFE; //串口1选择定时器1为波特率发生器
- TMOD &= 0x0F; //设置定时器模式
- TL1 = 0xFA; //设置定时初始值
- TH1 = 0xFF; //设置定时初始值
- ET1 = 0; //禁止定时器中断
- TR1 = 1; //定时器1开始计时
- ES = 1; //使能串口1中断
- EA = 1;
-
- send_busy = 0;
- BUFF_RESET(uart_buff);
- }
-
- void UartSend(char dat)
- {
- while(send_busy);
- send_busy = 1;
- SBUF = dat;
- }
-
- void UartSendStr(const char *p)
- {
- while(*p)
- UartSend(*p++);
- }
-
- void UartSendData(const char *p,uchar len)
- {
- while (len-->0)
- UartSend(*p++);
- }
-
- //串口接收数据,如果返回1,则表示有数据,返回0表示未收到数据,接收的数据储存在str_buff中
- bit UartReceived()
- {
- if(recv_timeout>0)
- {
- BUFF_RESET(str_buff);
- while(recv_timeout>0)
- {
- BUFF_CPY(uart_buff,str_buff)
- recv_timeout--;
- Delay1ms();
- }
- BUFF_PUSH(str_buff,0);
- return 1;
- }
- return 0;
- }
复制代码
|