Here is a "stripped down version" of a sketch I used to replicate the Clap On, Clap Off lamp switch we had in the 1980's. It works with the KY-038 sound sensor module you currently have. You will need to install the [VirtualDelay][1] Library.
EDIT: To answer your question regarding the multiple High to Low transitions from the module's digital output, you can use a DSO to look at the relationship between the analog and digital signals it produces.
In the following image, the digital signal (yellow trace) and the analog signal (blue trace) are superimposed over each other. The white dashed line (E), is set to 2.8 VDC which is approximately the analog output pin's voltage with ambient room noise. Once you clap in front of the microphone, this wave form is generated.
[![enter image description here][2]][2]
The entire clap lasts about 5.6 ms and the module gives you 18 High to Low transitions on it's digital output pin. When the analog voltage drops below a certain voltage, the digital output goes High. When the analog voltage goes above that voltage, the digital output goes Low.
The problem is, the sound of a person clapping generates a noisy signal and the sound sensor module does not know the difference between noise and the sound you want to trigger it.
Instead of using delay()
like I did, you could increment a "clap counter" to equal "1" on the first Low to High transition of the digital output pin. Next, start a non-blocking millis()
timer that waits before you read the digital output pin again. If digital out is High after 400 ms, it's your second clap so change the LED state. A second millis()
timer could reset the "clap counter" to 0 after 1 second.
[1]: https://github.com/avandalen/VirtualDelay
[2]: https://i.sstatic.net/XvJt8.png