/* ============================================
code is placed under the MIT license
Copyright (c) 2025 J-M-L
For the Arduino Forum : https://forum.arduino.cc/u/j-m-l
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/
#include <Servo.h>
Servo myServo; // Create a servo object
const byte soundSensorPin = A0;
const byte servoPin = 9;
const int clapThreshold = 900;
const unsigned long clapInterval = 1000;
const unsigned long servoInterval = 500;
const int servoPosition = 90;
int deltaPos = 50; // should be 5° but 50° is more visible
unsigned long t0;
enum {IDLE, FIRST_CLAP, ACTION} state = IDLE;
bool clapDetected() {
static bool previousClapDetected = false;
bool clapDetected = analogRead(soundSensorPin) >= clapThreshold;
if (not previousClapDetected && clapDetected) {
previousClapDetected = true;
return true;
}
previousClapDetected = clapDetected;
return false;
}
void setup() {
Serial.begin(115200);
myServo.attach(servoPin);
myServo.write(servoPosition);
}
void loop() {
switch (state) {
case IDLE:
if (clapDetected()) {
t0 = millis();
state = FIRST_CLAP;
}
break;
case FIRST_CLAP:
if (clapDetected()) {
t0 = millis();
myServo.write(servoPosition + deltaPos);
state = ACTION;
} else if (millis() - t0 >= clapInterval) state = IDLE;
break;
case ACTION:
if (millis() - t0 >= servoInterval) {
myServo.write(servoPosition);
deltaPos = -deltaPos;
state = IDLE;
}
break;
}
}