资源描述:
《单片机c语言双机通信》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、一.单片机与PC机通信(1)mcu2pc(1)#include#defineucharunsignedchar#defineuintunsignedintuchartemp,num;ucharcodetable[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};//串行口初始化函数voidspinit(){//串行口工作方式设定SCON=0x50;//串行通信波特率设定PCON=0x00;TMOD=0x20;TH1=253;TL1=253;
2、TR1=1;//串行口中断允许EA=1;ES=1;}//串行口中断服务函数voidspsv()interrupt4{if(RI==1){RI=0;temp=SBUF;SBUF=temp;if(temp=='1')num++;}if(TI==1)TI=0;}//显示函数voiddisplay(){P0=table[num/10];P2=table[num%10];}//主函数voidmain(){spinit();P0=table[0];while(1){if(num==100)num=0;display();}}(2)课本#include#defineuc
3、harunsignedchar#defineuintunsignedintuchardat,num;sbitwei1=P2^0;sbitwei2=P2^1;ucharcodetable[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};voiddelay(uintz){uintx,y;for(x=z;x>0;x--)for(y=110;y>0;y--);}voidinit_serial(){SCON=0x50;TMOD=0X20;PCON=0X00;TH1=0xfd;TL1=0xfd;TR1=1;EA=1;ES=1;
4、}voidserial()interrupt4{if(RI==1){RI=0;dat=SBUF;if(dat=='1'){num++;}SBUF=dat;}elseif(TI==1)TI=0;}voiddisplay(){P0=table[num/10];wei1=0;delay(1);wei1=1;P0=table[num%10];wei2=0;delay(1);wei2=1;}voidmain(){init_serial();while(1){if(num==100)num=0;display();}}一.单片机与单片机通信(1)双机通信-方式1Rxd#include<
5、reg51.h>#defineucharunsignedchar#defineuintunsignedintucharcodetable[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x00};voidmain(){TMOD=0x20;TH0=253;TL0=253;TR1=1;PCON=0x00;SCON=0x50;EA=1;ES=1;P0=table[10];while(1);}voidrxd()interrupt4{RI=0;P0=table[SBUF];}Txd#include#defi
6、neucharunsignedchar#defineuintunsignedintsbitkey=P3^7;ucharkeynum;voidmain(){TMOD=0x20;TH0=253;TL0=253;TR1=1;PCON=0x00;SCON=0x40;EA=1;ES=1;while(1){if(key==0){while(key==0);keynum++;if(keynum>=10)keynum=0;SBUF=keynum;}}}voidtxd()interrupt4{TI=0;}(1)双击通信-方式2&3RXD#include#defineucha
7、runsignedchar#defineuintunsignedintucharcodetable[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x00};voidmain(){TMOD=0x20;TH0=253;TL0=253;TR1=1;PCON=0x00;SCON=0xb0;//10110000EA=1;ES=1;P0=table[10];while(1);}voidrxd()interrupt4{RI=0;P0=table[SBUF];}TXD#