Nano with Servo

So i would just like some help getting my arduino nano and its shield to make a servo motor to spin 90 degrees after i press a button, and go back counter clockwise after i press the button again. My servo is connected to pin 9, and button is pin 4.

The script right now works by when button is pressed the servo motor goes indifinetly until i press it again which it stops.

#include <Servo.h>

#define BUTTON_PIN 4  // Button connected to D4
#define SERVO_PIN 9   // Servo motor connected to D9

Servo myservo;  // Create Servo object to control the servo

bool buttonState = HIGH;       // Current button state
bool lastButtonState = HIGH;   // Previous button state
bool servoPosition = false;    // Tracks servo position (false = 0 degrees, true = 90 degrees)

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP); // Button as input with pull-up resistor
  myservo.attach(SERVO_PIN);        // Attach the servo to pin 9
  myservo.write(0);                 // Start with the servo at 0 degrees
}

void loop() {
  buttonState = digitalRead(BUTTON_PIN); // Read the button state

  // Detect button press (transition from HIGH to LOW)
  if (buttonState == LOW && lastButtonState == HIGH) {
    toggleServoPosition(); // Toggle the servo position
    delay(300);            // Debounce delay
  }
  lastButtonState = buttonState; // Update the last button state
}

// Function to toggle the servo position
void toggleServoPosition() {
  if (servoPosition) {
    myservo.write(0);     // Move servo to 0 degrees
  } else {
    myservo.write(90);    // Move servo to 90 degrees
  }
  servoPosition = !servoPosition; // Toggle the position state
}

Thanks for the help.

Welcome to the forum

Does the servo rotate continuously through 360 degrees ?

If so, then you do not have a servo, you have an electronically controlled motor and can only control its direction of movement and its speed. Please post a link to where you got the servo

1 Like

yeah it rotates after 360 degrees, its the FIIEC continuous servo fs90r

As I suspected, that is not really a servo at all

sorry forgot the link: Pololu - FEETECH FS90R Micro Continuous Rotation Servo

wait so what does that mean? is it still possible for my script to work?

Your sketch is doing what you tell it to but the so called "servo" is not able to do what you want

You cannot control its angle, which is what you want to do

ok well thanks for you help, it really helped. Thanks once again

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