/*
Arduino | coding-help
i needs help (arduino r3)
_tranxt — January 15, 2025 at 5:20 AM
i have a push button to open and close door after 3sec.
but now i want to change it: first press door open, second
press door close
*/
#include <Servo.h>
const int BTN_PIN = 2;
const int SERVO_PIN = 4;
bool doorMode = false;
int oldBtnState = HIGH; // INPUT_PULLUP
Servo doorServo;
// function returns true if button is pressed
bool checkButton() {
bool isPressed = false;
int btnState = digitalRead(BTN_PIN);
if (btnState != oldBtnState) {
oldBtnState = btnState;
if (btnState == LOW) {
isPressed = true;
Serial.println("Button pressed");
}
delay(20); // debounce
}
return isPressed;
}
void setup() {
Serial.begin(9600);
pinMode(BTN_PIN, INPUT_PULLUP);
doorServo.attach(SERVO_PIN);
Serial.println("Door open");
}
void loop() {
bool wasPressed = checkButton();
if (wasPressed) {
doorMode = !doorMode;
Serial.print("Door ");
Serial.println(doorMode ? "closed" : "open");
if (doorMode) {
doorServo.write(0);
} else {
doorServo.write(90);
}
}
}