We can’t easily differentiate claps from other short, sharp sounds, such as knocks. Still, you might prefer to make a knocking sound to control it. We are basically trying to detect a sharp increase in volume.
To detect claps, we need to smooth out the waveform to get a signal corresponding to volume (rather than instantaneous amplitude). We use ‘exponential smoothing’ because it is straightforward to implement. Adding an RC (resistor and capacitor) low-pass filter circuit would have the same effect, but we can do exponential smoothing in software without adding any parts.
We then apply some thresholds to distinguish claps from other sounds. We detect the start of a clap when the smoothed value rises above a certain level and its end when the value falls below a different, lower level. This is called hysteresis and is another way to separate claps in a noisy environment.
Once one clap is detected, a timer runs for one second and further claps within that second are counted. Thus, the software can detect multiple claps in close succession. The Leonardo’s onboard LED is also lit while each clap is detected.