我正在尝试使用压电蜂鸣器和超声波传感器来发出汽车警告声音,如果物体在50到30厘米之间,它将发出1秒钟的声音并尝试将声音关闭1秒钟,但是我想不出一种实现此代码的方法。你能帮助我吗?这是我的代码。
#define echoPin 4
#define trigPin 3
#define buzPin 5
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzPin, OUTPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
digitalWrite(echoPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
unsigned long duration = pulseIn(echoPin, HIGH);
float distance = ((float)(340 * duration) / 10000) / 2;
Serial.print(distance);
Serial.println("cm");
if (distance <= 50 && distance > 31)
{
tone(buzPin, 391, 1000);
}
else if (distance <= 30 && distance > 21)
{
tone(buzPin, 391, 500);
}
else if (distance <= 20 && distance > 11)
{
tone(buzPin, 391, 100);
}
else if (distance <= 10)
{
tone(buzPin, 391);
}
else {
noTone(buzPin);
}
}
答案 0 :(得分:0)
每次您告诉arduino开始发出声音(这是tone()命令)后,都会增加一些延迟。为此,请按照以下说明操作:
//code
if(statement)
{
tone(buzPin, 391, 500);
delay(x); //x=with the delay you want the buzzer to sound in ms
noTone(buzPin); //after that the sound stops
delay(y); //y=with the delay you want the buzzer to be silent in ms
}