#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#define RELAY_PIN 23
// Keypad pins
int rowPins[4] = {19, 18, 5, 17};
int colPins[4] = {16, 4, 2, 15};
char keys[4][4] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
char password[] = "1234";
char input[5];
int pos = 0;
// Initialize GPIO
void gpio_init_all() {
// Set rows as OUTPUT
for(int i = 0; i < 4; i++) {
gpio_reset_pin(rowPins[i]);
gpio_set_direction(rowPins[i], GPIO_MODE_OUTPUT);
gpio_set_level(rowPins[i], 1);
}
// Set columns as INPUT with pull-up
for(int i = 0; i < 4; i++) {
gpio_reset_pin(colPins[i]);
gpio_set_direction(colPins[i], GPIO_MODE_INPUT);
gpio_set_pull_mode(colPins[i], GPIO_PULLUP_ONLY);
}
// Relay pin
gpio_reset_pin(RELAY_PIN);
gpio_set_direction(RELAY_PIN, GPIO_MODE_OUTPUT);
gpio_set_level(RELAY_PIN, 0);
}
// Scan keypad
char scan_keypad() {
for(int row = 0; row < 4; row++) {
gpio_set_level(rowPins[row], 0); // activate row
for(int col = 0; col < 4; col++) {
if(gpio_get_level(colPins[col]) == 0) {
vTaskDelay(pdMS_TO_TICKS(200)); // debounce
gpio_set_level(rowPins[row], 1);
return keys[row][col];
}
}
gpio_set_level(rowPins[row], 1); // deactivate row
}
return '\0';
}
void app_main() {
gpio_init_all();
memset(input, 0, sizeof(input));
while(1) {
char key = scan_keypad();
if(key != '\0') {
printf("Pressed: %c\n", key);
if(key == '#') {
input[pos] = '\0';
if(strcmp(input, password) == 0) {
printf("Access Granted\n");
gpio_set_level(RELAY_PIN, 1);
vTaskDelay(pdMS_TO_TICKS(5000));
gpio_set_level(RELAY_PIN, 0);
} else {
printf("Access Denied\n");
}
pos = 0;
memset(input, 0, sizeof(input));
}
else if(key == '*') {
pos = 0;
memset(input, 0, sizeof(input));
printf("Cleared\n");
}
else {
if(pos < 4) {
input[pos++] = key;
}
}
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}