0

对于学校,我正在用我的 arduino nano 制作拍手传感器。我找到了一些代码来检测是否有 2 个拍手(链接)。但现在我想修改代码,以便区分我是拍了 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;


    }
4

1 回答 1

0

Try this snippet:

    #define signalToRelayPin              12
    #define sensorPin                      7

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

    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 && lastSoundValue == 0) 
    { 
        if (claps == 0) // allow first to register without much condition
        {
            claps = 1;
            lastNoiseTime = currentNoiseTime;
        }
        else
        {
            if (currentNoiseTime > lastNoiseTime + clap_interval)
            {
                claps++;
                lastNoiseTime = currentNoiseTime;
                            relayStatus = !relayStatus;
            }
        }           
    }
    else
    {
        if (currentNoiseTime > lastNoiseTime + 2 * clap_interval) // no claps for a longer duration time to print and/or reset clap
        {
            if (claps > 0)
            {
                Serial.print(claps);
                Serial.println(" CLAPS");
                claps = 0; ///reset
            }
        }
    }

    //lastSoundValue = soundValue;
    delay(50); // delay polling
}
于 2018-10-07T14:45:18.987 回答