My son is working on a school project and he wants to use two servos connected to two separate buttons, all on one arduino.
The code he is using is below. The problem is that when any button is pressed both servos move. Can someone please tell me what he did wrong with the code?
#include <Servo.h>
Servo myServo;
Servo myServo2;
int buttonState;
int buttonState2;
void setup() {
Serial.begin(9600);
myServo.attach(3);
myServo2.attach(5);
}
void loop() {
buttonState = analogRead(A0);
if (buttonState == LOW){
myServo.write(90);
}
else{
myServo.write(0);
}
buttonState2 = analogRead(A2);
if (buttonState2 == LOW){
myServo2.write(90);
}
else{
myServo2.write(0);
}
}
system
March 7, 2019, 3:10pm
2
I would be very inclined to pinMode the button pins as INPUT_PULLUP, and do digitalRead()s not analog.
system
March 7, 2019, 3:17pm
3
My thinking, btw, is that analogRed() gives us back a number from 0 to 1023. You're looking for a low, that's a 0. So if the tiniest bit of interference lifts the analogRead() off 0, you won't be reading a low.
Not saying my thinking is infallible, though
So something like this using pins 2 and 4 for the button for example.
#include <Servo.h>
Servo myServo;
Servo myServo2;
byte buttonPin = 2;
byte buttonState;
byte buttonPin2 = 4;
byte buttonState2;
void setup() {
Serial.begin(9600);
myServo.attach(3);
myServo2.attach(5);
pinMode (buttonPin, INPUT_PULLUP);
pinMode (buttonPin2, INPUT_PULLUP);
}
void loop() {
buttonState = digitalRead (buttonPin);
if (buttonState == LOW) {
myServo.write(90);
}
else {
myServo.write(0);
}
buttonState2 = digitalRead (buttonPin2);
if (buttonState2 == LOW) {
myServo2.write(90);
}
else {
myServo2.write(0);
}
}
Robin2
March 7, 2019, 4:47pm
5
I suspect the problem is the two ELSE clauses. They do not distinguish between which button is not pressed.
Try it like this
if (buttonState == LOW) {
myServo.write(90);
}
else if (buttonState == HIGH) {
myServo.write(0);
}
And maybe the ELSE is not actually needed - just another IF
...R