Hello,
I am working on a sketch in which when the correct keypad password is typed in, a servo moves, then when a button is pressed it waits 5 seconds then moves back. I have added almost everything i need but I still need to debounce the button. I have read example sketches but cant quite figure out how to put it into my sketch. Can anybody help me?
Here is the code:
#include <Servo.h> //include the servo library
#include <Keypad.h> //include the keypad library
Servo servoMain; //Define our servo
const int buttonPin = 2; //the pushbutton pin
int buttonState = 0; //variable for reading the pushbutton
char* secretCode = "235711";
int position = 0;
const byte rows = 4;
const byte cols = 3;
char keys[rows][cols] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[rows] = {4, 5, 6, 7};
byte colPins[cols] = {1, 2, 3};
Keypad keypad = Keypad(makeKeymap(keys),
rowPins, colPins,
rows, cols);
int redPin = 8;
int greenPin = 9;
void setup()
{
//start button code
pinMode(buttonPin, INPUT);
//end button code
//start servo code
servoMain.attach(10); //servo on digital pin 10
//end servo code
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
setLocked(true);
}
void loop()
{
//start button code
buttonState = digitalRead(buttonPin); //read the state of the button
if (buttonState == HIGH) {
delay(5000); //wait 5 seconds
servoMain.write(90); //turn servo 90 deg. left (locked)
}
//end button code
char key = keypad.getKey();
if (key == '*' || key == '#') {
position = 0;
setLocked(true);
}
if (key == secretCode[position]) {
position++;
}
if (position == 6) {
setLocked(false);
}
delay(50);
}
void setLocked(int locked)
{
if (locked) {
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
}
else {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
servoMain.write(0); // Turn Servo to center
}
}
P.S. I am new to programming and Arduino
Thanks