Single and double clap switch

Hey all.
I'm trying to build a clap switch that will detect both single and double claps.
The single claps would trigger one type of load and double claps another type of load.

The logic to do this is the problem.
I have this code that responds to and activates the load for single clap but the double clap triggers both loads.
Can someone help me out please.

I guess they are still working on the code tags because it doesn't work for now.
I'll just put it below.

    int reading = 0;
    int mic = A2;
    int led = 12;
    int led2 = 13;
    boolean ledOn = 0;
    boolean ledOn2 = 0;
    boolean flag;
    int iChecker =0;
     
    void setup(){
      pinMode(mic, INPUT);
      pinMode(led, OUTPUT);
      pinMode(led2, OUTPUT);
    }

    void loop(){
      reading = analogRead(mic);
    
       if (reading > 100){
    iChecker = 0;
    //flag = false;
    delay(200);
    for (int i = 0; i < 1000; i++){
      reading = analogRead(mic);
      delay(1);
      if (reading > 100){
        ledOn = !ledOn;
        //flag = true;
        iChecker = 3;
        break;
      }
    }

    if (iChecker != 3){
        ledOn2 = !ledOn2;
        //break;
      }
  }

  if (ledOn == 1){
    digitalWrite(led, HIGH);
  }
  else{
    digitalWrite(led, LOW);
  }

  if (ledOn2 == 1){
    digitalWrite(led2, HIGH);
  }
  else{
    digitalWrite(led2, LOW);
  }
}

Hey all.
Some help here please.

Hi please.
It may seem this post is being skipped over or not displayed to the public.

Your cross post has been deleted and this one has been moved here to the Programming section

1 Like

Alright, thanks.
I'm glad it's being seen now.

Hi Ben,

You have a first detection of sound = a clap
then you do a delay(200)

and then starts the for-loop that detects the second clap

you toggle your variable ledOn inside the loop for that shall detect the second clap

so this is what your program does

I did a quick googling and found this video which is pretty the same code as you have

Anyway you have been impatient about getting answers. Even writing pesonal messages. What you always can do until answers are posted is analysing your own code through serial output at a high baudrate of 115200 baud

void setup() {

Serial.begin(115200);
Serial.println("Setup-Start");

an then add
Serial.print(....

at places to printout with whatever you like to see while your program gets executed

best regards Stefan

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.