I am trying to use two momentary contact switches to control the position of a servo.
I want the servo to rest at zero degrees. When I press Sw1 it should go to ninety degrees. When the button is released it should go back to zero degrees.
When I press Sw2 it should go to 160 degrees. When the button is released it should go back to zero degrees.
I have coded the Arduino and Sw1 will do as programmed individually if I "comment out" the code related to Sw2. Sw2 will do as programmed individually if I "comment out" the code related to Sw1. but if I leave both sets of code in, the servo just shutters without moving to either position. This one set of my code wherein I used the button library.
I can not figure out why it is happening I am very new to programming so I am wondering if it is a hardware problem. I have an Arduino Uno and I have 10K resistors on both inputs. The servo has its own battery and I have tied the battery ground to the Arduino ground.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 0; // variable to store the servo position
const int buttonPin = 2; // the number of the pushbutton pin
const int buttonPin2 = 4; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonState2 = 0; // variable for reading the pushbutton status
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
// initialize the LED pin as an output:
myservo.writeMicroseconds(1500); // set servo to mid-point
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
pinMode(buttonPin2, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
//myservo.write (170);
myservo.writeMicroseconds(600); // set servo to mid-point
}
else {
myservo.writeMicroseconds(1500); // set servo to mid-point
//myservo.write (10);
// turn LED off:
digitalWrite(ledPin, LOW);
}
{
// read the state of the pushbutton value:
buttonState2 = digitalRead(buttonPin2);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState2 == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
//myservo.write (170);
myservo.writeMicroseconds(2300); // set servo to mid-point
}
else {
myservo.writeMicroseconds(1500); // set servo to mid-point
//myservo.write (10);
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
}