Control a servo with one push button

For my gate I needed to control a servo with one push button...when I press it once it turns 180 deg.  When I push it again, it swings back to 0 deg.  Or I want to move a servo from position A to B with a push of 1 button. Then from B back to A with push of same button.

digin.jpg

Hobby servos that I am familiar with need the 1 to 2 mS pulse delivered at 50 Hz. This can be done without a library, but Servo library makes it much easier. To make the sketch work like you want, you need to detect when the button is pushed (transition from HIGH to LOW or LOW to HIGH) not the level, LOW or HIGH. The state change detection example in the digital section of example code in the IDE shows how to detect the transition. The example includes a button push count variable so on the first transition send one value to the servo and on the second transition send a different value to the servo. Note that in the state change detection example the switch is wired with a pull down. If the switch is wired like the schematic, reverse the logic.

Screen Shot 2020-06-09 at 4.55.29 PM.png


//servo button toggle
#include <Servo.h>
int button = 5; //button pin, connect to ground to move servo
int press = 0;
Servo servo;
boolean toggle = true;

void setup()
{
  pinMode(button, INPUT); //arduino monitor pin state
  servo.attach(7); //pin for servo control signal
  digitalWrite(5, HIGH); //enable pullups to make pin high
}

void loop()
{
  press = digitalRead(button);
  if (press == LOW)
  {
    if(toggle)
    {
      servo.write(160);
      toggle = !toggle;
    }
    else
    {
      servo.write(20);
      toggle = !toggle;
    }
  }
  delay(500);  //delay for debounce
}

Previous
Previous

Electric motors for DIY Electric Cars and Go Karts : A Simple Guide

Next
Next

6 Ideas to Make Money With a 3D Printer