//晶振:11.0592MHz //收數據 #include <AT89X52.h> sbit TSCLK=P3^3; sbit TSDAT=P1^6; sbit LED1=P2^0; sbit LED2=P2^1; sbit LED3=P2^2; sbit LED4=P2^3; sbit LED5=P2^4; sbit LED6=P2^5; sbit LED7=P2^6; sbit LED8=P2^7; sbit fmq=P3^6; //這是蜂鳴器 unsigned char num[4]={0,0,0,0}; unsigned char code DIS_SEG7[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e}; unsigned int lowtime,hightime; //延遲n毫秒 void delay(unsigned int n) { while (n--) { TH0=0xfc; TL0=0x66; //11.0592MHz TF0=0; TR0=1; while (TF0==0); TF0=0; } } void superdelay(unsigned char h, unsigned char l) { TH0=h; TL0=l; TF0=0; TR0=1; while (TF0==0); TR0=0; } //延遲半毫秒 void delay500us() { superdelay(0xfe,0x33); } //蜂鳴器 void beep() { unsigned char i; for (i=0;i<150;i++) { fmq=0; delay500us(); fmq=1; delay500us(); } } void receivebyte(unsigned char* Data) { unsigned char i; unsigned int time; for (i=0;i<8;i++) { *Data<<=1; //不應該在for循環的最後執行此操作,否則第一位會丟失 TH0=TL0=0; while (TSDAT==0); //跳過低電平 TR0=1; while (TSDAT==1 && TF0==0); //根據高電平長度判斷是0還是1 TR0=0; time=TH0*256+TL0; if (time>950) *Data|=0x01; //讀1 else *Data&=0xfe; //讀0 } } void Display() { P0=0xff; LED1=0; P0=DIS_SEG7[num[0]/10]; delay(1); LED1=1; P0=0xff; LED2=0; P0=DIS_SEG7[num[0]%10]; delay(1); LED2=1; P0=0xff; LED3=0; P0=DIS_SEG7[num[1]/10]; delay(1); LED3=1; P0=0xff; LED4=0; P0=DIS_SEG7[num[1]%10]; delay(1); LED4=1; P0=0xff; LED5=0; P0=DIS_SEG7[num[2]/10]; delay(1); LED5=1; P0=0xff; LED6=0; P0=DIS_SEG7[num[2]%10]; delay(1); LED6=1; P0=0xff; LED7=0; P0=DIS_SEG7[num[3]/10]; delay(1); LED7=1; P0=0xff; LED8=0; P0=DIS_SEG7[num[3]%10]; delay(1); LED8=1; } void main() { TMOD=0x01; //定時器2工作於16位查詢工作方式 TR0=0; EA=1; EX1=1; IT1=1; while (1) { P1_7=0; Display(); P1_7=1; } } void int1() interrupt 2 { EX1=0; //檢測引導碼 //數據線1ms低電平和2.5ms高電平 TH0=TL0=0; TR0=1; while (TSDAT==0); TR0=0; lowtime=TH0*256+TL0; TH0=TL0=0; TR0=1; while (TSDAT==1); TR0=0; hightime=TH0*256+TL0; //對於低電平:1000us/1.085=921,實際值通常為934 //對於高電平:2500/1.085=2304,實際值通常為2365或2367 if (lowtime>880 && lowtime<980 && hightime>2300 && hightime<2400) { receivebyte(&num[0]); receivebyte(&num[1]); receivebyte(&num[2]); receivebyte(&num[3]); delay500us(); //全部數據接收完畢後,等待時鐘線拉高,防止再次進入本中斷 } else beep(); //引導碼不合法 EX1=1; }
|