可以測當前距離,當超過閾值距離時,蜂蜜器報警,並且實時顯示溫度數據,51單片機超聲波測距C語言程序
製作出來的實物圖如下:
源代碼資料下載 : www.fpxing.com/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.fpxing.com/Soft/mcu/92.html