- #include <reg52.h>
- #include<intrins.h>
- //#define _nop() _asm nop _endasm
- typedef unsigned char uchar;
- typedef unsigned int uint;
- sbit RX = P2^0;//接收
- sbit TX = P2^1;//发射
- uchar flag;
- uchar date_distance[5];//距离
- uchar kk;
- sbit duan = P2^6;//段选
- sbit wei = P2^7;//位选
-
-
-
-
- uchar duan1[] = {0X3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x00};
- uchar wei1 [] = {0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
-
- // void delay_10us(uchar i)
- // {
- // while(i--);
- // }
-
- void delay_ms(uint c)
- {
- uint a,b;
- for(;c>0;c--)
- for(b=102;b>0;b--)
- for(a=3;a>0;a--);
- }
-
- void init_wei(uchar i)
- {
- P0 = 0xff;
- wei = 1;
- P0 = wei1[i] ;
- wei = 0;
- }
-
- void init_timer()// 定时器初始化
- {
- TMOD = 0X11;// 定义定时器定时类型
- TH0 = 0x00;// 定时器0高位
- TL0 = 0x00;// 定时器0低位
- EA = 1;// 单片机中断总开关
- ET0 = 1;// 允许T0溢出中断
-
-
- TH1 = 0xf8;// 定时器1高位
- TL1 = 0xCD;// 定时器1低位
- ET1 = 1;// 允许T1溢出中断
- TR1 = 1;// 定时器1的运行控制位
- }
-
- void count_distance()// 距离数
- {
-
- uint distance = (TH0*256+TL0*1)*0.18;// 通过时间算距离
- TH0 = 0;
- TL0 = 0;
- // 计时器归零
- if(distance>=4000||distance < 20)
- {
- flag = 1;
- }
- else
- {
- date_distance[1] = distance%10000/1000;
- date_distance[2] = distance%1000/100;
- date_distance[3] = distance%100/10;
- date_distance[4] = distance%10/1;
- }
- }
- void display()// 显示
- {
- uchar i;
- if(flag==1)
- {
- flag = 0;
- date_distance[1] = 14;
- date_distance[2] = 14;
- date_distance[3] = 14;
- date_distance[4] = 14;
- }
- count_distance();
- for(i = 1;i<=4;i++)
- {
-
- init_wei(i);
- duan = 1;
- if(i==1)
- P0 = duan1[date_distance[i]]|0x80;
- else
- P0 =duan1[date_distance[i]];
- delay_ms(1);
- duan = 0;
- P0 = 0x00;
- }
-
- }
-
- void main()
- {
- RX = 0;
- TX=0;
- init_timer();//定时器初始化
- while(1)
- {
- TR1=1;
- while(!RX);// 收到信号RX为零
- TR0 = 1;
-
- while(RX);
- TR0 = 0;
- count_distance();
- }
- }
-
-
- void timer0() interrupt 1
- {
- flag = 1;
- }
- void timer1() interrupt 3
- {
- TR1 = 0;
- TH1 = 0xf8;
- // 0xf8;
- TL1 = 0xcd;
- // 0xcd;
-
- kk ++;
- display();
- if(kk>100)
- {
- kk = 0;
- TX = 1;
- _nop_();_nop_();_nop_();_nop_();
- _nop_();_nop_();_nop_();_nop_();
- _nop_();_nop_();_nop_();_nop_();
- _nop_();_nop_();_nop_();_nop_();
- TX = 0;
- }
- TR1 = 1;
- }
复制代码
|