Coding a clap switch with a timer between claps
Now, we will add a timer to limit the waiting timeframe between the first and second claps:
- Define two new variables, both of the
unsigned long
type, to store the time of each clap. The changes to the previous sketch are highlighted:const int MicAnalogPin = 0; const int LedDigitalPin = PC13; const int ClapThreshold = 300; int ClapNumber = 0; bool LedState = false; unsigned long FirstClapEvent = 0; unsigned long SecondClapEvent = 0;
These two highlighted variables will store the milliseconds when a clap is detected: one for the first time and another for the second time.
- The
setup()
section remains unchanged, and we will continue to theloop()
section to introduce the timer changes. We will add a conditional inside the conditional sentence for detecting a clap:void loop() { Â Â int SoundValue = analogRead(MicAnalogPin);Â Â Â Â if (SoundValue > ClapThreshold) { Â Â Â Â ClapNumber...