振动报警器
Language | English |
---|
目的做一个震动报警器,当有震动时,蜂鸣器循环发出两次报警音频。 原理震动传感器检测是否发生震动,检测到有震动时控制蜂鸣器发出报警音。 设备
准备
调试
#define pushButton 4
#define speakPin 6
int pushState;
long time, timer;
boolean shock;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(115200);
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
pinMode(speakPin, OUTPUT);
}
void loop() {
if (digitalRead(pushButton))
shock = true;
if (millis() - time > 2000)
{
if (!digitalRead(pushButton))
shock = false;
time = millis();
}
// Serial.println(shock);
if (shock)
{
for (int j = 0; j < 2; j++)
buzzer();
}
else
noTone(speakPin);
}
void buzzer()
{
for (int i = 200; i <= 800; i++)
{
tone(speakPin, i);
delay(5);
}
delay(1000);
for (int i = 800; i >= 200; i--)
{
tone(speakPin, i);
delay(10);
}
}
软件调试
#define pushButton 4 //震动
#define speakPin 6 //蜂鸣器
if (millis() - time > 2000)
{
if (!digitalRead(pushButton))
shock = false;
time = millis();
}
if (shock)
{
for (int j = 0; j < 2; j++)
buzzer();
}
else
noTone(speakPin);
结果当敲击震动传感器,蜂鸣器循环两次报警,循环之后没有震动时则停止。你也可以通过乐高搭建一个漂亮的外观。 视频 |