- #include <avr/sleep.h>
- #include <avr/interrupt.h>
- #include <SoftwareSerial.h>
-
- const int rx = 1; // for serial input
- const int tx = 4; // pin 5 for serial.print()
- SoftwareSerial Serial(rx, tx); // rx, tx pins
-
- int rgLed = 2; // red/green LED pin
- int button = 3; // buttons pin
- int buttonValue; // Stores analog value when button is pressed
-
- String ourCode = "1324"; // Set the required PIN code.
- String currentCode = ""; // Stores entered code
-
- void setup() {
- pinMode(rgLed, INPUT);
- pinMode(rx, INPUT); // setup and print to serial
- pinMode(tx, OUTPUT);
- Serial.begin(9600);
- Serial.println("Running");
-
- red(500);
- green(500);
- }
-
- #pragma GCC push_options
- #pragma GCC optimize ("O0") // Disable optimisations
-
- void addkey(String keyPressed) {
- currentCode += keyPressed;
- Serial.println("Entered so far: " + currentCode);
-
- if (currentCode.length() == ourCode.length()) {
- Serial.print("Checking: ");
- volatile bool correct = true;
-
- for (int i = 0; i < ourCode.length(); i++) {
- if (currentCode[i] != ourCode[i]) {
- correct = false;
- break;
- }
-
- do_login();
- }
-
- if (correct) {
- Serial.println("correct");
- green(500);
- delay(500);
- green(500);
- delay(500);
- green(500);
- } else {
- Serial.println("failed");
- red(500);
- }
- currentCode = ""; // Reset the entered code
- }
- }
-
- #pragma GCC pop_options
-
- void green(int del) { // turn on green LED for delay()
- pinMode(rgLed, OUTPUT);
- analogWrite(rgLed, HIGH);
- delay(del);
- pinMode(rgLed, INPUT);
- }
-
- void red(int del) { // turn on red LED for delay()
- pinMode(rgLed, OUTPUT);
- analogWrite(rgLed, 255);
- delay(del);
- pinMode(rgLed, INPUT);
- }
-
- void do_login(){
- delay(5);
- }
-
- void loop() {
- buttonValue = analogRead(button); // Read analog value from A0 pin
-
- if (buttonValue >= 1015 && buttonValue <= 1030) { // For 1st button:
- addkey("1");
- } else if (buttonValue >= 1000 && buttonValue <= 1014) { // For 2nd button:
- addkey("2");
- } else if (buttonValue >= 950 && buttonValue <= 999) { // For 3rd button:
- addkey("3");
- } else if (buttonValue >= 870 && buttonValue <= 950) { // For 4th button:
- addkey("4");
- }
-
- if (Serial.available()) { // Check if data is available from Serial input
- char key = Serial.read(); // Read the character
- if (key >= '1' && key <= '4') { // Ensure input is a valid key
- addkey(String(key));
- }
- }
-
- delay(100);
- }