/*
Arduino | coding-help
Need Help with Project
technical — January 15, 2025 at 10:09 PM
I need help getting the servo to spin when the button is pushed,
and automatically release when the button is not pushed.
My current code is just making the motor spin randomly.
*/
#include <Servo.h>
Servo myservo; // Create a servo object
const int pushButtonPin = 2; // Pin connected to the button
int defaultAngle = 0; // Default angle
int activeAngle = 90; // Angle to turn when button is pressed
bool buttonState = false; // Current button state
void setup() {
pinMode(pushButtonPin, INPUT_PULLUP); // Set button pin as input with pull-up resistor
myservo.attach(4); // Attach servo to pin 9
myservo.write(defaultAngle); // Set servo to default position
Serial.begin(9600); // Start serial communication
Serial.println("Servo Button Control Initialized");
}
void loop() {
if (digitalRead(pushButtonPin) == LOW) { // Button pressed (LOW due to pull-up)
if (!buttonState) { // Detect state change to avoid repeated movement
buttonState = true;
myservo.write(activeAngle); // Move servo to active position
Serial.println("Button pressed: Servo moved to 90 degrees");
}
} else { // Button released
if (buttonState) { // Detect state change to avoid repeated movement
buttonState = false;
myservo.write(defaultAngle); // Move servo back to default position
Serial.println("Button released: Servo moved back to default position");
}
}
}