I am relatively new to arduino and having a few problems on one of my projects. I am attempting to make a combination lock, using two buttons, that activate a servomotor when the correct sequence is pressed. I have it sort of figured out - the correct combination is supposed to be "1221" (in reference to the buttons). However, any sequence beginning with a 1 is passing as correct. My code is attached in the file below. Any help would be greatly appreciated. For those of you too sketched out to open the file, here is the code below. Sorry if the formatting is not great.
// Which pins things are attached to
#include <Servo.h>
Servo myServo;
const int b1 = 3;
const int b2 = 4;
const int b3 = 7;
const int correctLed = 5;
const int incorrectLed = 6;
// button states when they are pressed
int bs1 = 0;
int bs2 = 0;
int bs3 = 0;
int pwcount = 0;
int combination[4] = {1, 2, 2, 1};
int userInput[4];
void setup() {
myServo.attach(2);
pinMode(b1, INPUT);
pinMode(b2, INPUT);
pinMode(b3, INPUT);
pinMode(correctLed, OUTPUT);
pinMode(incorrectLed, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(incorrectLed, LOW);
digitalWrite(correctLed, LOW);
static int pushCounter = 0;
bs1 = digitalRead(b1);
bs2 = digitalRead(b2);
if (bs1 == HIGH){
userInput[pwcount] = 1;
pwcount++;
delay(300);
Serial.print('1');
}
if (bs2 == HIGH){
userInput[pwcount] = 2;
pwcount++;
delay(300);
Serial.print('2');
}
int n = 0;
for(n = 0; n < 4; n++){
if (userInput[n] == combination[n] && pwcount == 4){
digitalWrite(correctLed, HIGH);
Serial.println("unlocked");
myServo.write(179);
delay(3000);
pwcount = 0;
}
else {
if(userInput[n] != combination[n] && pwcount == 4){
digitalWrite(incorrectLed, HIGH);
Serial.println("Denied");
delay(2000);
pwcount = 0;
n = 0;
}
bs3 = digitalRead(b3);
if(bs3 == HIGH){
myServo.write(1);
}
}
}
}
lock_sketch.ino (1.53 KB)