/*
Servo waver, inspired by
Arduino | coding-help
welden lebe September 20, 2025 — 6:05 AM
*/
#include <Servo.h>
const int BTN_PIN = 2;
const int SERVO_PIN = 9;
const int INTERVAL = 5; // 5ms between servo steps
bool doWave = false;
int oldBtnState = 1; // pin idles high
int increment = 1;
int pos = 0;
unsigned long lastUpdate = 0;
Servo servo;
bool checkButton() {
bool wasPressed = false;
int btnState = digitalRead(BTN_PIN); // read the pin
if (btnState != oldBtnState) { // if it changed
oldBtnState = btnState; // remember the state
if (btnState == LOW) { // was just pressed
wasPressed = true;
//Serial.println("Button Pressed");
} else { // was just released
//Serial.println("Button Released");
}
delay(20); // short delay to debounce button
}
return wasPressed;
}
void waveServo() {
if ((millis() - lastUpdate) > INTERVAL) { // time to update
lastUpdate = millis();
pos += increment;
servo.write(pos);
//Serial.println(pos);
if ((pos >= 180) || (pos <= 0)) { // end of sweep
// reverse direction
increment = -increment;
}
}
}
void setup() {
Serial.begin(115200);
servo.attach(SERVO_PIN);
pinMode(BTN_PIN, INPUT_PULLUP);
Serial.println("Push the button!\n");
}
void loop() {
if (checkButton()) { // if the button was pressed
doWave = !doWave; // toggle the 'doWave' variable
Serial.println(doWave ? "Start waving" : "Stop waving");
}
if (doWave) {
waveServo(); // wave if true
}
}