I am trying to code a servo that is controlled by a sound sensor. Essentially if it is at 180 degrees and hears the sound it should go to zero and if it is at zero degrees and hears the sound it should go to 180. I have some code but when the sound is received the servo doesn't move.
#include <Servo.h>
Servo s;
int pos = 0;
int soundpin = A2;
int threshold = 200;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(soundpin, INPUT);
s.attach(2);
s.write(100);
}
void loop() {
// put your main code here, to run repeatedly:
int sens = analogRead(soundpin);
s.write(180);
if(sens>=threshold && pos == 180){
s.write(0);
delay(15);
}else if (sens>=threshold && pos == 0){
s.write(180);
delay(15);
}
}
#include <Servo.h>
Servo s;
int pos = 0;
int soundpin = A2;
int threshold = 200;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(soundpin, INPUT);
s.attach(2);
s.write(0);
}
void loop() {
// put your main code here, to run repeatedly:
int sens = analogRead(soundpin);
//s.write(180);
if(sens>=threshold && s.read() == 180){
s.write(0);
delay(15);
}else if (sens>=threshold && s.read() == 0){
s.write(180);
delay(15);
}
}