51 serial communication transmission and reception

   //The baud rate of sending data is 9600
//1. If a string starting with $ is sent on the computer, the entire string will be returned as it is (the length of the string is not fixed).
//2. If 1 is received, set P10 to high level, and if 0 is received, set P01 to low level. (Used to control an LED)
#include "STC/STC15F2K60S2.H"
sbit LED = P0^1;
sbit ledle = P2^5;
sbit bell = P4^5;
unsigned char UART_buff,buff;
bit New_rec = 0, Send_ed = 1, Money = 0;
unsigned flag1 = 0;//Receive complete flag
unsigned flag2 = 0; //Send complete flag
//-------------------- --------------------------
void main (void)
{
// ledle = 1;
 SCON = 0x50; //Serial port mode 1, allowing reception
 AUXR = 0x00;
 PCON = 0x00;
 TMOD = 0x20; //Timer working mode 2, using timer 1 as the baud rate generator
    TH1 = 0xFD; 
    TL1 = 0xFD;
 REN = 1;   
 TR1 = 1; //Enable timer T1                
    ES = 1; //Enable serial port interrupt.
    EA = 1; //Enable general interrupt
 
    while(1)
 {
     if(flag1 == 1)
   LED = 0;
  if(flag1 == 0)
   LED = 1;
    
  while(flag2 == 0);
       while(1)
  {
   if(flag2 == 1)
   {
    SBUF = UART_buff;  
    flag2 = 0;
   }
  }           
     
  
 }
}


//----------------------------------------------
void ser_int (void) interrupt 4
{
    if(RI == 1)
 {//if received
      RI = 0; //clear the flag
 
 UART_buff = SBUF;
 if(UART_buff == '1') //input text mode 1 light up the LED
   flag1 = 1;
    if(UART_buff == '0') //    Turn off the LED
 { 
flag1 = 0;
 }
 if(UART_buff =='$') 
  flag2 = 1;
  }
 else //Send completed
 {
   TI = 0; //Clear the flag
  Send_ed = 1;
 }
 
}
//------------------------------------------ ----

Guess you like

Origin blog.csdn.net/zl1107604962/article/details/47208221