Ive done some more work on the code and come up with this. Everything works as I want it to, except the motor goes back and forth really quickly when there is no input, and the backlight blinks to it. When you enter commands, the motor pauses, and it performs the 90° turns fine. Its only when its idle that it goes back and forth.
#include <Servo.h>
#include <Keypad.h>
#include <LiquidCrystal.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
bool state = true;
bool doorOpen;
int currentLength = 0;
int i = 0;
char password[4] = {
0,0,0,0};
char entered[4];
char keys[ROWS][COLS] =
{
{
'1','2','3' }
,
{
'4','5','6' }
,
{
'7','8','9' }
,
{
'*','0','#' }
};
byte rowPins[ROWS] = {
3, 2, 1, 0 };
byte colPins[COLS] = {
7, 6, 5 };
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);
Servo servo; // create servo object to control a servo
void setup()
{
servo.attach(4); // attaches the servo on pin 0 to the servo object
servo.write(0);
lcd.begin(2, 16);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Pick a password:");
while (currentLength < 4)
{
lcd.setCursor(currentLength + 6, 1);
lcd.cursor();
char key = keypad.getKey();
if (key != NO_KEY)
{
lcd.print(key);
password[currentLength] = key;
currentLength++;
delay(200);
}
}
if (currentLength == 4)
{
lcd.noCursor();
lcd.clear();
lcd.home();
lcd.print("The password is");
lcd.setCursor(6,1);
lcd.print(password[0]);
lcd.print(password[1]);
lcd.print(password[2]);
lcd.print(password[3]);
delay(3000);
currentLength = 0;
}
}
void loop()
{
if (!doorOpen)
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Enter password:");
while (currentLength < 4)
{
lcd.setCursor(currentLength + 6, 1);
lcd.cursor();
char key = keypad.getKey();
if (key != NO_KEY)
{
lcd.print(key);
entered[currentLength] = key;
currentLength++;
delay(200);
lcd.noCursor();
lcd.setCursor(currentLength + 5, 1);
lcd.print("*");
lcd.setCursor(currentLength + 6, 1);
lcd.cursor();
}
}
if (currentLength == 4)
{
if (entered[0] == password[0] && entered[1] == password[1] && entered[2] == password[2] && entered[3] == password[3])
{
lcd.noCursor();
lcd.clear();
lcd.home();
lcd.print("--- Password ---");
lcd.setCursor(0,1);
lcd.print("--- Accepted! --");
servo.write(90);
delay(1500);
lcd.clear();
lcd.home();
lcd.print("----- Door -----");
lcd.setCursor(0,1);
lcd.print("---- opened ----");
delay(1500);
currentLength = 0;
doorOpen = true;
}
else
{
lcd.noCursor();
lcd.clear();
lcd.home();
lcd.print("--- Password ---");
lcd.setCursor(0,1);
lcd.print("--- Incorrect! --");
delay(1500);
currentLength = 0;
}
}
}
else
{
lcd.clear();
lcd.home();
lcd.print("--- Press # ----");
lcd.setCursor(0,1);
lcd.print("--- to lock. ---");
while (doorOpen)
{
char key = keypad.getKey();
if (key != NO_KEY && key == '#')
{
lcd.clear();
lcd.home();
lcd.print("----- Door -----");
lcd.setCursor(0,1);
lcd.print("---- locked ----");
servo.write(0);
delay(1500);
doorOpen = false;
}
}
}
}