可以测当前距离,当超过阈值距离时,蜂蜜器报警,并且实时显示温度数据,51单片机超声波测距C语言程序
制作出来的实物图如下:
源代码资料下载 : www.dzkfw.com.cn/Soft/mcu/92.html
#include#include #define uchar unsigned char #define uint unsigned int int num=0; unsigned char table[]={"0123456789"};//显示的数值 // 1602的引脚定义 sbit RW=P2^5; sbit RS=P2^6; sbit E=P2^7; //报警引脚定义 sbit feng=P2^4; sbit led=P1^2; sbit key1=P1^0; sbit key2=P1^1; int numm=0,nnum=0; void delayms(unsigned int ms) { unsigned char i=100,j; for(;ms;ms--) { while(--i) { j=10; while(--j); } } } bit flag; //温度变量 uint temp; sbit ds=P1^3; //温度引脚 //超声波位定义 sbit Trig = P2^1; sbit Echo = P2^0; uint time=0; unsigned long S=0; bit flagg=0; void delay2(uchar p) { uchar l,k; for(l=p;l>0;l--) for(k=110;k>0;k--); } void delay(uchar z) { while(z--); } //温度初始化函数 void ds_reste() { ds=1; delay(5); ds=0; delay(80); ds=1; delay(14); if(ds==0) //判断ds总线被拉低 flag=1; else flag=0; delay(20); } //读一位字节 bit ds_read_byte() { bit dat; ds=0; _nop_(); _nop_(); ds=1; _nop_(); dat=ds; delay(10); return dat; } //读一位字节 uchar ds_read() { uchar i,j,k; for(i=0;i<8;i++) { j=ds_read_byte(); k=(j<<7)|(k>>1); } return k; } //写入数据 void ds_write(uchar dat) { uchar i; for(i=0;i<8;i++) { ds=0; _nop_(); ds=dat&0x01; delay(6); ds=1; dat=dat>>1; } delay(6); } //读取温度 uint read_temp() { uchar a,b; ds_reste(); ds_write(0xcc); ds_write(0xbe); a=ds_read(); b=ds_read(); temp=b; temp=temp<<8; temp=temp|a; temp=temp*0.0625*10+0.5; return temp; } //写入命令1602 void write_com(uchar com) { RS=0; RW=0; E=0; P0=com; delay2(5); E=1; delay2(5); E=0; } //写入数据 1602 void write_data(uchar date) { RS=1; RW=0; E=0; P0=date; delay2(5); E=1; delay2(5); E=0; } //1602初始化显示 void init() { RS=0; write_com(0x38); write_com(0x0c); write_com(0x06); write_com(0x01); write_com(0x80); } //温度在1602上显示出来 void display(uint tempp) { write_com(0x80+0x0b); write_data(table[tempp/100]); delay2(0); write_com(0x80+0x0c); write_data(table[tempp%100/10]); delay2(0); write_com(0x80+0x0d); write_data('.'); delay2(0); write_com(0x80+0x0e); write_data(table[tempp%100%10]); delay2(0); write_com(0x80+0x0f); write_data('C'); delay2(0); write_com(0x80+0x09); write_data('T'); delay2(0); write_com(0x80+0x0a); write_data(':'); delay2(0); }
全部代码到页面下载 www.dzkfw.com.cn/Soft/mcu/92.html