- #include <stc15f2k60s2.h>
- #include "intrins.h"
- #define uchar unsigned char
- #define uint unsigned int
-
- sbit TX = P1^0; //发射引脚
- sbit RX = P1^1; //接收引脚
- uchar tab[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90, 0xff,0x8e};
- uchar code weixuan[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
- uchar dspbuf[] = {10,10,10,10,10,10,10,10};
- uint distance,time = 0,intr=0;
- uchar s_flag = 0,du=0,moshi;
- void display();
- void moshi0();
- void moshi1();
- void xian();
- void Delay12us();
- void send_wave();
- void all_chushihua();
- void all_chushihua()
- {
- P0 = 0xff;
- P2 = (P2 & 0x1f) | 0x80;
- P2 = 0x1f;
- P0 = 0x00;
- P2 = (P2 & 0x1f) | 0xa0;
- P2 = 0x1f;
- P0=0XFF;
- P2=(P2&0X1F)|0XC0;
- P2=P2&0X1F;
- P0=0XFF;
- P2=(P2&0X1F)|0XE0;
- P2=P2&0X1F;
- }
- void main(void)
- {
- all_chushihua();
- //AUXR = 0x80;
- TMOD = 0x11; //配置定时器工作模式
- TH0 = (65535-2000)/256;
- TL0 = (65535-2000)/256;
- TH1 = 0;
- TL1 = 0;
- TR0 = 1; //启动定时器
- EA = 1;
- ET0 = 1; //打开定时器0中断
- while(1)
- {
- /** 200毫秒更新一次数据 */
- if(s_flag)
- {
- s_flag = 0;
- /** 关闭定时器0中断:计算超声波发送到返回的时间 */
- // ET0 = 0;
- send_wave(); //发送方波信号
- TR1 = 1; //启动计时
- while((RX == 1) && (TF1 == 0)); //等待收到脉冲,没有计满溢出
- TR1 = 0; //关闭计时
- //发生溢出
- if(TF1 == 1)
- {
- TF1 = 0;
- distance = 9999; //无返回
- moshi=0;
- }
- else
- {
- /** 计算时间 */
- time=TH1*256+TL1;
- distance = (unsigned int)(time*0.017); //计算距离 340 00 /1000 000/2=0.017
- if(distance<10) distance=10; //在这规范那个范围内,
- if(distance>50) distance=50;
- moshi=1;
- }
- TH1 = 0;
- TL1 = 0;
- }
- }
- }
- //定时器0中断服务函数
- void time0() interrupt 1 //默认中断优先级 1
- {
- TH0 = (65535-2000)/256;
- TL0 = (65535-2000)/256;
- if(++intr == 100){
-
- s_flag = 1;intr = 0;}
-
- display();
- }
- void Delay12us()//@11.0592MHz
- {
- unsigned char i;
- _nop_();
- _nop_();
- _nop_();
- i = 30;
- while (--i);
- }
- void send_wave()//发送八段脉冲波(40Khz)
- {
- unsigned char i = 8;
-
- while(i --)
- {
- TX = 1;
- Delay12us();
- TX = 0;
- Delay12us();
- }
- }
- void xianshi0()
- {
- switch(du)
- {
- case 0:P0=tab[11];break;
- case 1:P0=tab[10];break;
- case 2:P0=tab[10];break;
- case 3:P0=tab[10];break;
- case 4:P0=tab[10];break;
- case 5:P0=tab[10];break;
- case 6:P0=tab[10];break;
- case 7:P0=tab[10];break;
- }
- }
- void xianshi1()
- {
- switch(du)
- {
- case 0:P0=tab[10];break;
- case 1:P0=tab[10];break;
- case 2:P0=tab[10];break;
- case 3:P0=tab[10];break;
- case 4:P0=tab[10];break;
- case 5:P0=tab[distance/100%10];break;
- case 6:P0=tab[distance/10%10];break;
- case 7:P0=tab[distance%10]; break;
- }
- }
- void xian()
- {
- switch(moshi)
- {
- case 0:xianshi0();break;
- case 1:xianshi1();break;
- }
- }
- void display()
- {
- P0=weixuan[du];
- P2=(P2&0X1F)|0XC0;
- P2=P2&0X1F;
- xian();
- P2=(P2&0X1F)|0XE0;
- P2=P2&0X1F;
- if(++du>7) du=0;
- }
复制代码
超声波_DYH.rar
(100.26 KB, 下载次数: 11)
|