Week 4: Combination lock

This Week’s assignment was to create a circuit for a combination lock. The default state for this circuit is locked (represented by a red LED). When all four buttons are pressed in the right sequence, the circuit becomes unlocked (LED turns green).

List of Materials

1 x Elegoo Uno R3

1 x Full sized breadboard

4 x Pushbuttons

2 x LED’s (Red and Green)

Resistors: 4 x 220 Ohms (for the LEDs), 2 x 10K Ohms (for the buttons)

Jumper wires

Description of assembly 

  1. Connect both sides of the breadboard to each other. The ground to the ground and the power to the power using jumper wires.
  2. Connect the ground side of the breadboard to the GND pin, and the power side to the 5V pin, on the Arduino.
  3. Add pushbuttons to the breadboard, where one of the legs is connected to the power source, the adjacent leg to the ground (through the resistor). Connect the leg opposite the ground to a digital pin. When the pushbutton is not pressed, the digital output pin is connected to the ground and returns a LOW state. When it is pressed, the circuit gets complete, electricity flows through it, and a HIGH state is recorded.
  4. Arrange the LEDs with the shorter leg connected to the ground through a resistor and the longer leg to the digital pins.
  5. Upload the code to the Arduino IDE.
  6. Debug, check connections and keep working on iterations.

How it works

The Arduino code, has nested if loops that sequentially check whether certain conditions hold true. It first checks whether button 1 is pressed, if it is, then it checks if button 2 is pressed and so on and so forth. There are two variables being used buttonPushCounter and val. The first checks whether any button is being pressed and the other is to determine the order in which they are being pressed. It is only when all the four buttons are pressed in the right order that the green LED lights up.


Setting the circuit was not as challenging as was getting the code to work. I encountered a problem with my buttonPushCounter because it wasn’t registering button presses. I used the console to debug and realized that it was because I had defined the variable globally as well as locally which was interfering with the functioning of the code. The solution is to either define it globally or to use something called static int to define it within the scope of the void loop.

What I am still struggling with is using the same button twice in the code. At present, I can program different combinations of button presses, but I cannot get the counter to reset every time a button is pressed.


//Referenced from code available on the Arduino forum


Leave a Reply

Your email address will not be published. Required fields are marked *