#include <avr/io.h>
#include <util/delay.h>
#include <string.h>
// Define pins for LED
#define LED_PIN PB0
// Define keypad connections
#define KEYPAD_PORT PORTD
#define KEYPAD_DDR DDRD
#define KEYPAD_PIN PIND
// Password definition
const char password[] = "1234";
char entered_password[5];
void keypad_init();
char keypad_getkey();
void check_password();
void lock_open();
void lock_close();
int main(void) {
// Initialize peripherals
keypad_init();
DDRB |= (1 << LED_PIN); // Set LED pin as output
while (1) {
check_password();
}
}
void keypad_init() {
KEYPAD_DDR = 0xF0; // Rows as outputs, Columns as inputs
KEYPAD_PORT = 0x0F; // Enable pull-ups on columns
}
char keypad_getkey() {
for (uint8_t row = 0; row < 4; row++) {
KEYPAD_PORT = ~(1 << (row + 4)); // Ground one row
_delay_ms(10);
for (uint8_t col = 0; col < 4; col++) {
if (!(KEYPAD_PIN & (1 << col))) {
while (!(KEYPAD_PIN & (1 << col))); // Wait for release
return (row * 4 + col) + '0'; // Return key value
}
}
}
return '\0'; // No key pressed
}
void check_password() {
uint8_t index = 0;
char key;
// Collect password
while (index < 4) {
key = keypad_getkey();
if (key != '\0') {
entered_password[index++] = key;
}
}
entered_password[index] = '\0';
// Verify password
if (strcmp(entered_password, password) == 0) {
lock_open();
} else {
lock_close();
}
}
void lock_open() {
PORTB |= (1 << LED_PIN); // Turn on LED
_delay_ms(3000); // Hold for 3 seconds
PORTB &= ~(1 << LED_PIN);// Turn off LED
}
void lock_close() {
// Blink LED for failure
for (uint8_t i = 0; i < 3; i++) {
PORTB |= (1 << LED_PIN);
_delay_ms(200);
PORTB &= ~(1 << LED_PIN);
_delay_ms(200);
}
}