arduino - 如何在 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);
}
}
解决方案
每次你告诉 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
}
推荐阅读
- javascript - Docusign ifra 完成事件捕获
- php - Laravel 查询/访问数据库信息
- python - discord.py 中的歌词命令
- r - 是否有 R 代码用 0 替换空单元格,但保留填充单元格的原始值?
- android - Android DataBinding / BindingAdapter 错误:{缺少返回语句}
- amazon-s3 - 在 S3 中的现有 ORC 文件上使用 Presto
- json - 将 CityGML 模型转换为 CityJson 文件
- firebase - 如何更改firebase颤动中数组字段的值?
- java - org.springframework.beans.factory.UnsatisfiedDependencyException Springboot
- java - Vaadin 7 中的外部脚本 (CORS) 问题