#include <ESP32Servo.h>
#include <Keypad.h>
// Defining Pins
#define SERVO_PIN 2 // Servo motor pin
// Servo motor
Servo servo;
// Define the keypad
const byte ROW_NUM = 4; // four rows
const byte COLUMN_NUM = 4; // four columns
char keys[ROW_NUM][COLUMN_NUM] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte pin_rows[ROW_NUM] = {23, 22, 21, 19}; // connect to the row pinouts of the keypad
byte pin_column[COLUMN_NUM] = {18, 5, 15, 14}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM);
// Define passwords
const char* correctPassword = "1234"; // Change this to your desired password
const char* closePassword = "4321"; // Change this to your desired close password
// Buffer to store entered password digits
char enteredPassword[5]; // Assuming the password length is 4 digits, plus one for null terminator
// Index to keep track of the current position in the entered password buffer
int passwordIndex = 0;
// Flag to track whether the servo is open or closed
bool isServoOpen = false;
void setup() {
Serial.begin(115200);
servo.attach(SERVO_PIN);
servo.write(0); // Initialize servo to 0 degrees (closed position)
}
void loop() {
// Local keypad control
char key = keypad.getKey();
if (key) {
Serial.println("Keypad key pressed: " + String(key));
// Check if the key is a numeric key
if (isdigit(key)) {
// Store the entered digit in the buffer
enteredPassword[passwordIndex] = key;
passwordIndex++;
// Check if the entered password matches the correct password
if (passwordIndex == 4 && strcmp(enteredPassword, correctPassword) == 0) {
Serial.println("Correct password entered. Opening servo.");
// Move the servo to 180 degrees (open position)
servo.write(180);
// Update the servo state and reset the password buffer and index
isServoOpen = true;
passwordIndex = 0;
memset(enteredPassword, 0, sizeof(enteredPassword));
} else if (passwordIndex == 4 && strcmp(enteredPassword, closePassword) == 0) {
Serial.println("Close password entered. Closing servo.");
// Move the servo to 0 degrees (closed position)
servo.write(0);
// Update the servo state and reset the password buffer and index
isServoOpen = false;
passwordIndex = 0;
memset(enteredPassword, 0, sizeof(enteredPassword));
} else if (passwordIndex >= 4) {
// Incorrect password entered, move the servo to 0 degrees (closed position)
Serial.println("Incorrect password. Moving servo to 0 degrees (closed)");
servo.write(0);
// Reset the password buffer and index
passwordIndex = 0;
memset(enteredPassword, 0, sizeof(enteredPassword));
}
}
}
}