/*超声波测距.
P1_7 trig
P3_2 ECHO
*/
#include <AT89X51.H>
#include <intrins.h>
const char LED[]= //定义LED数码管显示数字.常量(不带点)
{0x84, 0xF6, 0x4C, 0x64, 0x36, 0x25, 0x05, 0xF4, 0x04, 0x24};
const char LED_P[]= //定义LED数码管显示数字.常量(带点)
{0x80, 0xF2, 0x48, 0x60, 0x32, 0x21, 0x01, 0xF0, 0x00, 0x20};
char Bai,Shi,Ge;//数码管显示位
unsigned long int JuLi;//距离
unsigned char Gao,Di;//存储计时器高位,低位
void ChuShiHua();//初始化
void FaShe();//发射声波
void Shou();//接收外部中断程序
void XianShi();//扫描扫描程序(计时器中断)
void Deng();//空等待
//主程序------------------------------------------------------
main()
{
ChuShiHua();
while (1)
{
FaShe();
Deng();
}
}
//初始化------------------------------------------------------
void ChuShiHua()
{
IE = 0x88; //开T1中断
TMOD = 0x01; //定时器1模式0,定时器0模式1
PX0 = 1; //INT0高优先级
PT1 = 0; //T1 低级中断
IT0 = 0; //INT0电平触发0
TR1 = 1; //启动定时器1
}
//空等待------------------------------------------------------
void Deng()
{
unsigned int i,j;
for (i = 0; i < 100; i++)
for (j = 0; j < 100; j++);
}
//发射方波----------------------------------------------------
void FaShe()
{
unsigned int counter;
IE = 0; //关中断
TH0 = 0;
TL0 = 0; //计数器清零
TR0 = 1; //启动计算器;
for (counter = 0;counter < 16; )
{
P1 = P1 ^ 0x80;
_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();
counter++;
}
P1_7 = 1;
for (counter = 0;counter < 300; counter++) _nop_();//2.1315
IE = 0x89; //开中断
}
//收,外部中断程序---------------------------------------------
void Shou() interrupt 0 //外部中断INT0
{
IE = 0x00; //关中断
JuLi = 0;
TR0 = 0;
Gao = TH0;
Di = TL0;
JuLi = JuLi | Gao;
JuLi = JuLi << 8;
JuLi = JuLi | Di;
JuLi = JuLi - 44;
JuLi = JuLi * 85;
JuLi = JuLi/10000;
Bai = JuLi / 100;
Shi = (JuLi - (Bai*100))/10;
Ge = JuLi%10;
IE = 0x88; //关int0中断,开显示中断
}
//显示中断程序------------------------------------------------
void XianShi() interrupt 3 //定时器中断1
{
static char xian_shi_wei = 0; //显示位
TH1 = TL1 = 0;
if (xian_shi_wei >= 3)
xian_shi_wei = 0;
P0 = 0xFF; //全关了
switch (xian_shi_wei) //开下一个
{
case 0:
P0_2 = 0;
P2 = LED_P[Bai];
break;
case 1:
P0_1 = 0;
P2 = LED[Shi];
break;
case 2:
P0_0 = 0;
P2 = LED[Ge];
break;
}
xian_shi_wei++;
}
//------------------------------------------------------------