Python is a popular language in the Internet of Things (IoT) ecosystem due to its simplicity and extensive library support. It enables the development of applications that interact with sensors, actuators, and other devices to build IoT solutions.
Using Python on IoT Devices
Python is commonly used on devices like Raspberry Pi and Arduino to control and manage IoT hardware.
Setting Up Python on Raspberry Pi
Install Raspbian OS on the Raspberry Pi.
Python comes pre-installed on Raspbian.
Update Python:
sudo apt update
sudo apt install python3
Example: Blinking an LED with Raspberry Pi
import RPi.GPIO as GPIO
import time
# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
# Blink LED
for _ in range(5):
GPIO.output(18, GPIO.HIGH)
time.sleep(1)
GPIO.output(18, GPIO.LOW)
time.sleep(1)
GPIO.cleanup()
Working with Sensors and Actuators
Python libraries like Adafruit_DHT and smbus allow interaction with various sensors and actuators.
Example: Reading Temperature and Humidity
Install the Adafruit_DHT library:
pip install Adafruit_DHT
import Adafruit_DHT
# Sensor type and GPIO pin
sensor = Adafruit_DHT.DHT22
pin = 4
# Read data
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print(f"Temp: {temperature:.1f} C Humidity: {humidity:.1f}%")
else:
print("Failed to retrieve data from the sensor")
Example: Controlling a Servo Motor
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
# Set up PWM
pwm = GPIO.PWM(18, 50) # 50 Hz
pwm.start(0)
# Rotate servo
pwm.ChangeDutyCycle(7) # Middle position
time.sleep(1)
pwm.ChangeDutyCycle(12) # Right position
time.sleep(1)
pwm.ChangeDutyCycle(2) # Left position
time.sleep(1)
pwm.stop()
GPIO.cleanup()
IoT Protocols
IoT devices communicate using protocols like MQTT and HTTP.
MQTT with Python
Install the paho-mqtt library:
pip install paho-mqtt
Example: Publish and Subscribe
import paho.mqtt.client as mqtt
# Callback for when a message is received
def on_message(client, userdata, message):
print(f"Received message: {message.payload.decode()}")
# Connect to broker
client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
# Subscribe to topic
client.subscribe("test/topic")
# Publish a message
client.publish("test/topic", "Hello, MQTT")
# Loop forever
client.loop_forever()
Building an IoT Project
Example: Home Automation System
Sensors: Read temperature and humidity.
Actuators: Control a fan and light.
Server: Send data to a cloud server using HTTP.
Example Code:
import requests
import Adafruit_DHT
import RPi.GPIO as GPIO
# Set up GPIO and sensor
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT) # Fan
sensor = Adafruit_DHT.DHT22
pin = 4
# Read data
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if temperature > 30:
GPIO.output(18, GPIO.HIGH) # Turn on fan
else:
GPIO.output(18, GPIO.LOW) # Turn off fan
# Send data to server
payload = {"temperature": temperature, "humidity": humidity}
response = requests.post("http://example.com/api/data", json=payload)
print(response.status_code)
GPIO.cleanup()
Exercises
Exercise 1: Monitor Temperature
Write a script to monitor temperature and print an alert if it exceeds 35°C.
Solution:
import Adafruit_DHT
sensor = Adafruit_DHT.DHT22
pin = 4
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if temperature > 35:
print("Alert! High temperature detected.")
Exercise 2: Automate LED Control
Write a script to turn an LED on or off based on user input.
Solution:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
while True:
command = input("Enter 'on' to turn on LED, 'off' to turn off, 'quit' to exit: ").strip().lower()
if command == "on":
GPIO.output(18, GPIO.HIGH)
elif command == "off":
GPIO.output(18, GPIO.LOW)
elif command == "quit":
break
GPIO.cleanup()
Best Practices
Use proper GPIO cleanup to avoid pin conflicts.
Secure IoT devices with firewalls and encrypted communication.
Test sensor and actuator configurations thoroughly.
Follow energy-efficient practices for battery-powered devices.
Document hardware setups and code for reproducibility.
In the next chapter, we will explore Python appendices, including cheat sheets, glossaries, and recommended resources to deepen your Python knowledge.