/*
Arduino | coding-help
Code help with button
klapxed - Sunday, February 15, 2026 4:18 PM
hey everyone, im a beginner and im tryna build a lock with
a pattern where if i press a button twice, the servo motor
rotates and opens the lock, however i dont know how to make
a condition to check whether the button is pressed 2 times
consecutively, anyone can help?
TODO: still not quite right...
*/
#include <Servo.h>
const int BTN_PIN = 2;
const int SERVO_PIN = 3;
const unsigned long TIME_OUT = 1000;
bool isLocked = true;
int count = 0;
int oldBtnState = HIGH; // button idles HIGH
unsigned long prevTime = 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
//Serial.println("Button Pressed");
wasPressed = true;
} else { // was just released
//Serial.println("Button Released");
}
delay(20); // short delay to debounce button
}
return wasPressed;
}
void lockServo() {
isLocked = true;
servo.write(0);
//if (!isLocked) {
//Serial.println("Locked!");
//}
}
void unlockServo() {
isLocked = false;
servo.write(180);
Serial.println("Unlocked!");
}
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP);
servo.attach(SERVO_PIN);
Serial.println("System ready");
lockServo();
}
void loop() {
bool wasPressed = checkButton();
if (wasPressed) {
count++;
if (count == 1) {
prevTime = millis();
if (!isLocked) {
count = 0;
lockServo();
Serial.println("Locked!");
}
}
}
if (count == 2) {
count = 0;
if (millis() - prevTime < TIME_OUT) {
unlockServo();
} else {
lockServo();
}
}
}