使用拍手传感器(arduino nano)检测多个拍手

时间:2018-10-07 13:54:55

标签: c++ arduino sensor clap

在学校里,我正在用arduino nano制造鼓掌传感器。我找到了一些代码来检测是否有2个拍手(link)。但是现在我想修改代码,以便区分我拍过1,2或3次。现在,我将源更改为检测1或2个拍手。但是现在如果我拍手两次,在看到2个拍手之前,总会检测到一个拍手。而且我完全不知道如何检测3个拍手。有人可以帮我解决这个问题吗?

代码:

    #define signalToRelayPin              12
    #define sensorPin                      7

    int lastSoundValue;
    int soundValue;
    long lastNoiseTime = 0;
    long currentNoiseTime = 0;
    long lastLightChange = 0;
    int relayStatus = HIGH;

    void setup() {
      pinMode(sensorPin, INPUT);
      pinMode(signalToRelayPin, OUTPUT);
      Serial.begin(115200);
    }

    struct DataBlockStruct  meting1,meting2;

    void loop() {

      soundValue = digitalRead(sensorPin);
      currentNoiseTime = millis();

      if (soundValue == 1) { // if there is currently a noise
        if (
          (currentNoiseTime > lastNoiseTime + 200) && // to debounce a sound occurring in more than a loop cycle as a single noise
          (lastSoundValue == 0) &&  // if it was silent before
          (currentNoiseTime < lastNoiseTime + 800) && // if current clap is less than 0.8 seconds after the first clap
          (currentNoiseTime > lastLightChange + 1000) // to avoid taking a third clap as part of a pattern
        ) {

          relayStatus = !relayStatus;
          Serial.println("2 X CLAP");

         } else {    
          Serial.println("1 X CLAP");
          }

         lastNoiseTime = currentNoiseTime;
      }

      lastSoundValue = soundValue;


    }

1 个答案:

答案 0 :(得分:0)

尝试以下代码段:

UI