40
}
//==========================================================
void keysacn()
{
int val;
val=digitalRead(key);// Reads the button ,the level value assigns to val
while(digitalRead(key))// When the button is not pressed
{
val=digitalRead(key);
}
while(!digitalRead(key))// When the button is pressed
{
delay(10);
//delay 10ms
val=digitalRead(key);// Reads the button ,the level value assigns to val
if(val==LOW) //Double check the button is pressed
{
digitalWrite(beep,LOW);//The buzzer sounds
delay(50);//delay 50ms
while(!digitalRead(key)) //Determine if the button is released or not
digitalWrite(beep,HIGH);//mute
}
else
digitalWrite(beep,HIGH);//mute
}
}
void Distance_test() // Measuring front distance
{
digitalWrite(Trig, LOW); // set trig port low level for 2
μ
s
delayMicroseconds(2);
digitalWrite(Trig, HIGH); // set trig port high level for 10
μ
s(at least 10
μ
s)
delayMicroseconds(10);
digitalWrite(Trig, LOW); // set trig port low level
float Fdistance = pulseIn(Echo, HIGH); // Read echo port high level time(unit:
μ
s)
Fdistance= Fdistance/58; // Distance(m) =(time(s) * 344(m/s)) / 2 /****** The
speed of sound is 344m/s.*******/
// ==> 2*Distance(cm) = time(
μ
s) * 0.0344(cm/
μ
s)
// ==> Distance(cm) = time(
μ
s) * 0.0172 = time(
μ
s) / 58
Serial.print("Distance:"); //Output Distance(cm)
Serial.println(Fdistance); //display distance
Distance = Fdistance;
}
/*main loop*/
void loop()
{
keysacn();//Press the button to start
while(1)
{
Distance_test();// Measuring front distance
if(Distance < 25)//The value is the distance that meets the obstacle, and can be set
according to the actual situation
{