聲音感測模組測試可以到
http://yhhuang1966.blogspot.com/2017/10/arduino.html
以下是我改編過的拍手兩次..原版似乎不太準(Using Arduino IDE)
請在自行修正參數
請在自行修正參數
#define ledPin 2
boolean ledState = false; //紀錄 LED 狀態,預設為打開
int micVal; //紀錄偵測到的音量
long current = 0; //紀錄目前過門檻時戳
long last = 0; //紀錄上次過門檻時戳
long diff = 0; //紀錄前後兩次時間差
int count = 0; //紀錄已偵測到的次數
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
if (analogRead(micPin) > 2000) { //若超過門檻值
delay(50);
if (analogRead(micPin) > 2000 ) {
Serial.println(analogRead(micPin));
current = millis(); //紀錄目前時戳
count++; //次數
}
if (analogRead(micPin) > 2000 && count >= 2) { //若次數已達 2 次
diff = current - last; //計算前後兩次時間差
Serial.println("disdance="+String(diff));
if (diff > 300 && diff < 1500) {
Serial.println("change");
ledState = !ledState;
count = 0;
} else {
count = 1; //太久或太慢
}
}
last = current; //以目前時戳更新上次時戳
if (ledState) {
digitalWrite(ledPin, HIGH);
}else {
digitalWrite(ledPin, LOW);
}
}
delay(50);
}
沒有留言:
張貼留言