首页 > 编程知识 正文

超声波模块接51单片机,基于51单片机超声波测距设计

时间:2023-05-06 02:25:02 阅读:40857 作者:951

电路的连接

超声波模块单片机备注VCCVCC电源GNDGND接地EchoP2^0接收信号TrigP2^1发射信号测量范围2—400cm

HCSR04模块有四个引脚、VCC、GND、TRIG和ECHO; 这些管脚有不同的功能。 VCC和GND是HSCR04的直接驱动电源。 这些引脚必须分别连接到5v的电压和接地。 TRIG端子负责发送超声波信号的信号端子。 该引脚需要以超过10us的高电平启动,HCSR04每点发射8只40khz纯真蜻蜓。 的纯真蜻蜓发射后,ECHO引脚输出高电平。 ECHO端子是用于测量距离的数据端子。 一个超声波信号发射后,ECHO引脚输出高电平。 在ECHO端子检测到超声波信号并返回之前,ECHO端子输出低电平。 The HC­SR04 has four pins,VCC,GND, trigandechothesepinsallhavedifferentfunctions.thevccandgndpinsarethesimplesttheypowerthehcsr 04.thesepinsneeedtobeattached tached to tive ly.thereisasinglecontrolpin : thetrigpinisresponsibleforsendingtheultrasonic rst.thispinshouldbesettohigpin atwhichpointthehcsr 04 willsendoutaneightcyclesonicburstat 40k Hz.afterasonicbursthasbeensenttheechopinwillgohigh.thee chop inistat istance measurements.afteranultrasonicburstissentthepinwillgohigh,itwillstayhighuntilanultrasonicburstisdetectedback,at whh

参考代码#include REG52.H/*自定义变量类型*/typedef unsigned char uchar; //0至255 typedef unsigned int uint; //0~65535sbit RX=P2^0; sbit TX=P2^1; Uchar标志; uchar date_distance[5]; uchar kk; /*用于控制数码管的引脚*/sbit LSA=P2^2; sbit LSB=P2^3; sbit LSC=P2^4; uchar LSA _ node1[ ]={ 0,1,0,1,0,1,0,1,0 }; uchar LSB _ node1[ ]={ 0,1,1,0,0,1,1,0,0 }; uchar LSC _ node1[ ]={ 0,1,1,1,0,0,0 }; //共阴数字代码表0-Fuchar SMG[]={0x3f、0x 06、0x5b、0x4f、0x6f、0x7d、0x 07、0x7f、0x7d、0x7d、0x 39,} //延迟1msvoiddelay_ms(uintc )//误差0us ) uinta,b; for (; c0; c----for(b=102; b0; b--) for(a=3; a0; a----; (/)数字代码选择函数(/voidinit_SMG ) ucharI ) { LSA=LSA_NODE1[i]; LSB=LSB_NODE1[i]; LSC=LSC_NODE1[i]; //初始化计时器void init_timer () {TMOD=0x11; //计时器0 1//初始化计时器0 TH0=0x00; TL0=0x00; EA=1; ET0=1; //TR0=1; //初始化计时器1TH1=0xF8; //定时2ms TL1=0xCD; ET1=1; TR1=1; (/)计算距离void count_distance ) )/s=340 m/s * time us/2=170 * time * 10 ^-6m=0.17 * timemmmuintdistance=) th0 //TL0=0; if(distance=4000||distance20 ) /测量范围外为“er r0”{ flag=1; } else { date _ distance [1]=distance 000/1000; date _ distance [2]=distance 00/100; date_distance[3]=distance0/10; date_distance[4]=distance/1; }}void display () {uchar i; if(flag==1) {flag=0; date_distance[1]=14; date_distance[2]=14; date_distance[3]=14; date_distance[4]=14; (for ) I=1; i=4; I ) init_SMG(I ); if(I==1) P0=SMG[date_distance[i]] |0x80; elseP0=SMG[date_distance[i]]; dlay_ms(1; P0=0x00; }}void main () {init_timer ); while(1) {while (! RX; //等待tx发出TR0=1超时while(rx ); //tx输出时,RX为高电平TR0=0; //超时count_distance (); (//计时器0是距离void timer0 ) )中断1 ) flag=1; //计时器1是发送数字管的显示数据和超声波信号的voidtimer1(interrupt3) tr1=0; //结束定时TH1=0xF8; //定时2ms TL1=0xCD; kk; 显示(; 每隔if(kk100 ) 200ms启动超声波模块({kk=0; //启动超声波模块TX=1的dlay_10us(2; TX=0; }TR1=1; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。