Controlling Servo with 1 button and Arduino - Need help.

Thread Starter

Device Unknown

Joined Apr 11, 2016
3
Hey guys,
I have been at this for some time and I just can not seem to get it. Programming never was my strong suit.
I am simply trying to push a button and make a servo move from point A to B and stop. Then push button again and have it move from Point B back to point A.

It seems so easy in theory and what sample code i get. But all the code I work with has 2 issues. 1) I have to old the button down for the servo to stay at point B, upon releasing it returns to A. and 2) the servo jitters.
I have the servo powered externally and grounded to the Mega also. I also added the debouncing and delay to supposedly help with jitter.

Any and all help would be greatly appreciated.
 

MrSoftware

Joined Oct 29, 2013
1,573
The jitter is probably due to the clock on the arduino not being stable. Does it jitter at points a and b, or just b?

In your code set a flag that flip flops when you press the button. Something like (I'm trying to remember servo code from a couple years ago lol):

Position = 100; // position a, 200 is position b

When button pushed:

Position = (position == 100 ? 200 : 100)

To reduce jitter, do as little as possible in-between button pushes. Using processor power can cause variations in the pulses sent to the servo, causing jitter.
 

jpanhalt

Joined Jan 18, 2008
8,105
What is the repeat rate (frame rate) for the servo pulse? The problem you describe can occur when the repeat rate is too high. It should be around 50 Hz (20 ms between repeats) for most inexpensive hobby servos. Some newer servos are different.

John
 

Thread Starter

Device Unknown

Joined Apr 11, 2016
3
servo.jpg
This is how I wired it. When I use this code...
C:
#include <Servo.h>
int button = 8; //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(9); //pin for servo control signal
  digitalWrite(8, 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
}
It just starts sweeping.

Moderators note: please use code tags for pieces of code
 
Last edited by a moderator:

MrSoftware

Joined Oct 29, 2013
1,573
Only read your button press when the state changes, not on every loop. When the button state changes, only toggle the servo position when the button change was to be pressed down.
 
Top