任务: PC按下1键, mcu连续发送a, 当PC按下2键, 终止发送
查询:
1 #include <reg52.h> 2 #define uint unsigned int 3 #define uchar unsigned char 4 uint receive ; 5 6 void tranData(); 7 void delay(uint ms) 8 { 9 for( ;ms>0;ms--); 10 11 } 12 void main(void) 13 { 14 EA = 1; //允许总中断(如不使用中断,可用//屏蔽) 15 ES = 1; //允许UART串口的中断 16 TMOD = 0x20; //定时器T/C1工作方式2 17 SCON = 0x50; //串口工作方式1,允许串口接收(SCON = 0x40 时禁止串口接收) 18 TH1 = 0xF3; //定时器初值高8位设置 //12MHZ晶振,波特率为4800 0xf3 19 TL1 = 0xF3; //定时器初值低8位设置 //11.0592MHZ晶振,波特率为4800 0xf4 9600 0xfa 19200 0xfd 20 PCON = 0x80; //波特率倍频(屏蔽本句波特率为2400) 21 TR1 = 1; //定时器启动 22 23 while(1) 24 { 25 receive=SBUF; 26 tranData(); 27 delay(500000) ; 28 } 29 } 30 31 void tranData() //interrupt 4 32 { RI=0; 33 if((receive==0x31)) 34 { 35 SBUF='a'; 36 while(!TI); 37 TI=0; 38 39 } 40 else if((receive==0x32)) 41 { 42 TI=1; 43 } 44 45 } 46 47
中断:
1 #include <reg52.h> 2 #define uint unsigned int 3 #define uchar unsigned char 4 uint receive ; 5 6 void tranData(); 7 void delay(uint ms) 8 { 9 for( ;ms>0;ms--); 10 11 } 12 void main(void) 13 { 14 EA = 1; 15 ES = 1; 16 TMOD = 0x20; 17 SCON = 0x50; 18 TH1 = 0xF3; 19 TL1 = 0xF3; 20 PCON = 0x80; 21 TR1 = 1; 22 23 while(1); 24 } 25 26 void tranData() interrupt 4 27 { 28 receive=SBUF; 29 while(1) 30 { 31 if (receive==0x31) 32 { 33 SBUF='a'; 34 while(!TI); 35 TI=0; 36 } 37 else if (receive==0x32) 38 { 39 TI=1; 40 } 41 42 RI=0; 43 receive=SBUF; 44 delay(500000); 45 } 46 } 47 48