Intermediate Level • Lesson 5

📡 Reading Sensors

⏱️ 50 minutes 📚 Intermediate 🎯 Sensor Input
📡

Reading Sensors

Learn how to read input from buttons and sensors - this lets your programs interact with the real world!

What are Sensors?

Sensors are devices that detect things in the real world - like temperature, light, sound, or movement. They send information to your Raspberry Pi so your program can react to what's happening around it!

💡 Real-World Example: Your phone has many sensors - it knows when you tilt it (gyroscope), how bright it is (light sensor), and when you touch the screen (touch sensor). Your Raspberry Pi can use similar sensors!

GPIO Pins: Input vs Output

GPIO pins can be used in two ways:

📤

Output

Send signals OUT (like turning LEDs on/off)

GPIO.setup(pin, GPIO.OUT)

📥

Input

Read signals IN (like reading button presses)

GPIO.setup(pin, GPIO.IN)

Reading Button Input

Buttons are the simplest input device. When you press a button, it connects two wires, sending a signal to your Raspberry Pi.

Basic Button Setup

import RPi.GPIO as GPIO import time # Set up button on GPIO 2 GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Read button state button_state = GPIO.input(2) if button_state == GPIO.LOW: print("Button is pressed!") else: print("Button is not pressed")

Understanding the Code:

  • GPIO.IN: Sets the pin as an input (for reading)
  • GPIO.PUD_UP: Enables pull-up resistor (keeps pin HIGH when button not pressed)
  • GPIO.input(2): Reads the current state of pin 2
  • GPIO.LOW: Means button is pressed (connected to ground)
  • GPIO.HIGH: Means button is not pressed

Button Wiring

How to Wire a Button:

  1. One side of button: Connect to GPIO pin (e.g., GPIO 2)
  2. Other side of button: Connect to GND (ground)
  3. Pull-up resistor: Use GPIO.PUD_UP in code (built-in on Raspberry Pi)

Note: When button is not pressed, pin reads HIGH. When pressed, it connects to GND and reads LOW.

Reading Button in a Loop

To continuously check if a button is pressed, use a loop:

Continuous Button Reading

import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(18, GPIO.OUT) # LED try: while True: button_state = GPIO.input(2) if button_state == GPIO.LOW: GPIO.output(18, GPIO.HIGH) # Turn LED on print("Button pressed - LED ON") else: GPIO.output(18, GPIO.LOW) # Turn LED off print("Button not pressed - LED OFF") time.sleep(0.1) # Check every 0.1 seconds except KeyboardInterrupt: GPIO.cleanup()

Reading Analog Sensors

Some sensors give analog values (like temperature or light level). Raspberry Pi GPIO pins are digital, so we need special techniques:

🌡️

Temperature Sensors

DS18B20 (digital) or DHT11/DHT22 (digital)

Read temperature values

💡

Light Sensors

LDR (Light Dependent Resistor)

Detect light levels

📏

Distance Sensors

Ultrasonic (HC-SR04)

Measure distance

Project: Interactive Button-Controlled LED System

Let's build a system where pressing a button controls an LED!

Materials Needed:

  • Raspberry Pi
  • Push button
  • LED (any color)
  • Resistor (220Ω for LED, 10kΩ for button - optional)
  • Breadboard and jumper wires

Wiring Instructions:

  1. Button: One side to GPIO 2, other side to GND
  2. LED: Long leg to GPIO 18 via resistor, short leg to GND
  3. Make sure all connections are secure

The Complete Code:

import RPi.GPIO as GPIO import time # Set up GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button GPIO.setup(18, GPIO.OUT) # LED # Keep track of LED state led_on = False try: print("Press the button to toggle the LED. Press Ctrl+C to exit.") while True: button_state = GPIO.input(2) # Check if button is pressed (goes LOW) if button_state == GPIO.LOW: # Toggle LED state led_on = not led_on if led_on: GPIO.output(18, GPIO.HIGH) print("LED turned ON") else: GPIO.output(18, GPIO.LOW) print("LED turned OFF") # Wait a bit to avoid multiple toggles from one press time.sleep(0.3) time.sleep(0.05) # Small delay to prevent too much CPU usage except KeyboardInterrupt: GPIO.output(18, GPIO.LOW) GPIO.cleanup() print("\nProgram stopped!")

Understanding the Code:

  • led_on variable: Tracks whether LED is currently on or off
  • not led_on: Toggles the state (True becomes False, False becomes True)
  • time.sleep(0.3): Prevents the button from toggling multiple times from one press (debouncing)
  • The loop continuously checks the button and toggles the LED when pressed

Debouncing

When you press a button, it might "bounce" - quickly turning on and off multiple times. This is called "bounce" and can cause your program to think the button was pressed many times. We fix this with a small delay after detecting a press - this is called "debouncing".

💡 Tip: Always add a small delay (like 0.2-0.3 seconds) after detecting a button press to prevent multiple triggers from one press!

Common Mistakes to Avoid

⚠️ Watch Out For:

  • Wrong Pin Mode: Make sure to use GPIO.IN for inputs, not GPIO.OUT
  • Missing Pull-up: Use GPIO.PUD_UP to prevent floating pins
  • No Debouncing: Add a delay after button press to prevent multiple triggers
  • Wrong Logic: Remember LOW means pressed when using PUD_UP
  • Forgetting Cleanup: Always call GPIO.cleanup() when done

Summary

You've learned:

  • ✅ Sensors let your program detect the real world
  • ✅ GPIO pins can be inputs (read) or outputs (write)
  • ✅ Use GPIO.IN to set a pin as input
  • ✅ Use GPIO.input(pin) to read the pin state
  • ✅ Buttons read LOW when pressed (with PUD_UP)
  • ✅ Always add debouncing delay to prevent multiple triggers
  • ✅ You can combine inputs and outputs to create interactive systems
🎉 Great Progress! You can now read input from the real world! In the next lesson, you'll learn to display information on screens.

🎮 Try It: Practice Reading Inputs!

Practice writing code to read sensors. Try these challenges:

📝 Challenge 1: Simple Button Check

Write code that reads a button on GPIO 2 and prints "Pressed" or "Not Pressed":

📝 Challenge 2: Button Counter

Write code that counts how many times a button is pressed:

💡 Tip: Remember to use GPIO.IN for reading, GPIO.PUD_UP for pull-up resistor, and add debouncing delays!

🎯 Activity: Interactive Button-Controlled LED System

What You'll Build:

Create a system where pressing a button toggles an LED on and off!

Step-by-Step Instructions:

  1. Wire the Button: Connect button between GPIO 2 and GND
  2. Wire the LED: Connect LED to GPIO 18 with resistor
  3. Write the Code: Use the example code from the Learn tab
  4. Test: Press the button and watch the LED toggle
  5. Experiment: Try changing the debounce delay time
  6. Enhance: Add a second button to control a second LED

Testing Checklist:

  • ✅ LED turns on when button is pressed first time
  • ✅ LED turns off when button is pressed second time
  • ✅ Button doesn't trigger multiple times from one press
  • ✅ Program stops cleanly with Ctrl+C
🏆 Bonus Challenge: Can you create a system with two buttons - one to turn LED on, another to turn it off?

💪 Practice Challenges

Challenge 1: Button State Monitor

Write code that continuously monitors a button and prints its state every second:

# Should print "Button: Pressed" or "Button: Not Pressed" every second

Challenge 2: Press Counter

Create a program that counts button presses and displays the count. Reset the count when it reaches 10:

# Count presses, print count each time # When count reaches 10, reset to 0 and print "Reset!"

Challenge 3: Hold to Light

Create a system where the LED only stays on while the button is held down:

# LED should be ON when button is pressed # LED should be OFF when button is released

Challenge 4: Double Button Control

Use two buttons to control one LED:

  • Button 1 (GPIO 2): Turn LED on
  • Button 2 (GPIO 3): Turn LED off

Challenge 5: Code Detective

What's wrong with this code? Find and fix the mistakes!

import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.OUT) # Should this be OUT? button = GPIO.input(2) if button == True: print("Pressed")
Click to see the answer
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Fixed: use IN, add PUD_UP button = GPIO.input(2) if button == GPIO.LOW: # Fixed: use GPIO.LOW, not True print("Pressed") GPIO.cleanup() # Added: cleanup