Controlling a servo with a sound sensor

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);
  }
}

Every time through loop() the servo is unconditionally commanded to move to 180 degrees

Why ?

Hello zachfinger

Try this:

pos 

to

s.read()==180; below s.read()==0;

Awesome that solved it thank you!

1 Like

Please post the working code in a new post and mark the topic solved

#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);
  }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.