Internet of Things with Python (original) (raw)

favouredInternet of Things (IoT) is transforming how we interact with technology, integrating it into every facet of our lives. Here are some key reasons why IoT is so important:

Python for IoT

Python is favoured for IoT due to its simplicity, readability, and a rich ecosystem of libraries. Python is a popular choice for developing Internet of Things (IoT) applications due to several compelling advantages:

Python Libraries for IoT

Platform Use Case
Raspberry Pi Full Linux-based IoT projects
Arduino + PyFirmata Hardware control through Python
ESP8266 Wi-Fi enabled IoT devices
ESP32 Wi-Fi + Bluetooth IoT applications

Python on Raspberry Pi

Raspberry Pi is a IoT platform that combines computing capabilities, GPIO support and Python compatibility, enabling the development of connected and automated systems. It's a low-cost, credit-card-sized computer that plugs into a computer monitor or TV and uses a standard keyboard and mouse.

**Example: The following code uses the GPIO Zero library to control an LED using a push button connected to a Raspberry Pi. When the button is pressed, the LED turns on, and when the button is released, the LED turns off.

Python `

from gpiozero import LED, Button from signal import pause

led = LED(17) button = Button(2)

button.when_pressed = led.on button.when_released = led.off

pause()

`

**Output

Pressing the button lights up the LED connected to the Raspberry Pi. Releasing the button turns the LED off.

**Explanation:

Control Arduino with Python and pyFirmata

Python and pip should be Installed in your system. Then you can run the following command to install the PyFirmata module in your system.

pip install pyFirmata

Upload StandardFirmata to Arduino

Before running Python code with PyFirmata, the StandardFirmata sketch must be uploaded to the Arduino board. StandardFirmata acts as a bridge, allowing Python programs to communicate with and control Arduino pins.

**Step 1: Connect the Arduino

Connect the Arduino board to your computer using a USB cable.

**Step 2: Identify the Serial Port

Find the port assigned to the Arduino:

**Step 3: Open StandardFirmata

Launch the Arduino IDE and open the StandardFirmata example:

File → Examples → Firmata → StandardFirmata

**Step 4: Select the Board and Port

Click the Upload button in the Arduino IDE to upload the StandardFirmata sketch to the board. Once the upload is complete, the Arduino is ready to receive commands from Python through the PyFirmata library.

Lightbox

Connections:

Connect four LEDs to Arduino digital pins 10, 11, 12, and 13 as shown in the circuit diagram. Each LED should be connected through an appropriate current-limiting resistor.

Implementation

Python `

from pyfirmata import Arduino from time import sleep

board = Arduino("COM8")

leds = [ board.get_pin("d:13:o"), board.get_pin("d:12:o"), board.get_pin("d:11:o"), board.get_pin("d:10:o") ]

while True: for num in range(16):

    binary = f"{num:04b}"

    for led, bit in zip(leds, binary):
        led.write(int(bit))

    print(binary)
    sleep(1)

`

**Output:

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
...

Here is the Simulation Output:

**Explanation:

ESP8266 and ESP32 with MicroPython

ESP8266 and ESP32 are low-cost Wi-Fi microchips with full TCP/IP stack and microcontroller capability. They are highly popular for IoT projects due to their wireless capabilities.

Benefits of Using ESP8266 and ESP32 in IoT:

Example of a Simple MicroPython Script:

  1. **Installation: First, install the esptool module using pip with the command:

$ pip install esptool.

  1. **Firmware: Download the latest MicroPython firmware from the official website. Use esptool to flash this firmware onto your device. Remember to erase the flash memory of the board before installing the new firmware to ensure a clean setup.
  2. **Development Environment: You can write your MicroPython code on a standard computer using any compatible IDE designed for MicroPython. After coding, compile and transfer the script to the ESP8266 or ESP32's memory.

Implementation

Here's a basic example demonstrating how to control an LED with an ESP8266 or ESP32 using MicroPython:

Python `

from machine import Pin import time

Initialize a pin for the LED

ledPin = Pin(2, Pin.OUT)

Toggle the LED on and off in a loop

while True: ledPin.on() # Turn on the LED time.sleep(1) # Wait for one second ledPin.off() # Turn off the LED time.sleep(1) # Wait for another second

`

**Explanation:

Python in IoT Backend

Python is an excellent choice for developing the backend systems of IoT applications due to its versatility, ease of use, and robust ecosystem. Here’s why Python is well-suited for the backend side of IoT:

**Example: Sending Sensor Data to a Flask API

IoT devices often send sensor readings such as temperature, humidity, or pressure to a server for processing and storage. The following example creates a Flask API that receives sensor data through an HTTP POST request and displays it on the server.

Install flask using following command:

pip install flask

Create a file named app.py and add the following code:

Python `

from flask import Flask, request

app = Flask(name)

@app.route("/sensor", methods=["POST"]) def sensor_data(): data = request.json

print("Received Data:", data)

return {"status": "received"}

app.run(debug=True)

`

Create another file named client.py and add the following code:

Python `

import requests

sensor_data = { "temperature": 28, "humidity": 65 }

response = requests.post( "http://127.0.0.1:5000/sensor", json=sensor_data )

print(response.json())

`

**Output

Server Output:

Received Data: {'temperature': 28, 'humidity': 65}

Client Output:

{'status': 'received'}

**Explanation:

Python TensorFlow PyTorch Wi-Fi