Go Down

Topic: Clap clap toggle - getting clap duration (Read 402 times) previous topic - next topic

--Smigol--

First of all - nice to meet you all guys, I'm a new user on this forum and a new user to arduino.

I'm trying to toggle a led (called SWITCH in the sketch) using a microphone i bought, that outputs LOW when receiving a sound, and HIGH when it's not. I can change it's sensitivity using a potentiometer.

My problem is that the code doesn't work well - it doesn't calculate the duration of the clap sound well. I suppose it's an error with the while() use logic.

Here's the code:

Code: [Select]
#define MIC 12
#define SWITCH 11
unsigned long time[3], temp;

void setup(){
  Serial.begin(9600);
  pinMode(MIC, INPUT);
  pinMode(SWITCH, OUTPUT);
  digitalWrite(SWITCH, LOW);
}

void loop(){
  if(!digitalRead(MIC)){
    temp=millis();
    while(!digitalRead(MIC)){}
    time[0]= millis()-temp;
    Serial.print("Time0: ");
    Serial.println(time[0]);
    temp = millis();

    if(time[0]<10){
      while(digitalRead(MIC)){}
      time[1] = millis()-temp;
      Serial.print("Time1: ");
      Serial.println(time[1]);
      temp = millis();

      if((time[1]>150) && (time[1]<600)){
        while(!digitalRead(MIC)){}
        time[2] = millis()-temp;
        Serial.print("Time2: ");
        Serial.println(time[2]);
        if(time[2]<10){
          digitalWrite(SWITCH, !digitalRead(SWITCH));
          Serial.println("TOGGLE SWITCH");
        }else{
          Serial.println("TIME2 TOO HIGH");
        }
      }else{
        Serial.println("TIME1 TOO HIGH or TOO LOW");
      }
    }else{
      Serial.println("TIME0 TOO HIGH");
    }
  }
}


And here a sample serial output:
Code: [Select]
Time0: 0
Time1: 0
TIME1 TOO HIGH or TOO LOW
Time0: 0
Time1: 0
TIME1 TOO HIGH or TOO LOW
Time0: 3
Time1: 0
TIME1 TOO HIGH or TOO LOW
Time0: 0
Time1: 0
TIME1 TOO HIGH or TOO LOW


Sometimes the LED does toggle, but usually it doesn't.


PaulS

Why are you attempting to re-implement the pulseIn() function?
The art of getting good answers lies in asking good questions.

Blue Eyes

It seems like you would have to have amazing timing on your claps to light the LED.  I recommend that you change each if statement that checks the time array to not check and just flow right through like this:

Code: [Select]
if( true /*time[0]<10*/  ){

This way you will see what values are printed out for each clap, the numbers might be  different than you expect.


Go Up