声控灯

用arduino实现的声控灯。有两种实现方式,一种是在死循环里不断检测声音,然后做相应处理,一种是使用中断,也就是事件触发机制。这两种的差别就是同步和异步的差别,同步是排队,异步是叫号。

我是用中断实现的,代码如下:

 1 /*
 2  *auther Siriuslzx
 3  */
 4 const byte ledPin = 13;
 5 //arduino支持中断的端口只有1和2
 6 const byte interruptPin = 2;
 7 //易变,适合用于传感器值
 8 volatile byte sensorVal = HIGH;
 9 
10 void setup() {
11   pinMode(ledPin, OUTPUT);
12   digitalWrite(ledPin, LOW);
13   //上拉电阻,在没有检测到输入时为高电平
14   pinMode(interruptPin, INPUT_PULLUP);
15   //外部中断,用来实现事件触发机制
16   attachInterrupt(digitalPinToInterrupt(interruptPin), read, CHANGE);
17 }
18 
19 void loop() {
20   //检测到声音时亮灯2s,自动关闭
21   if (sensorVal == LOW) {
22     digitalWrite(ledPin, HIGH);
23     delay(2000);
24     digitalWrite(ledPin, LOW);
25   }
26 }
27 
28 void read() {
29   sensorVal = digitalRead(interruptPin);
30 }

效果如下:http://www.bilibili.com/video/av17234605/

原文地址:https://www.cnblogs.com/lzxskjo/p/8035250.html