Im very newbie with this and coding, i dont know a lot of stuff.
So, i want to make a garage with an automated door, that can also be locked and unlocked with a keypad, for a RC car for a school proyect.
The thing is simple, the car goes close to the garage, and if the garage is unlocked, a sensor detects the car, the garage door opens with a servo when the car gets detected.
But when the garage is locked, the garage door doesn't open when getting the car close.
I wanted to make to the door gets locked when pressing '1' in the keypad, then unlocking it pressing '2', and i managed to make it stay lock, but cant unlock it, and i dont know how to solve it. I already tried many ways and looked up some tutorials, but i couldn't find anything that i could understand, is there a way to make a proper lock? I'm somewhat desperate.
PS. The LCD shows the state of the lock.
(also sorry if my english is confusing)
#include <LiquidCrystal.h>
const int pecho = 13;
const int ptrig = 12;
int duration, distance;
LiquidCrystal lcd(8,7,5,4,3,2);
#include <Servo.h>
Servo servoMotor;
#include <Keypad.h>
const byte ROWS = 2;
const byte COLS = 2;
char Keys[ROWS][COLS] = { //only using 4 keys from a 4x4 keypad.
{'1', '2'},
{'4', '5'},
};
byte rowPins[ROWS] = {16, 17};
byte colPins[COLS] = {14, 15};
Keypad customKeypad = Keypad(makeKeymap(Keys), rowPins, colPins, ROWS, COLS);
//
void setup() {
Serial.begin(9600);
servoMotor.attach(6);
pinMode(pecho, INPUT);
pinMode(ptrig, OUTPUT);
lcd.begin(16, 2);
}
//
void loop() {
char KEY = customKeypad.getKey();
int keyState = '1';
int lastKeyState = 0;
int keyOverwrite = '4';
while (KEY == '1'){
delay(500);
//
if (KEY){
Serial.println(KEY); //this was only to verify if the thing worked, wich is not
//
}
if ((KEY == '1') && (lastKeyState = '1')){ //the problem, i can't make it exit the state '1' (LOCK)
if (KEY == '2'){
lastKeyState == keyOverwrite;
}
lcd.setCursor(0,0);
lcd.print("--Status--");
Serial.print("--Status--");
lcd.setCursor(0,1);
lcd.print("[Lock]");
Serial.print("[Lock]");
servoMotor.write(90);
delay(200);
keyState == lastKeyState; //what i did to make it loop from here
}
}
digitalWrite(ptrig, LOW); //State (UNLOCK), i cant get it to get back here and loop here again,
delay(2);
digitalWrite(ptrig, HIGH);
delay(0.01);
digitalWrite(ptrig, LOW);
duration = pulseIn(pecho, HIGH);
distance = (duration/2)*0.034;
delay(2);
if (distance > 20){
lcd.setCursor(0,0);
lcd.print("--Status--");
Serial.print("--Status--");
lcd.setCursor(0,1);
lcd.println("Closed");
Serial.println("Closed");
servoMotor.write(90);
}
else if(distance <= 20){
lcd.setCursor(0,0);
lcd.print("--Status--");
Serial.print("--Status--");
lcd.setCursor(0,1);
lcd.println("Open");
Serial.println("Open");
servoMotor.write(0);
}
}