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.
shows the Arduino Serial Plotter debugging data. The orange trace is the smoothed volume signal; each peak corresponds to what is seen in Scope 1. The green trace shows the claps being detected, while the yellow spike shows the one-second counter expiring, having detected two claps (indicated by the peak reaching 200 on the vertical scale).
Note how the smaller orange peaks are ignored. The other two traces ensure that the plotter maintains a useful range.