AT89C51單片機雙機通信
QQ截圖20180619103515.png (42.72 KB, 下載次數(shù): 31)
下載附件
2018-6-19 10:38 上傳
主機程序
- #include<reg51.h>
- #define shuchu0 P0
- #define shuchu2 P2
- #define KEY P1
- //unsigned char code num[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x7f};
- unsigned char code num[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e}; //共yang數(shù)碼管
- unsigned char KeyValue; //返回按鍵值
- int i;
- void Delay10ms(unsigned int c); //延時10ms
- void KeyDown(); //檢測按鍵函數(shù)
- void main(void)
- {
- while(1)
- {
- unsigned char temp=0;
- KeyDown(); //運行按鍵掃描函數(shù),返回按鍵值KeyValue=0,1,2到15
- TMOD=0x20; //設(shè)置定時器T為方式2
- TH1=0xfd; //波特率9600
- TL1=0xfd;
- SCON=0x40; //串口初始化方式1發(fā)送,不接受
- PCON=0x00; //SMOD=0,方式2,波特率=187.5kbit/s 波特率僅與SMOD的值有關(guān) 波特率選擇位
- TR1=1; //啟動T1
-
- i=KeyValue;
- if(i<=9)
- {
- shuchu0 = num[0];
- shuchu2 = num[KeyValue];
- }
- else
- {
- i=i-10;
- shuchu0 = num[1];
- shuchu2 = num[i];
- }
- while(1){
- temp=KeyValue; //讀入按鍵值
- SBUF=temp; //數(shù)據(jù)串行口發(fā)送
- while(TI==0); //如果TI=0,位發(fā)送完,循環(huán)等待
- TI=0; //數(shù)據(jù)發(fā)送完成,把TI清零
- break;
- }
- }
-
-
- }
- /*******************************************************************************
- * 函 數(shù) 名 : KeyDown
- * 函數(shù)功能 : 檢測有按鍵按下并讀取鍵值
- * 輸 入 : 無
- * 輸 出 : 無
- *******************************************************************************/
- void KeyDown(void)
- {
- char a = 0;
- KEY=0x0f;
- if(KEY!=0x0f)//讀取按鍵是否按下
- {
- Delay10ms(1);//延時10ms進行消抖
- if(KEY!=0x0f)//再次檢測鍵盤是否按下
- {
-
- //測試列
- KEY=0X0F;
- switch(KEY)
- {
- case(0X07): KeyValue=0;break;
- case(0X0b): KeyValue=4;break;
- case(0X0d): KeyValue=8;break;
- case(0X0e): KeyValue=12;break;
- }
- //測試行
- KEY=0XF0;
- switch(KEY)
- {
- case(0X70): KeyValue=KeyValue+3;break;
- case(0Xb0): KeyValue=KeyValue+2;break;
- case(0Xd0): KeyValue=KeyValue+1;break;
- case(0Xe0): KeyValue=KeyValue;break;
- }
- while((a<50) && (KEY!=0xf0)) //檢測按鍵松手檢測
- {
- Delay10ms(1);
- a++;
- }
- }
- }
- }
- void Delay10ms(unsigned int c)
- {
- unsigned char a, b;
- for (;c>0;c--)
- {
- for (b=38;b>0;b--)
- {
- for (a=130;a>0;a--);
- }
- }
- }
- 從機程序
- #include<reg51.h>
- unsigned char code num[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e}; //共yang數(shù)碼管
- unsigned char i;
- #define shuchu0 P0
- #define shuchu2 P2
- void main(void)
- {
- while(1){
- unsigned char temp=0;
- TMOD=0x20; //設(shè)置串口為方式1接收,REN=1,REN允許串行接收位
- TH1=0xfd;
- TL1=0xfd;
- SCON=0x50;
- PCON=0x00;
- TR1=1; //啟動T1
- while(1)
- {
- while(RI==0); //若TI為0,未接收到數(shù)據(jù)
- RI=0; //接收到數(shù)據(jù),把RI清零
- temp=SBUF; //讀取數(shù)據(jù)存入temp中
- i=temp;
- if(i<=9)
- {
- shuchu0 = num[0];
- shuchu2 = num[i];
- }
- else
- {
- i=i-10;
- shuchu0 = num[1];
- shuchu2 = num[i];
- }
- }
- }
- }
復制代碼
|