/*
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>
const int DEFAULT_ANGLE = 135; // Default angle
const int ACTIVE_ANGLE = 45; // Angle to turn when button is pressed
const int BTN_PIN = 2;
const int SERVO_PIN = 4;
const char DEG_SYMBOL = 176; // ascii code for °
int oldBtnState = HIGH; // INPUT_PULLUP
Servo servo;
void checkButton() {
int btnState = digitalRead(BTN_PIN); // read the button
if (btnState != oldBtnState) { // if it changed
oldBtnState = btnState; // save current state
if (btnState == LOW) { // if LOW, was pressed
servo.write(ACTIVE_ANGLE);
Serial.print("Button pressed, servo moved to ");
Serial.print(ACTIVE_ANGLE);
} else { // else HIGH, was released
servo.write(DEFAULT_ANGLE);
Serial.print("Button released, servo moved to ");
Serial.print(DEFAULT_ANGLE);
}
Serial.println(DEG_SYMBOL);
delay(20); // debounce delay
}
}
void setup() {
Serial.begin(9600);
servo.write(DEFAULT_ANGLE); // sets PWM before servo is attached
servo.attach(SERVO_PIN);
pinMode(BTN_PIN, INPUT_PULLUP);
Serial.print("Start: servo at ");
Serial.print(DEFAULT_ANGLE);
Serial.println(DEG_SYMBOL);
}
void loop() {
checkButton();
}