ds18b20程序 lm386 超声波测距
//超声波测距
#include <reg52.h>
#include "display.h"//共阳数码管
//只能236mm~1m的距离,再远就会显示错误的数值.
sbit csbout=P1^0; sbit csbint=P1^1; uchar cl; uint shu;
void CSB_init() { TMOD=0x11;//T0记路程时间 计数器,T1记每五百毫秒的显示时间 定时器 TH0=0; TL0=0; TH1=(65536-50000)/256; TH1=(65536-50000)%256; EA=1; ET1=1; TR1=1; }
uint csbcj() { uint i,t; uint m,num; TR1=0; TH0=0;//非常重要,否则定时器0不清0; TL0=0; TH1=(65536-50000)/256; TH1=(65536-50000)%256; TR0=1;//开始计数 时间 i=20;//10脉冲超声波 while(i--) csbout=!csbout; i=150;//延时1.5~2毫秒,防止发送的超声波拐弯到接收端 while(i--); while(csbint);//判断是否接到超声波的回波
{ m++; if(m>=2500)//如果过一段时间没收到回波,则将其置0 csbint=0; } TR0=0;//关闭计数器 t=TH0; t=t*256+TL0; num=(uint)t*0.172;//精确到毫秒 TR1=1;//在进行下一个500毫秒的计时 return num; }
void main() { CSB_init(); while(1) { if(cl==20)//1秒一刷新 { cl=0; shu=csbcj(); } display(shu); } }
void timer1() interrupt 3 { TH1=(65536-50000)/256; TL1=(65536-50000)%256; cl++; }