Hi everybody, this is my first post in this forum.
Yesterday my roommate brought an arduino kit, any of us has any idea how it works but we like this stuff so we started learning the basics. Yesterday nigth we coudn't make a led with a resistance work and today we made a 4 button combination lock, the wiring was pretty easy, and the program took a while (I know some basic C).
This is what we came up, the hardest thing was to figure out how the loop and the imput pins of the buttons work, with adding some delay we finally made it work, but I feel like the code can be much bettter. Do you guys can take a look and suggest us some ways of imporving the code, please? Thank you!
The sequence is 3,4,2,1. If you press the wrong button while making the correct sequence it resets and the red led turns on. If you introduce the correct sequence the blue red truns on and resets and turns off when any button is pressed again.
const int b1 = 2;
const int b2 = 3;
const int b3 = 4;
const int b4 = 5;
const int blu = 6;
const int red = 7;
int b1State = 0;
int b2State = 0;
int b3State = 0;
int b4State = 0;
int d1=0,d2=0,d3=0,d4=0;
void setup() {
pinMode(blu, OUTPUT);
pinMode(red, OUTPUT);
pinMode(b1, INPUT);
pinMode(b2, INPUT);
pinMode(b3, INPUT);
pinMode(b4, INPUT);
}
void loop() {
b1State = digitalRead(b1);
b2State = digitalRead(b2);
b3State = digitalRead(b3);
b4State = digitalRead(b4);
if(d4==1){
digitalWrite(blu, HIGH);
}else{
digitalWrite(blu, LOW);
}
if(b3State == HIGH){
if(d1==0 && d2==0 && d3==0 && d4==0){d1=1;delay(300);}else{d1=0;d2=0;d3=0;d4=0;digitalWrite(red, HIGH);delay(1000);digitalWrite(red, LOW);}
}
if(b4State == HIGH){
if(d1==1 && d2==0 && d3==0 && d4==0){d2=1;delay(300);}else{d1=0;d2=0;d3=0;d4=0;digitalWrite(red, HIGH);delay(1000);digitalWrite(red, LOW);}
}
if(b2State == HIGH){
if(d1==1 && d2==1 && d3==0 && d4==0){d3=1;delay(300);}else{d1=0;d2=0;d3=0;d4=0;digitalWrite(red, HIGH);delay(1000);digitalWrite(red, LOW);}
}
if(b1State == HIGH){
if(d1==1 && d2==1 && d3==1 && d4==0){d4=1;delay(300);}else{d1=0;d2=0;d3=0;d4=0;digitalWrite(red, HIGH);delay(1000);digitalWrite(red, LOW);}
}
}