The code initializes the UART (Universal Asynchronous Receiver Transmitter) module and defines a function UARTRxdData().

In the UARTRxdData() function, it checks if there is data received on the UART. If there is data, it waits for a delay of 2 milliseconds. Then, it checks the length of the received data. If the length is 6, it converts the received data to a time value (hours, minutes, and seconds) and writes it to the DS1302 time module. If the length is 4, it checks if the received data is 'open' or 'close' and sets a switch variable accordingly. Finally, it resets the receive delay, receive flag, and receive count variables.

The Uart_init() function initializes the UART module by setting the necessary registers and enabling interrupts for UART receive.

void UARTRxdData()
{
   if(UartFlg==1) //  串口有数据接收
	 {
	    if(++UartTmr>=2) // 延时等待接收完毕
			{
			     if(UartCnt==6) // 如果收到数据长度为6
					 {
							 Timer[2] = (UartData[0]-0x30)*10+(UartData[1]-0x30);  // 计算时
							 Timer[1] = (UartData[2]-0x30)*10+(UartData[3]-0x30);  // 计算分 
							 Timer[0] = (UartData[4]-0x30)*10+(UartData[5]-0x30);  // 计算秒 
							 Timer[2] =  Timer[2]/10*16+Timer[2]%10;  // 10进制 转16进制
							 Timer[1] =  Timer[1]/10*16+Timer[1]%10;  // 10进制 转16进制
							 Timer[0] =  Timer[0]/10*16+Timer[0]%10;  // 10进制 转16进制
						   Ds1302WriteTime(); // 写入数据	
					 }
					 if(UartCnt==4) // 如果收到数据长度为4
					 {
						  if(UartData[0]=='o'&&UartData[1]=='p'&&UartData[2]=='e'&&UartData[3]=='n')
							{
							   Sw= 1;  // 打开
							}
							  else 	  if(UartData[0]=='c'&&UartData[1]=='l'&&UartData[2]=='s'&&UartData[3]=='e')
							{
							   Sw= 0; // 关闭 
							}
					 }
					 
				   UartTmr=0; // 接收延时
				   UartFlg=0; // 接收到数据标志位置零
				   UartCnt=0;					 
			}
	 }
}

void Uart_init(void)
{

//   TMOD |= 0x20;   //  TMOD=0010 0000B,定时器T1工作于方式2 
//   SCON |= 0x40;   //  SCON=0100 0000B,串口工作方式1
//   PCON &= 0xef;
//   TH1  = 0xfd;    
//   TL1  = 0xfd;   
//   TR1  = 1;       
	
  	SCON |= 0x50;
		TMOD |= 0x20;
		PCON |= 0x00; 
		TH1   = 0xfd; //  根据规定给定时器T1赋初值 波特率9600
		TL1   = 0xfd;  //  根据规定给定时器T1赋初值 波特率9600
		TI    = 0;
		RI    = 0;
		TR1   = 1;  //  启动定时器T1 
		IE   |= 0x90;
	  ES = 1;
}```
UART Data Receive and Processing Function (UARTRxdData) - 51 Single-Chip Microcontroller

原文地址: https://www.cveoy.top/t/topic/pInP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录