Author Options:

Arduino coding help! Buttons, switches, and servos are not agreeing. Answered

Hi my name is Nash and I've been playing with Arduino Duemilanove for about a year and just touching a little bit of everything. Right now I'm have the Arduino powering basically a pan/tilt device that rotates horizontally 360 degrees and vertically 90 degrees. Using a specific code containing one button, I can have the Arduino run a sequence of the two servos. I would like to add a second button and have a switch to choose "modes." If the switch is OFF, then pushing one button will run the sequence- simple enough. When the switch is ON, I would like the same button as before as well as an additional button control rotation of the horizontal servo. I have the code using only one button and no switch to run the sequence and the device runs flawlessly. Once I add the "switching" part to the code, the servos freak out and fidget constantly without a positive result. I am fairly new to the servo library in Arduino and am open to any kind of instruction or changes to my code below. Thanks for your help!

#include <Servo.h>

Servo servo; //we think this will make the Cont-Rot servo to sit still
Servo iservo; //set second servo

#define button 3 //attaches button to pin 3
int ibutton = 0; //ibutton is used to store state of input
#define button2 2 //second button attached to pin 2
int qbutton = 0; //qbutton stores input
#define button7 7 //switch connected to pin 7
int sbutton = 0; //switch stores input

void setup() {
  servo.attach(5); //attaches servo to pin 5
  iservo.attach(6); //attaches second servo to pin 6
  pinMode(button, INPUT); //sets button as input
  pinMode(button2, INPUT); //sets button2 as input
  pinMode(button7, INPUT); //sets switch as input

void loop() {
  ibutton = digitalRead(button); //reads state of button
  qbutton = digitalRead(button2); //reads state of second button
  Switch = digitalRead(button7); //reads state of switch
if (Switch == LOW) { //if switch is off
  if (ibutton == HIGH) { //and ibutton is pressed
    iservo.write(0); //run this servo sequence
  if (ibutton == LOW) { //ibutton is not pressed
    servo.write(90); //do nothing
  if (Switch == HIGH) { //switch is on
    if ((ibutton == HIGH) && (qbutton == LOW)) { //ibutton is pressed and qbutton is not
      servo.write(80); //servo spin counter-clockwise
    if ((ibutton == LOW) && (qbutton == HIGH)) { //ibutton is not pressed and qbutton is
      servo.write(100); //servo spin clockwise
    if ((ibutton == LOW) && (qbutton == LOW)) { //neither button is pressed
      servo.write(90); //do nothing


Walk through your code on paper. Take VERY great care to consider just exactly WHEN your switches and buttons are high and low.

Since switch can be EITHER high or low, and nothing in between you should use an IF ELSE construction around the selection condition.

CLUE: Regardless of the state of "Switch", if ibutton is low, you push the servo to one position.....