Python
  • Intro.
  • Catalogue
  • Chapter 1: Introduction to Python
  • Chapter 2: Python Syntax and Fundamentals
    • Chapter: Variables and Data Types in Python
  • Chapter 3: Control Flow
  • Chapter 4: Functions
  • Chapter 5: Data Structures
  • Chapter 6: Object-Oriented Programming (OOP)
  • Chapter 7: Modules and Packages
  • Chapter 8: File Handling
  • Chapter 9: Error and Exception Handling
  • Chapter 10: Working with Databases
  • Chapter 11: Iterators and Generators
  • Chapter 12: Decorators and Context Managers
  • Chapter 13: Concurrency and Parallelism
  • Chapter 14: Testing and Debugging
  • Chapter 15: Web Development with Python
  • Chapter 16: Data Science and Machine Learning with Python
  • Chapter 17: Working with APIs
  • Chapter 18: Automation with Python
  • Chapter 19: Python and Cloud/DevOps
  • Chapter 20: Python and IoT
  • Appendices
Powered by GitBook
On this page

Chapter 20: Python and IoT

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

  1. Install Raspbian OS on the Raspberry Pi.

  2. Python comes pre-installed on Raspbian.

  3. 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

  1. Sensors: Read temperature and humidity.

  2. Actuators: Control a fan and light.

  3. 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

  1. Use proper GPIO cleanup to avoid pin conflicts.

  2. Secure IoT devices with firewalls and encrypted communication.

  3. Test sensor and actuator configurations thoroughly.

  4. Follow energy-efficient practices for battery-powered devices.

  5. 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.

PreviousChapter 19: Python and Cloud/DevOpsNextAppendices

Last updated 5 months ago