[英]Ultrasonic sensor with Arduino
我是学生,我的英语不太好。但是,我有一个问题,我认为你可以解决这个问题我正在通过超声波传感器制作一个带有 LED 和扬声器的电路。 但是我应该怎么做才能让声音在一定距离内发出一次,并在我从一定距离回来时再次发出声音? 拜托我需要你的帮忙...
那是我的电路
int distance = 0;
int i = 0;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // clear thr trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH status for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads thr echo Pin, and returns the sound wave
return pulseIn(echoPin, HIGH);
}
void setup()
{
pinMode(11, OUTPUT);
distance = 0.01723 * readUltrasonicDistance(5,4);
if (distance > 40) {
noTone(11);
}
delay(1000); // Wait for 1000 millisecond(s)
}
void loop()
{ distance = 0.01723 * readUltrasonicDistance(5,4);
if (distance < 40) {
tone(11,523,500); // play tone 60
delay(1000); // wait for 1000 millisecond(s)
}
}
您可以尝试使用一个变量来指定是否达到了一次距离。 并重置变量只有id距离很远。 并使用该变量播放一次声音并更新变量。
bool came = false;
void setup(){
//remaining stuff here
}
void loop()
{ distance = 0.01723 * readUltrasonicDistance(5,4);
if (distance < 40 && !came) {
//tone code here
came = true;
}
if (distance >= 40) {
come = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.