// // put your setup code here, to run once:
#include <ESP32Servo.h>
#include <Keypad.h>
// Define the pin connected to the servo's PWM wire
int servoPin = 5;
Servo myServo;
// Define a code, later on this will be sent to the box from the app
String correctCode = "12345"; // Change this to your desired code
String inputCode = ""; // Variable to store input from the keypad
// Setup keypad pins and layout
const byte ROWS = 4; // 4 rows
const byte COLS = 3; // 3 columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {1, 2, 3, 4};
byte colPins[COLS] = {6, 7, 8};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
// Attach the servo on the specified pin to the servo object
myServo.attach(servoPin);
myServo.write(0); // Initialize the servo to 0 degrees (closed)
// Begin Serial communication for debugging
Serial.begin(115200);
}
void loop() {
// Check for code, if code input by user == code defined - move servo
char key = keypad.getKey(); // Get the pressed key
if (key) { // If a key is pressed
if (key == '#') { // '#' will be used as the "Enter" key
if (inputCode == correctCode) {
// Correct code entered, move the servo
Serial.println("Correct Code! Opening box...");
openBox(); // Call the function to open the box (servo movement)
} else {
// Incorrect code, reset input
Serial.println("Incorrect Code. Try again.");
inputCode = ""; // Clear the input
}
} else if (key == '*') {
// '*' will be used to clear the input
Serial.println("Clearing input...");
inputCode = ""; // Reset the inputCode
} else {
// Append pressed key to inputCode
inputCode += key;
Serial.println("Entered: " + inputCode);
}
}
}
// Function to move the servo and simulate opening the box
void openBox() {
// Move the servo to 180 degrees (open)
myServo.write(180);
delay(2000); // Keep the box open for 2 seconds
// Move the servo back to 0 degrees (closed)
myServo.write(0);
}