#include <ResponsiveAnalogRead.h>For this project have included "ResponsiveAnalogRead" library.
#define sound_pin 5 //use any ADC pin for sound sensor #define relay_pin 3 //Can use any pin for digital logicHere you can define the pin number where the sensor is attached. Use only ADC pin for sound sensor as we need analog value. Relay can be connected to any pin which will give use digital output.
ResponsiveAnalogRead sound(sound_pin, true);An object 'sound' of class 'ResponsiveAnalogRead' is created here. This has been done so we could access various functions in the 'ResponsiveAnalogRead' library.
void loop() { sound.update(); //current sound value is updated soundValue = sound.getValue(); currentNoiseTime = millis(); Serial.println(soundValue); if (soundValue > threshold) { // if there is currently a noise if ( (currentNoiseTime > lastNoiseTime + 250) && // to debounce a sound occurring in more than a loop cycle as a single noise (lastSoundValue < 400) && // if it was silent before (currentNoiseTime < lastNoiseTime + 750) && // if current clap is less than 0.75 seconds after the first clap (currentNoiseTime > lastLightChange + 1000) // to avoid taking a third clap as part of a pattern ) { relayStatus = !relayStatus; digitalWrite(relay_pin, relayStatus); delay(300); lastLightChange = currentNoiseTime; } lastNoiseTime = currentNoiseTime; } lastSoundValue = sound.getValue(); }This is the algorithm for sensing the only two claps and changing the logic level accordingly. The sound value is stored in the variable 'soundValue'. This is updated every loop.
#include <ResponsiveAnalogRead.h> #define sound_pin 5 #define relay_pin 3 ResponsiveAnalogRead sound(sound_pin, true); int soundData = 0; int threshold = 1000; int lastSoundValue = 0 ; int soundValue; long lastNoiseTime = 0; long currentNoiseTime = 0; long lastLightChange = 0; int relayStatus = HIGH; int data = 0; void setup() { pinMode(relay_pin,OUTPUT); digitalWrite(relay_pin,HIGH); //pinMode(sound_pin,INPUT); Serial.begin(9600); } void loop() { sound.update(); soundValue = sound.getValue(); currentNoiseTime = millis(); Serial.println(soundValue); if (soundValue > threshold) { // if there is currently a noise if ( (currentNoiseTime > lastNoiseTime + 250) && // to debounce a sound occurring in more than a loop cycle as a single noise (lastSoundValue < 400) && // if it was silent before (currentNoiseTime < lastNoiseTime + 750) && // if current clap is less than 0.75 seconds after the first clap (currentNoiseTime > lastLightChange + 1000) // to avoid taking a third clap as part of a pattern ) { relayStatus = !relayStatus; digitalWrite(relay_pin, relayStatus); delay(300); lastLightChange = currentNoiseTime; } lastNoiseTime = currentNoiseTime; } lastSoundValue = sound.getValue(); }