I'm trying to code the pan and tilt bracket to turn based on where I speak, I know how to move the servo motors, but I really need help with the sound sensing. This is the code I've got currently:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
Servo myservo2; // a maximum of eight servo objects can be created
int sound1;
int sound2;
int pos = 0; // variable to store the servo position
void setup()
{
Serial.begin(9600);
myservo.attach(5); // attaches the servo on pin 9 to the servo object
myservo2.attach(6);
}
void loop()
{
sound1 = analogRead(A0);
sound2 = digitalRead(7);
if (sound1 > 50)
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
if (sound2 > 50)
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo2.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo2.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
I've been working on this for some time, but for some reason, whenever I try to code the sound sensor, it always ends up being ignored, so for example, If my code says, if sound sensor number 1 detects sound, move 90 degrees vertically or horizontally, it always ignores that if statement and just continuously moves 90 degrees to wherever. I need it to follow my voice, or if that's too advanced, it's fine if it just follows any sound. So if I more 30 degree to the right on the pan and tilt bracket, and speak, I need it to turn and face me. Also, the kind of sound sensor I'm using is KY-037, the red variation with 4 pins. Any advice would be really helpful, thanks.
digitalRead()
forsound2
? It will return only 0 or 1. Soif(sound2 > 50)
will never be true. Also currently your code tells the servo to move 180 degrees back and forth. Nothing with 90° or following you. What sound sensors do you have? I don't quite understand what you want to achieve. Do you want the servos to follow you linearily (so for example moving to 30° when you talk from 30°)? Or do you want it to change between 2 positions? What should happen if both sensors detect a loud enough sound?