Micro:bit Password Lock

be a code ninja

Micro:bit Password Lock Documentation

The Micro:bit Password Lock program is a code designed to create a simple password lock functionality on the micro:bit device. It allows users to set a specific button combination to unlock the micro:bit, displaying a happy image upon successful entry.

Program Flow

  1. Initialization
    • The program starts by initializing the necessary variables.
    • password variable stores the desired button combination to unlock the micro:bit.
    • current_input variable tracks the current button input.
    • locked variable represents the lock state of the micro:bit, initially set to True.
  2. Locked State
    • The micro:bit starts in a locked state, where it displays a skull image indicating that it’s locked.
    • The program checks for button presses:
      • If both buttons A and B are pressed simultaneously, the letter “A” is appended to current_input, representing the button A press.
      • If only button B is pressed, the letter “B” is appended to current_input, representing the button B press.
    • If the length of current_input reaches the length of the password:
      • The program checks if current_input matches the password.
        • If there’s a match:
          • The micro:bit is unlocked.
          • The display shows a happy image.
          • After 2 seconds, the display is cleared.
          • current_input is reset for the next input.
        • If there’s no match:
          • The display shows a sad image to indicate an incorrect password.
          • After 2 seconds, the display is cleared.
          • current_input is reset for the next input.
  3. Unlocked State
    • Once the micro:bit is unlocked, it enters the unlocked state.
    • The display is cleared to remove any remaining images from the previous state.
    • After a 2-second pause, the micro:bit becomes locked again.
    • The program goes back to the locked state, waiting for the correct button combination to be entered.

Usage

To use the Micro:bit Password Lock program, follow these steps:

  1. Upload the program to the micro:bit device.
  2. Power on the micro:bit.
  3. The micro:bit will display a skull image, indicating that it’s locked.
  4. Enter the correct button combination specified in the password variable:
    • Press button A and button B in the specific sequence defined by the password.
    • For example, if the password is set as “ABABABAB”, press A, then B, then A, and so on.
  5. Upon successful entry of the correct button combination, the micro:bit will display a happy image for 2 seconds, indicating that it’s unlocked.
  6. After 2 seconds, the display will be cleared.
  7. The micro:bit remains unlocked for 2 seconds, allowing interaction.
  8. After 2 seconds, the micro:bit becomes locked again, and the process repeats from step 3.

Customization

You can customize the Micro:bit Password Lock program according to your needs:

  • Password: Modify the password variable to set your desired button combination for unlocking the micro:bit.
  • Images: You can replace the skull and happy images with your own images by modifying the display.show() function calls.
  • Timing: Adjust the duration of the displayed images or the pause duration by modifying the sleep() function calls.

Feel free to experiment and modify the code to create your own customized password lock functionality on the micro:bit.

Note: Make sure to follow the micro:bit programming guidelines and take necessary precautions while using the device.

Code

from microbit import *
# import music

# Initial state
password = "ABABABAB"  # Set the desired button combination to unlock the micro:bit in the code before you upload to the micro:bit
current_input = ""     # Tracks the current button input
locked = True          # Represents the lock state of the micro:bit, initially set to True

while True:
    if locked:
        display.show(Image.SKULL)  # Display a skull image to indicate locked state
        if button_a.was_pressed():
            current_input += "A"   # Append "A" to current_input upon button A press
            sleep(500)
        elif button_b.was_pressed():
            current_input += "B"   # Append "B" to current_input upon button B press
            sleep(500)
            
        if len(current_input) >= len(password):
            if current_input == password:  # Check if current_input matches the password
                locked = False
                display.show(Image.HAPPY)  # Display a happy image upon successful entry
                # music.play(music.BA_DING)  # Optional sound effect
                sleep(2000)
                display.clear()
                sleep(2000)
                current_input = ""
            else:
                display.show(Image.SAD)  # Display a sad image to indicate incorrect password
                # music.play(music.JUMP_DOWN)  # Optional sound effect
                sleep(2000)
                display.clear()
                current_input = ""
    else:
        display.clear()
        sleep(2000)
        
        locked = True # Comment this line out to remain unlocked and add your code below..

Using Password File

The original password code and the file system password code differ in how they store and retrieve the password for the password lock functionality. Here’s a breakdown of the differences:

  1. Original Password Code:
    • In the original password code, the password is directly defined as a variable within the code itself.
    • The password is stored as a string using a variable assignment, for example: password = "ABABABAB".
    • Whenever the code runs, it compares the user input with the password variable to check for a match.
  2. File System Password Code:
    • In the file system password code, the password is stored in a separate password file.
    • The file path and name are specified using a variable, for example: password_file = "password.txt".
    • The code checks if the password file exists using file system operations.
    • If the file doesn’t exist, it creates the file and writes a default password into it.
    • When the user enters input, the code reads the password from the file and compares it with the user’s input.

The main difference between the two approaches is the storage location of the password. In the original password code, the password is stored directly within the code itself. This means that if you want to change the password, you need to modify the code itself.

On the other hand, in the file system password code, the password is stored in a separate file. This allows for more flexibility as you can change the password by modifying the contents of the password file without modifying the code. It provides a way to store the password externally and separate from the code logic.

Using a password file stored on the micro:bit’s file system allows you to easily update the password without modifying the code, making it more convenient and flexible.

from microbit import *

# File path for the password file
password_file = "password.txt"
default_password = "AAAAAAAA"

# Function to check if the password file exists
def file_exists(file_name):
    try:
        with open(file_name, "r"):
            return True
    except OSError:
        return False

# Check if the password file exists, and create it with the default password if not
if not file_exists(password_file):
    with open(password_file, "w") as file:
        file.write(default_password)

# Initial state
current_input = ""
locked = True

while True:
    if locked:
        display.show(Image.SKULL)  # Display a skull image to indicate locked state
        
        if button_a.was_pressed():
            current_input += "A"   # Append "A" to current_input upon button A press
            sleep(500)
        elif button_b.was_pressed():
            current_input += "B"   # Append "B" to current_input upon button B press
            sleep(500)

        if len(current_input) >= 8:  # Assuming the password length is fixed at 8 characters
            try:
                # Read the password from the file
                with open(password_file, "r") as file:
                    password = file.read().strip()

                if current_input == password:  # Check if current_input matches the password
                    locked = False
                    display.show(Image.HAPPY)  # Display a happy image upon successful entry
                    sleep(2000)
                    display.clear()
                    sleep(2000)
                    current_input = ""
                else:
                    display.show(Image.SAD)  # Display a sad image to indicate incorrect password
                    sleep(2000)
                    display.clear()
                    current_input = ""
            except OSError as e:
                if e.args[0] == 2:  # OSError code 2 corresponds to file not found
                    display.show(Image.NO)  # Display an error image if the password file is missing
                    sleep(2000)
                    display.clear()
                    current_input = ""
    else:
        display.clear()
        sleep(2000)
        
        locked = True

The code utilizes basic file system operations to check the existence of a password file, create the file if it doesn’t exist, and read the password from the file. Here’s an explanation of the file system operations used in the code:

  1. Checking file existence:
    • The function file_exists(file_name) checks if a file exists in the file system.
    • It attempts to open the file in read mode ("r") using a with statement.
    • If the file can be successfully opened, it means the file exists, and the function returns True.
    • If an OSError occurs during the file opening (e.g., the file doesn’t exist), the function catches the exception and returns False.
  2. Creating the password file:
    • If the password file doesn’t exist, the code enters the if not file_exists(password_file): block.
    • It opens the file in write mode ("w") using a with statement, which ensures proper file handling and automatic file closure.
    • Inside the block, it writes the default password to the file using the write() method.
  3. Reading the password from the file:
    • When the user enters input and it reaches the expected length (len(current_input) >= 8), the code attempts to read the password from the file.
    • It opens the file in read mode ("r") using a with statement.
    • It reads the contents of the file using the read() method, which returns a string containing the password.
    • The strip() method is called to remove any leading or trailing whitespace characters from the password string.

These file system operations rely on the built-in open() function in Python, which provides a convenient way to work with files. The with statement ensures that the file is automatically closed after the operations are completed, even if an exception occurs.

By combining these file system operations with conditionals and display functions, the code implements a password lock functionality using a password file stored on the micro:bit.

To update the password stored in the password.txt file in the file system, you can follow these steps:

  1. Connect the micro:bit to your computer using a USB cable.
  2. Access the micro:bit’s file system. It will appear as a removable storage device on your computer.
  3. Locate the password.txt file on the micro:bit. It should be in the root directory of the micro:bit’s file system.
  4. Open the password.txt file using a text editor on your computer.
  5. Modify the contents of the file to reflect the new password. Delete the existing password and replace it with the new password.
  6. Save the changes to the password.txt file.
  7. Safely disconnect the micro:bit from your computer.

By following these steps, you can update the password stored in the password.txt file. The next time the micro:bit runs the code, it will read the updated password from the file and use it for the password lock functionality.

It’s important to note that when updating the password file, you should ensure the new password follows the same format and length as expected by the code. In the provided code, the password length is assumed to be 8 characters.

If you want a longer password update line:

if len(current_input) >= 8:

Remember to keep the password.txt file secure and only accessible to authorized individuals to maintain the security of the password lock functionality ๐Ÿ™‚