// https://wokwi.com/projects/423250666579251201
# include <Servo.h>
const byte clapButton = 7; // clap! button
Servo myServo; // Create a servo object
const int soundSensorPin = A0;
const int servoPin = 9;
int soundLevel = 0;
int previousSoundLevel = 0;
int clapThreshold = 50;
int clapCount = 0;
//...
int servoPosition = 90;
const int servoDeviation = 30; //.. something we can see!
bool direction = true;
unsigned long lastClapTime = 0;
unsigned long clapInterval = 1000;
bool servoMoved = false;
void setup() {
Serial.begin(9600);
pinMode(clapButton, INPUT_PULLUP);
myServo.attach(servoPin);
myServo.write(servoPosition);
delay(100); //... life too short
}
void loop() {
soundLevel = analogRead(soundSensorPin);
//... you can if you need to Serial.println(soundLevel);
//... detect a clap served in on the button
static bool lastButton;
static bool aButtonClap;
bool gotClapped = false;
aButtonClap = digitalRead(clapButton) == LOW;
if (aButtonClap != lastButton) {
gotClapped = aButtonClap;
lastButton = aButtonClap;
if (gotClapped) Serial.println(" CLAP!");
}
// if (abs(soundLevel - previousSoundLevel) > clapThreshold) {
if (gotClapped) {
gotClapped = false;
unsigned long currentTime = millis();
//... the first clap... doesn't need to check time!
if (!clapCount) {
clapCount = 1;
// Serial.print("clap now "); Serial.println(clapCount);
}
else if (currentTime - lastClapTime < clapInterval) {
clapCount++;
// Serial.print("clap now "); Serial.println(clapCount);
}
//... else clapCount = 0; ???
Serial.print("clap now "); Serial.println(clapCount);
previousSoundLevel = soundLevel;
lastClapTime = currentTime;
}
if (clapCount >= 2 && !servoMoved) {
if (direction) {
myServo.write(servoPosition + servoDeviation);
delay(500);
myServo.write(servoPosition);
} else {
myServo.write(servoPosition - servoDeviation);
delay(500);
myServo.write(servoPosition);
}
direction = !direction;
clapCount = 0;
servoMoved = true;
}
if (servoMoved && (millis() - lastClapTime) > clapInterval) {
servoMoved = false;
}
delay(50);
}