Problem with servo

I'm trying out a servo motor for the first time. I want it to turn 0 degree when 'on' is entered and 90 degree when 'off' is entered. But it shows random stuff in the serial monitor and sometimes it just stops working. I don't know whether it's a problem with the code or with the servo. I'm providing a 5V power supply from the arduino UNO.

#include <Servo.h>

Servo servoMotor;
int servoPin = 9;

void setup() {
  Serial.begin(9600);
  servoMotor.attach(servoPin);
  servoMotor.write(90);
}

void loop() {
  if (Serial.available() > 0) {
    String state = Serial.readString();
    state.trim();
    if(state == "on"){
      servoMotor.write(0);
    }
    else if (state == "off"){
      servoMotor.write(90);
    }
    else{
      Serial.println("Invalid Input");
    }
  }
}

What have you got Line Ending set to in the Serial monitor ?

How is the servo powered and which Arduino are you using ?

You need to connect the servo to a 5V power supply, NOT the UNO 5V output

oh, so i'll need a separate power supply? the 5V on the arduino won't work?

It can't output enough current for even a small servo.
If you don't have a 5V supply, you can use 4 AA batteries

ok, thx! i'll surely try it

Make sure you connect the servo ground wire (usually black) to BOTH the power supply and the UNO GND

Don't forget to connect the GND of the external supply to the GND of the Uno so that there is a common point of reference for the servo control signal

As an aside, it is an unfortunate fact that a Uno can provide enough current to drive a servo, but only under very limited circumstances. The Uno is not designed to be used as a power supply

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.