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.