Glossary, Challenges & Resources
A comprehensive guide to terminology used throughout the workshop.
Put your skills to the test with these progressive challenges, organized by difficulty level.
Create a program that cycles through multiple LED blinking patterns. Each pattern should run for a few seconds before switching to the next pattern.
Define each pattern as a separate function. Here's a simple example to get started:
from gpiozero import LED
from time import sleep
red = LED(17)
yellow = LED(27)
green = LED(22)
def pattern_sequential():
for _ in range(3): # Repeat 3 times
red.on()
sleep(0.5)
red.off()
yellow.on()
sleep(0.5)
yellow.off()
green.on()
sleep(0.5)
green.off()
def pattern_alternate():
for _ in range(5): # Repeat 5 times
red.on()
green.on()
yellow.off()
sleep(0.3)
red.off()
green.off()
yellow.on()
sleep(0.3)
yellow.off()
# Main loop that switches patterns
while True:
pattern_sequential()
sleep(1) # Pause between patterns
pattern_alternate()
sleep(1) # Pause between patterns
Try adding a third pattern and use a list to cycle through them!
Create a system that monitors both temperature and light levels, logs the data to a CSV file, and provides visual feedback through LEDs. The system should also track daily highs and lows.
Use the PWMLED class for the blue LED to control brightness based on light level. Here's a structure to get started:
from gpiozero import LED, PWMLED, DigitalInputDevice
from w1thermsensor import W1ThermSensor
import time
import csv
from datetime import datetime
# Setup components
temp_sensor = W1ThermSensor()
light_sensor = DigitalInputDevice(4)
temp_led = LED(17) # Red LED for temperature alerts
light_led = PWMLED(18) # Blue LED with variable brightness
# Thresholds
TEMP_THRESHOLD = 75 # Fahrenheit
# Track daily highs and lows
today = datetime.now().date()
daily_high = -float('inf')
daily_low = float('inf')
# Setup CSV logging
filename = f"environment_log_{today.strftime('%Y%m%d')}.csv"
with open(filename, 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
# Write header if file is new (empty)
if csvfile.tell() == 0:
writer.writerow(['Timestamp', 'Temperature_F', 'Light_Level', 'Daily_High', 'Daily_Low'])
try:
while True:
# Get current time
now = datetime.now()
timestamp = now.strftime('%Y-%m-%d %H:%M:%S')
# Check if it's a new day
current_date = now.date()
if current_date != today:
today = current_date
daily_high = -float('inf')
daily_low = float('inf')
# Create new log file for new day
filename = f"environment_log_{today.strftime('%Y%m%d')}.csv"
with open(filename, 'w', newline='') as new_csvfile:
new_writer = csv.writer(new_csvfile)
new_writer.writerow(['Timestamp', 'Temperature_F', 'Light_Level', 'Daily_High', 'Daily_Low'])
# Read sensors
temp_c = temp_sensor.get_temperature()
temp_f = temp_c * 9/5 + 32
light_level = 0 if light_sensor.value else 1 # Invert because sensor is HIGH in darkness
# Update daily high/low
if temp_f > daily_high:
daily_high = temp_f
if temp_f < daily_low:
daily_low = temp_f
# Control LEDs
if temp_f > TEMP_THRESHOLD:
temp_led.on()
else:
temp_led.off()
light_led.value = light_level # 0.0 to 1.0 brightness
# Log data
writer.writerow([timestamp, f"{temp_f:.2f}", light_level, f"{daily_high:.2f}", f"{daily_low:.2f}"])
csvfile.flush()
# Display in terminal
print(f"{timestamp} | Temp: {temp_f:.2f}°F | Light: {light_level*100:.0f}% | " +
f"High: {daily_high:.2f}°F | Low: {daily_low:.2f}°F")
# Wait for next reading
time.sleep(30)
except KeyboardInterrupt:
print("\nMonitoring stopped")
This is just a starting point. Consider adding more features like time-based triggers or alerts when conditions change rapidly.
Create a comprehensive home monitoring system that integrates multiple sensors, provides a web interface for remote monitoring, and implements adaptive behavior based on environmental conditions and time of day.
This is a complex project. Start by developing each component separately:
Here's a sample structure for the Flask application to get you started:
from flask import Flask, render_template, request, jsonify
import threading
import time
import json
from gpiozero import LED, PWMLED, MotionSensor, Buzzer, DigitalInputDevice
from w1thermsensor import W1ThermSensor
app = Flask(__name__)
# Global variables for sensor data and system state
sensor_data = {
'temperature': 0,
'light_level': 0,
'motion_detected': False,
'last_updated': '',
}
system_state = {
'mode': 'Home', # 'Home', 'Away', 'Night'
'alerts_enabled': True,
'temp_threshold_high': 78,
'temp_threshold_low': 65,
}
# Setup hardware
temp_sensor = W1ThermSensor()
light_sensor = DigitalInputDevice(4)
motion_sensor = MotionSensor(27)
red_led = LED(17)
yellow_led = LED(22)
green_led = LED(23)
buzzer = Buzzer(24)
# Routes for web interface
@app.route('/')
def index():
return render_template('index.html',
sensor_data=sensor_data,
system_state=system_state)
@app.route('/api/data')
def get_data():
return jsonify(sensor_data)
@app.route('/api/set_mode', methods=['POST'])
def set_mode():
data = request.get_json()
system_state['mode'] = data['mode']
return jsonify({'status': 'success'})
# Function to update sensor data in background
def update_sensors():
global sensor_data, system_state
while True:
# Read temperature
temp_c = temp_sensor.get_temperature()
temp_f = temp_c * 9/5 + 32
# Read light level (invert because sensor is HIGH in darkness)
light_level = 0 if light_sensor.value else 1
# Update global data
sensor_data['temperature'] = temp_f
sensor_data['light_level'] = light_level
sensor_data['motion_detected'] = motion_sensor.value
sensor_data['last_updated'] = time.strftime('%Y-%m-%d %H:%M:%S')
# Apply logic based on mode
if system_state['mode'] == 'Home':
home_mode_logic()
elif system_state['mode'] == 'Away':
away_mode_logic()
elif system_state['mode'] == 'Night':
night_mode_logic()
# Log data to file
log_data()
# Sleep until next update
time.sleep(5)
# Mode-specific logic functions
def home_mode_logic():
# Implement home mode behavior
pass
def away_mode_logic():
# Implement away mode behavior
pass
def night_mode_logic():
# Implement night mode behavior
pass
def log_data():
# Implement data logging
pass
# Start the background thread for sensor updates
sensor_thread = threading.Thread(target=update_sensors, daemon=True)
sensor_thread.start()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False)
You'll also need to create HTML templates for the web interface. Consider using Chart.js for simple graphs of sensor data.
Explore these resources to deepen your understanding and expand your Raspberry Pi skills.
Comprehensive official documentation for Raspberry Pi hardware, operating system, and peripherals.
Reference documentation for the GPIO Zero library, with examples and API details for all supported components.
Detailed guide for using the Picamera2 library with the Raspberry Pi Camera Module.
A collection of beginner to advanced projects created by the Raspberry Pi Foundation, with step-by-step instructions.
Extensive collection of Raspberry Pi projects, tutorials, and guides from Adafruit, focusing on electronics and making.
Learn how to create web applications on the Raspberry Pi using Flask, with examples for sensor data visualization and remote control.
A beginner-friendly Python IDE pre-installed on Raspberry Pi OS, with features specifically designed for learning programming.
A simple Python library for creating graphical user interfaces (GUIs) on the Raspberry Pi, with an easy-to-learn API.
A Python library for creating static, animated, and interactive visualizations, perfect for graphing sensor data.