Hi guys. A little background: I'm making a project to turn the lights on and off by clapping.
Goal: By clapping twice, my objective is to turn a led on and at the same time move a micro servo. I'm trying to turn the lights on and off by clapping.
Problem: I have managed to write a code that would turn the LED on, however by adding the servo code, it doesnt work anymore. I need help. Thanks in advance.
#include <Servo.h>
#define micpin A0 //Analog Output
#define led 12 //Led
#define sctrl 9 //Servo control
int sdelay = 10; //Servo delay
Servo myservo;
int pos = 0; //Initial position of servo
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT); //Pin LED(11) as an output
myservo.attach(sctrl); // attaches the servo on sctrl(pin 6) to the servo object
}
void loop() {
int sensorvalue = 0;
static bool ledstate = true; //Control the initial LED status: if true, LED is off. Else, LED is on.
sensorvalue = analogRead(micpin); //Analog value
Serial.println(sensorvalue);
if (sensorvalue > 550) { // The sound sensor initial value is around 540. A clap can create an impulse around 550 and above.
delay(250);
for (int i = 0; i < 500; i++) { //wait for the 2nd clap
sensorvalue = analogRead(micpin);
delay(1);
if (sensorvalue > 550) {
ledstate = !ledstate; // break from the code if the 2nd clap is louder than the threshold
break;
}
}
}
if (ledstate) {
digitalWrite(led, LOW);
//--------------Added this for part for the servo-----------//
for (pos = 104; pos <= 180; pos++) {
myservo.write(pos);
delay(sdelay);
}
for (pos = 180; pos >= 104; pos--) {
myservo.write(pos);
delay(sdelay);
}
//--------------Added this for part for the servo-----------//
}
else {
digitalWrite(led, HIGH);
//--------------Added this for part for the servo-----------//
for (pos = 104; pos >= 27; pos--) {
myservo.write(pos);
delay(sdelay);
}
for (pos = 27; pos <= 104; pos++) {
myservo.write(pos);
delay(sdelay);
}
//-------------Added this for part for the servo-------------//
}
}
Note: I mentioned the servo code at the bottom that is causing for the code not to work. Does anyone know how to fix it? Thank you.
DoubleClapSwitch.ino (2.26 KB)