首页 > 解决方案 > 如何在 arduino 中延迟压电蜂鸣器的声音

问题描述

我正在尝试使用压电蜂鸣器和超声波传感器来实现汽车警告声音。如果物体距离 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);
  }
}

标签: arduinoarduino-uno

解决方案


每次你告诉 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
}

推荐阅读