๐Ÿ”ฆ Level 2 โ€“ Sensors & IR Control

Project 2.5: "Alarm with Crash Switch"

๐Ÿš€ Project 2.5 โ€“ Alarm with Crash Switch

๐ŸŽฏ What Youโ€™ll Learn

  • โœ… Goal 1: Detect collisions using a crash switch (press sensor).
  • โœ… Goal 2: Trigger alarms with LED and buzzer.
  • โœ… Goal 3: Log events and build a simple safety system.

Key Ideas

  • Short definition: A crash switch changes from 0 to 1 when pressed, which we use to detect impacts.
  • Real-world link: Robots and machines use impact sensors to pause, alert, or protect themselves.

๐Ÿงฑ Blocks Glossary (used in this project)

  • Digital input: Robot reads a pin as 0 or 1 to detect a press.
  • Digital output: Robot turns a pin ON or OFF for LED or devices.
  • Serial print: Robot sends messages to your computer screen.
  • if / else: The robot makes a decision based on sensor state.
  • Loop: Repeat the check forever to catch crashes as they happen.
  • Delay: Pause time to make behavior stable and readable.

๐Ÿงฐ What You Need

PartHow many?Pin connection
D1 R321USB cable (30 cm)
Crash switch1Pin 2 (digital input)
LED1Pin 5 (digital output)
Buzzer1Pin 26 (music output)

๐Ÿ”Œ Wiring tip: Connect one side of the crash switch to pin 2 and the other side to GND.
๐Ÿ“ Pin map snapshot: Pin 2 (input), Pin 5 (LED), Pin 26 (buzzer). Others unused.


โœ… Before You Start

  • USB cable is plugged in
  • Serial monitor is open
  • Test print shows:
print("Ready!")  # Confirm serial is working

๐ŸŽฎ Microprojects (5 Mini Missions)

๐ŸŽฎ Microproject 2.5.1 โ€“ Simple impact detection

Goal: Read the crash switch and print its state.
Blocks used:

  • Digital input: Read pin 2 (0/1).
  • Serial print: Show state on screen.

Block sequence:

  1. Setup pin 2 as input
  2. Read state
  3. Print state
  4. Repeat

MicroPython Code:

# Simple impact detection (print state)

import machine, time                          # Import pin control and time

pin2 = machine.Pin(2, machine.Pin.IN)         # Set pin 2 as digital input for crash switch

print("Crash switch detection ready")         # Serial start message

while True:                                   # Loop forever to keep checking
    state = pin2.value()                      # Read the input: 0 (no press) or 1 (pressed)
    print("Crash state:", state)              # Print the current state
    time.sleep(0.2)                           # Small delay to make output readable

Reflection: You can see when the crash switch is pressed (1) or not (0).
Challenge:

  • Easy: Print โ€œIMPACT!โ€ only when state is 1.
  • Harder: Print โ€œSafeโ€ when 0 and โ€œImpactโ€ when 1.

๐ŸŽฎ Microproject 2.5.2 โ€“ Collision alarm (LED + buzzer)

Goal: Turn ON LED and play a beep when an impact is detected.
Blocks used:

  • Digital input: Read pin 2.
  • Digital output: Control LED on pin 5.
  • Music output: Play beep on pin 26.

Block sequence:

  1. Setup input and outputs
  2. If pressed โ†’ LED ON + beep
  3. Else โ†’ LED OFF
  4. Repeat

MicroPython Code:

# Collision alarm (LED + buzzer)

import machine, time, music                   # Import pin control, time, and music

pin2 = machine.Pin(2, machine.Pin.IN)         # Crash switch input on pin 2
pin5 = machine.Pin(5, machine.Pin.OUT)        # LED output on pin 5
midi = music.MIDI(26)                         # Buzzer output on pin 26 (music interface)

print("Collision alarm ready")                # Serial start message

while True:                                   # Infinite loop to monitor continuously
    if pin2.value() == 1:                     # If crash detected (pressed)
        pin5.value(1)                         # Turn LED ON
        midi.pitch_time(440, 150)             # Play short beep at 440 Hz for 150 ms
        print("IMPACT DETECTED!")             # Serial alert message
    else:                                     # If not pressed
        pin5.value(0)                         # Turn LED OFF
    time.sleep(0.1)                           # Short delay to keep response snappy

Reflection: The alarm reacts instantly to a press with light and sound.
Challenge:

  • Easy: Use 523 Hz for a higher beep.
  • Harder: Make two beeps when pressed (ta-ta).

๐ŸŽฎ Microproject 2.5.3 โ€“ Impact counter (simple tally)

Goal: Count how many times an impact happens and print the total.
Blocks used:

  • Digital input: Read pin 2.
  • Variable: Store the count.
  • Serial print: Show count after each new impact.

Block sequence:

  1. Setup input
  2. Create counter variable
  3. Detect change from 0 โ†’ 1
  4. Increase counter and print

MicroPython Code:

# Impact counter (count presses)

import machine, time                          # Import pin control and time

pin2 = machine.Pin(2, machine.Pin.IN)         # Crash switch input on pin 2

count = 0                                     # Counter starts at 0
last = 0                                      # Last state starts at 0 (not pressed)

print("Impact counter ready")                 # Serial start message

while True:                                   # Loop forever
    state = pin2.value()                      # Read current state
    if state == 1 and last == 0:              # Detect rising edge: just pressed
        count = count + 1                     # Increase counter by 1
        print("Impact count:", count)         # Print the new count
        time.sleep(0.15)                      # Small debounce delay
    last = state                              # Update last state for next loop
    time.sleep(0.05)                          # Fast scan for responsive counting

Reflection: You track how many impacts happened, not just the current state.
Challenge:

  • Easy: Reset the counter to 0 when it reaches 10.
  • Harder: Add a second LED blink every 5 impacts.

๐ŸŽฎ Microproject 2.5.4 โ€“ Different sounds by impact

Goal: Play short or long beep depending on tap strength (simulated by duration).
Blocks used:

  • Digital input: Read pin 2.
  • Music output: Play beeps.

Block sequence:

  1. Wait for press start
  2. Measure how long it stays pressed
  3. Short press โ†’ short beep
  4. Long press โ†’ longer beep

MicroPython Code:

# Different sounds by impact (press duration)

import machine, time, music                   # Import pin control, time, and music

pin2 = machine.Pin(2, machine.Pin.IN)         # Crash switch input on pin 2
midi = music.MIDI(26)                         # Buzzer on pin 26

print("Impact sound mapping ready")           # Serial start message

while True:                                   # Continuous monitoring loop
    if pin2.value() == 1:                     # If pressed now
        start = time.ticks_ms()               # Record start time in milliseconds
        while pin2.value() == 1:              # Keep looping while still pressed
            time.sleep(0.01)                  # Tiny delay to avoid busy waiting
        duration = time.ticks_diff(time.ticks_ms(), start)  # Compute press time
        print("Press duration (ms):", duration)             # Show duration
        if duration < 200:                    # If short press (under 200 ms)
            midi.pitch_time(440, 150)         # Play short beep
            print("Short impact beep")        # Serial confirmation
        else:                                 # If long press (200 ms or more)
            midi.pitch_time(440, 400)         # Play long beep
            print("Long impact beep")         # Serial confirmation
    time.sleep(0.05)                          # Scan frequently for new presses

Reflection: Press length changes the sound, adding meaning to different impacts.
Challenge:

  • Easy: Use 523 Hz for long presses to make them sound different.
  • Harder: Add LED ON during press and OFF after release.

๐ŸŽฎ Microproject 2.5.5 โ€“ Antiโ€‘collision system (stop + alert)

Goal: Stop action when an impact is detected and show an alert until safe.
Blocks used:

  • Digital input: Read pin 2.
  • Digital output: LED on pin 5.
  • Serial print: Status messages (STOP or SAFE).

Block sequence:

  1. Read crash switch
  2. If pressed โ†’ STOP and alert
  3. If safe โ†’ CLEAR alert
  4. Repeat

MicroPython Code:

# Anti-collision system (STOP when impact)

import machine, time                          # Import pin control and time

pin2 = machine.Pin(2, machine.Pin.IN)         # Crash switch input on pin 2
pin5 = machine.Pin(5, machine.Pin.OUT)        # LED output on pin 5

print("Anti-collision ready")                 # Serial start message

while True:                                   # Continuous loop
    if pin2.value() == 1:                     # If crash detected
        pin5.value(1)                         # Turn LED ON (alert)
        print("STOP: Impact detected")        # Print STOP message
        time.sleep(0.2)                       # Hold alert briefly
    else:                                     # If safe
        pin5.value(0)                         # Turn LED OFF (clear alert)
        print("SAFE: No impact")              # Print SAFE message
        time.sleep(0.2)                       # Small delay for readability

Reflection: The system clearly shows STOP on impact and SAFE when clear.
Challenge:

  • Easy: Blink LED twice when impact detected.
  • Harder: Add buzzer beep only on first detection (not continuously).

โœจ Main Project โ€“ Crash Alarm System

๐Ÿ”ง Blocks Steps (with glossary)

  • Digital input: Read crash switch (pressed or not).
  • Digital output: LED shows alarm state.
  • Music output: Buzzer plays warning tones.
  • Serial print: Clear messages for STOP and SAFE.
  • Loop: Continuous monitoring to catch impacts live.

Block sequence:

  1. Setup input (pin 2) and outputs (pin 5, pin 26)
  2. Read crash switch
  3. If pressed โ†’ LED ON + warning beep + โ€œSTOPโ€ serial
  4. If not pressed โ†’ LED OFF + โ€œSAFEโ€ serial
  5. Repeat loop

๐Ÿ MicroPython Code (mirroring blocks)

# Project 2.5 โ€“ Alarm with Crash Switch (Main Project)

import machine, time, music                   # Import pin control, time, and music

pin2 = machine.Pin(2, machine.Pin.IN)         # Crash switch input on pin 2
pin5 = machine.Pin(5, machine.Pin.OUT)        # LED output on pin 5
midi = music.MIDI(26)                         # Buzzer output on pin 26

print("Crash Alarm Main ready")               # Serial start message

while True:                                   # Infinite loop to monitor continuously
    state = pin2.value()                      # Read crash switch: 0 (safe) or 1 (impact)
    if state == 1:                            # If impact detected
        pin5.value(1)                         # LED ON (alarm)
        midi.pitch_time(440, 200)             # Warning beep (440 Hz, 200 ms)
        print("STOP: Impact detected")        # Serial STOP message
        time.sleep(0.2)                       # Short delay to avoid spam
    else:                                     # If safe
        pin5.value(0)                         # LED OFF
        print("SAFE: No impact")              # Serial SAFE message
        time.sleep(0.2)                       # Short delay for readability

๐Ÿ“– External Explanation

  • What it teaches: You built a practical safety alarm that reacts to impacts with light, sound, and messages.
  • Why it works: The crash switch gives a reliable 0/1 reading; if itโ€™s pressed, the program triggers alarms and prints STOP; if not, it prints SAFE and turns the LED OFF.
  • Key concept: Inputs change outputs โ€” sensors drive decisions.

โœจ Story Time

Your robot is now a careful driver. If it bumps into something, it stops and flashes a warning. When the path is clear, it relaxes and turns the light off. Safety first, hero second.


๐Ÿ•ต๏ธ Debugging (2 Common Problems)

๐Ÿž Debugging 2.5.A โ€“ Overly sensitive detection

Problem: Alarm triggers too easily or keeps blinking.
Clues: Rapid STOP/SAFE messages in serial.
Broken code:

time.sleep(0.01)  # Too fast, causes noisy readings

Fixed code:

time.sleep(0.2)   # Reasonable delay to filter noise and bouncing

Why it works: A small delay reduces false triggers and switch bounce.
Avoid next time: Add a short debounce delay after each detection.


๐Ÿž Debugging 2.5.B โ€“ Does not detect minor impacts

Problem: Light taps are not detected.
Clues: State stays at 0 even when tapped.
Broken code:

if pin2.value() == 1:   # Only checks pressed, misses short taps
    print("Impact")

Fixed code:

last = 0                                # Track last state
state = pin2.value()                     # Read current state
if state == 1 and last == 0:             # Catch rising edge (just pressed)
    print("Impact detected")             # Log the event
last = state                             # Update last state

Why it works: Edge detection captures quick taps that a simple pressed check might miss.
Avoid next time: Use a short debounce and track state changes.


โœ… Final Checklist

  • I saw โ€œSTOP: Impact detectedโ€ when pressing the switch.
  • I saw โ€œSAFE: No impactโ€ when releasing the switch.
  • The LED matched the serial messages.
  • My beep played on impact.
  • My challenge changes worked (double beep or LED blink).

๐Ÿ“š Extras

  • ๐Ÿง  Student tip: Add a โ€œsafe modeโ€ light pulse every 2 seconds when no impact happens.
  • ๐Ÿง‘โ€๐Ÿซ Instructor tip: Demonstrate mechanical switch bounce and why we add short delays.
  • ๐Ÿ“– Glossary: Crash switch (press sensor), debounce (filtering noisy presses), rising edge (0 to 1 change).
  • ๐Ÿ’ก Mini tips:
    • Pins: Use Pin numbers (like 2, 5, 26).
    • Delays: Small delays help stabilize sensors.
    • Serial: Print short messages students can read fast.
On this page