💡 Level 1 – Fundamentals

Project 1.7: "Digital Sensors"

🚀 Project 1.7 – Digital Sensors


🎯 What You’ll Learn

  • ✅ Goal 1: Read button states.
  • ✅ Goal 2: Control LEDs and motors with button input.
  • ✅ Goal 3: Handle bouncing and create counters.

Key Ideas

  • Digital input: Detect HIGH/LOW from a button.
  • Digital output: Control LEDs or motors.
  • Logic: Use button state to trigger actions.

🧱 Blocks Glossary (used in this project)

  • pinX = machine.Pin(X, machine.Pin.IN) → Button input.
  • pinX = machine.Pin(X, machine.Pin.IN, machine.Pin.PULL_UP) → Button input with pull‑up.
  • pinX = machine.Pin(X, machine.Pin.OUT) → LED or motor output.
  • pinX.value() → Read pin state.
  • pinX.value(1) → Set pin HIGH (ON).
  • pinX.value(0) → Set pin LOW (OFF).
  • while True: → Infinite loop.
  • time.sleep() → Delay.

🧰 What You Need

PartHow many?Pin connection
D1 R321USB cable
Push Button2Pin 2, Pin 4
LED1Pin 5

🔌 Wiring tip: Connect button one to pin 2, button two to pin 4, LED to pin 5.
📍 Pin map snapshot: Pin 2/4 = buttons, Pin 5 = LED.


✅ Before You Start

  • USB cable connected
  • Buttons wired correctly
  • Test print shows:
print("Ready!")  # Confirm serial is working

🎮 Microprojects (5 Mini Missions)


🎮 Microproject 1.7.1 – Reading button status

Blocks used: Digital input, Serial print
Block sequence:

  1. Setup button pin as input
  2. Read value
  3. Print state

MicroPython Code:

import machine, time                          # Import modules

pin2 = machine.Pin(2, machine.Pin.IN)         # Pin 2 as input for button

while True:                                   # Infinite loop
    state = pin2.value()                      # Read button state (0 or 1)
    print("Button state:", state)             # Serial log of button state
    time.sleep(0.5)                           # Delay for readability

Reflection: Button state is read continuously.
Challenge: Try changing the pin to 4 for the second button.


🎮 Microproject 1.7.2 – Button‑controlled LED

Blocks used: Digital input, Digital output
Block sequence:

  1. Setup button pin as input
  2. Setup LED pin as output
  3. If button pressed → LED ON

MicroPython Code:

import machine, time                          # Import modules

pin2 = machine.Pin(2, machine.Pin.IN)         # Pin 2 as input for button
pin5 = machine.Pin(5, machine.Pin.OUT)        # Pin 5 as output for LED

while True:                                   # Infinite loop
    if pin2.value() == 1:                     # If button pressed
        pin5.value(1)                         # Turn LED ON
        print("LED ON")                       # Serial log
    else:                                     # If button not pressed
        pin5.value(0)                         # Turn LED OFF
        print("LED OFF")                      # Serial log
    time.sleep(0.2)                           # Delay for stability

Reflection: LED responds to button press.
Challenge: Add a second button to control LED OFF.


🎮 Microproject 1.7.3 – Heart rate counter

Blocks used: Digital input, Counter, Serial print
Block sequence:

  1. Setup button pin as input
  2. Count presses
  3. Print count

MicroPython Code:

import machine, time                          # Import modules

pin2 = machine.Pin(2, machine.Pin.IN)         # Pin 2 as input for button
count = 0                                     # Initialize counter

while True:                                   # Infinite loop
    if pin2.value() == 1:                     # If button pressed
        count += 1                            # Increase counter
        print("Heart rate count:", count)     # Serial log of count
        time.sleep(0.5)                       # Delay to avoid double count

Reflection: Button press increments counter.
Challenge: Try counting for 10 seconds and calculate beats per minute.


🎮 Microproject 1.7.4 – Anti‑bounce software

Blocks used: Digital input, Delay
Block sequence:

  1. Setup button pin as input
  2. Add delay after press
  3. Prevent multiple counts

MicroPython Code:

import machine, time                          # Import modules

pin2 = machine.Pin(2, machine.Pin.IN)         # Pin 2 as input for button
count = 0                                     # Initialize counter

while True:                                   # Infinite loop
    if pin2.value() == 1:                     # If button pressed
        count += 1                            # Increase counter
        print("Count:", count)                # Serial log
        time.sleep(0.3)                       # Delay prevents bouncing

Reflection: Delay reduces false counts.
Challenge: Try adjusting delay to 0.1s or 0.5s.


🎮 Microproject 1.7.5 – Motor control with button

Blocks used: Digital input, Digital output, PWM
Block sequence:

  1. Setup button pin as input
  2. Setup motor pins as output + PWM
  3. If button pressed → Motor ON

MicroPython Code:

import machine, time                          # Import modules

pin2 = machine.Pin(2, machine.Pin.IN)         # Pin 2 as input for button
pin12 = machine.Pin(12, machine.Pin.OUT)      # Motor IN3 output
pin13 = machine.Pin(13, machine.Pin.OUT)      # Motor IN4 output
pwm14 = machine.PWM(machine.Pin(14))          # Motor ENB PWM

pwm14.freq(2000)                              # Set PWM frequency
pwm14.duty(0)                                 # Start with motor OFF

while True:                                   # Infinite loop
    if pin2.value() == 1:                     # If button pressed
        pin12.value(1)                        # Motor forward IN3 HIGH
        pin13.value(0)                        # Motor forward IN4 LOW
        pwm14.duty(512)                       # Motor speed 50%
        print("Motor ON")                     # Serial log
    else:                                     # If button not pressed
        pwm14.duty(0)                         # Motor OFF
        print("Motor OFF")                    # Serial log
    time.sleep(0.2)                           # Delay for stability

Reflection: Button press controls motor.
Challenge: Add second button to reverse motor direction.


✨ Main Project – Digital Sensors

🔧 Blocks Steps (with glossary)

  • Digital input: Read button state.
  • Digital output: Control LED or motor.
  • Logic: Use button state for actions.

Block sequence:

  1. Setup pins for buttons and outputs.
  2. Read button state.
  3. Control LED or motor.
  4. Add counter and anti‑bounce.

MicroPython Code (mirroring blocks):

# Project 1.7 – Digital Sensors

import machine, time                          # Import required modules

pin2 = machine.Pin(2, machine.Pin.IN)         # Pin 2 input for button
pin5 = machine.Pin(5, machine.Pin.OUT)        # Pin 5 output for LED

count = 0                                     # Initialize counter

while True:                                   # Infinite loop
    if pin2.value() == 1:                     # If button pressed
        pin5.value(1)                         # LED ON
        count += 1                            # Increase counter
        print("LED ON, Count:", count)        # Serial log
        time.sleep(0.3)                       # Anti‑bounce delay
    else:                                     # If button not pressed
        pin5.value(0)                         # LED OFF
        print("LED OFF")                      # Serial log
        time.sleep(0.1)                       # Short delay

 

📖 External Explanation

This project shows how to use buttons as digital sensors.

  • Inputs detect button presses.
  • Outputs respond with LEDs or motors.
  • Counters and delays handle bouncing and measure events.
  • By combining these, students learn how sensors trigger actions in robotics.

✨ Story Time

Imagine your robot as a game controller 🎮. Each button press lights up an LED, starts a motor, or counts a heartbeat. With anti‑bounce, the robot avoids mistakes and responds smoothly, just like a professional device.


🕵️ Debugging (2 Common Problems)

🐞 Debugging 1.7.A – Inverted button state

Problem: Button reads pressed when it is not pressed.
Clues: Pull‑up or pull‑down resistor not set correctly.
Broken code:

pin2 = machine.Pin(2, machine.Pin.IN)         # Input without pull-up/down

Fixed code:

pin2 = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP)  # Correct pull-up

Why it works: Adding a pull‑up ensures the button reads HIGH only when pressed.
Avoid next time: Always check if your button wiring requires pull‑up or pull‑down.


🐞 Debugging 1.7.B – Uncontrolled rebounds

Problem: Button press counts multiple times.
Clues: Mechanical bounce causes repeated signals.
Broken code:

if pin2.value() == 1:
    count += 1
    print("Count:", count)

Fixed code:

if pin2.value() == 1:
    count += 1
    print("Count:", count)
    time.sleep(0.3)   # Anti-bounce delay

Why it works: Adding a short delay filters out bounce signals.
Avoid next time: Always include anti‑bounce logic when counting button presses.


✅ Final Checklist

  • Button state read correctly.
  • LED controlled by button.
  • Counter increments with presses.
  • Anti‑bounce implemented.
  • Motor controlled by button.

📚 Extras

  • 🧠 Student tip: Try combining two buttons—one for ON and one for OFF.
  • 🧑‍🏫 Instructor tip: Demonstrate bounce by showing rapid counts without delay.
  • 📖 Glossary: Digital input, pull‑up, bounce, counter.
  • 💡 Mini tip: Always test button state with print() before connecting to outputs.
On this page