所用元件:
1、Arduino 2012 UNO R3开发板
2、超声波模块:HC-SR04
3、LED \ 蜂鸣器
功能:
- 输出测距信息至串口
- 距离20CM 蜂鸣器开始报警,LED闪烁
- 20CM 到 3CM 间 报警音不断急促,3CM内报警音长鸣,LED长亮
代码:
1 int beeppin = 8; 2 int ledpin=9; 3 int echo= 6; 4 int trig=7; 5 unsigned long time_echo=0; // record the pulse width by sensor returns 6 unsigned long distance =0; // record the distance value; 7 8 void setup(){ 9 Serial.begin(9600); 10 pinMode(beeppin,OUTPUT); 11 pinMode(ledpin,OUTPUT); 12 pinMode(echo,INPUT); 13 pinMode(trig,OUTPUT); 14 } 15 16 void loop(){ 17 digitalWrite(trig,HIGH); //send pulse 18 delayMicroseconds(80); //set pulse width with 50us(>10us) 19 digitalWrite(trig,LOW); //stop send 20 21 time_echo = pulseIn(echo,HIGH); //get return pulse width 22 if((time_echo<60000)&&(time_echo>1)) //valid scope 1-60000 23 { 24 distance = (time_echo*34/100)/2; //mm 25 if(distance < 200) 26 { 27 if(distance<30){ 28 digitalWrite(beeppin,HIGH); 29 digitalWrite(ledpin,HIGH); 30 }else{ 31 alert(distance/2); 32 } 33 } 34 Serial.print(distance,DEC); 35 Serial.println('\n'); 36 37 } 38 delay(100); 39 } 40 void alert(unsigned i){ 41 digitalWrite(beeppin,HIGH); 42 digitalWrite(ledpin,HIGH); 43 delay(i); 44 digitalWrite(beeppin,LOW); 45 digitalWrite(ledpin,LOW); 46 delay(i); 47 }