roboticstinkercad

Why is my servo starting at 180 degrees on program start?


I'm trying to build a 2 degrees of freedom robotic arm as a prototype except my code is having my servo start at 180 degrees.

I have two push buttions that are supposed to have it move to 360 degrees and 0 degrees, which works, but when I start the program the servo always moves to 180 degrees.

// C++ code
//

#include <Servo.h>
Servo helloServo;
int baseButton1 =11;
int baseButton2 = 10;
int pos = 0;
int baseValue1;
int baseValue2;


void setup()
{
  helloServo.attach(2);
  pinMode(baseButton1,INPUT_PULLUP);
  pinMode(baseButton2,INPUT_PULLUP);
}

void loop()
{
  byte baseValue1 = digitalRead(baseButton1);
  if (baseValue1 != 1)
  {
    helloServo.write(360);
    pos +=1;
  }

  
  byte baseValue2 = digitalRead(baseButton2);
  if (baseValue2 != 1)
  {
    pos = 0;
    helloServo.write(pos);
  }

}

Solution

  • I am guessing that you're issue is because you aren't giving your servo an initial value, so the pin is likely floating. Try adding

    helloServo.write(360);
    

    to the end of your void setup(), this should make the servo start at the 360 position.