//MCS-51通過中斷方式接收pc機發來的字符,并回送給主機 #include #include #define uchar unsigned char uchar xdata rt_buf[32]; uchar r_in,t_out; bit r_full,t_empty; serial() interrupt 4 //串口中斷程序 { if(RI && r_full) { rt_buf[r_in]=SBUF; RI=0; if(rt_buf[r_in]==0x24) { r_full=1; SBUF=rt_buf[t_out]; t_empty=0; } /*接收字符為$,則接收結束;設置接收結束標志,開始發送*/ r_in=++r_in; } else if(TI && t_empty) { TI=0; t_out=++t_out; SBUF=rt_buf[t_out]; if(t_out==r_in) t_empty=1; /*t_out=r_in則發送完,設發送完標志t_empty*/ } } main() { /*設置定時器T1工作于方式2,計數常數為0xfdH */ TMOD=0x20; //TMOD:GATE C/T1 M1 M0 GATE C/T0 M1 M0 0010 0000 以TR啟動定時 TL1=0xfd; //定時3us TH1=0xfd; SCON=0x50; //在11.0592MHz下,設置串行口波特率為9600,方式1,允許接收 01010000 PCON=0xD0; // 11010000 波特率加倍 IE=0x10; //00010000 允許串行中斷ES=1 TR1=1; EA=1; r_in=t_out=0; t_empty =1; r_full=0; for(;;) { printf ("%s","serial communication\n"); //添加自己的程序處理代碼 } } 附上: proteus下單片機和pc機串口的連接圖 |