[Python Introduction Series] Chapter 21: Python Internet of Things and Sensor Applications


Preface

IoT and sensors play an important role in modern technology. The Internet of Things refers to connecting various devices and sensors through the Internet to achieve communication and data exchange between devices. Sensors are the core component of the Internet of Things and are used to sense and collect various data in the environment. In this article, we will explore the topic of developing IoT and sensor applications using Python.

1. Advantages of Python in IoT and sensor applications

Python is an easy-to-learn programming language with a rich library and tools, making it ideal for developing IoT and sensor applications. Python supports various hardware platforms and sensors, including Arduino, Raspberry Pi, etc. In addition, Python also has convenient data processing and analysis capabilities, which can help us process and utilize data collected by sensors.

2. Connect sensors and devices

In order to connect the sensor to the device, we need to use the appropriate hardware module. For example, if we use Arduino as the device, we can use the digital and analog pins of the Arduino to connect the sensors. In Python, we can use the serial port library to communicate with the sensor. The serial port library provides the function of data exchange with serial port devices.

3. Read sensor data

Once we have successfully connected the sensor and device, we can use Python's serial port library to read the data sent by the sensor. Sensors usually send data in a specific format, which we need to parse and process accordingly. For example, if we use a temperature sensor, it might send temperature values ​​in digital form, and we can use Python to parse these values ​​and do further processing.

4. Sample code and explanation

Here is sample code for a simple temperature sensor application:

import serial

# 打开串口
ser = serial.Serial('COM1', 9600)

while True:
    # 读取传感器数据
    data = ser.readline().decode().strip()
    
    # 解析数据
    temperature = float(data)
    
    # 处理数据
    if temperature > 30:
        print("温度过高!")
    else:
        print("温度正常")

In this code, we first imported Python's serial port library and opened the serial port connection. We then read the data sent by the sensor using the readline() function and convert it to string format using the decode() function. Next, we parse the temperature value and process it accordingly. If the temperature exceeds 30 degrees, we print out "Temperature is too high!", otherwise we print out "Temperature is normal".

5. Further processing and analysis of sensor data

In addition to simple processing, we can also perform more data processing and analysis according to needs. For example, we can use Python's data visualization library to draw real-time temperature curves to more intuitively observe changes in temperature. In addition, we can also set up a temperature alarm function. When the temperature exceeds a certain threshold, the system can send an alarm to notify relevant personnel.

6. More application examples

1. Temperature and humidity monitoring system

import Adafruit_DHT

sensor = Adafruit_DHT.DHT11
pin = 4

while True:
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    
    if humidity is not None and temperature is not None:
        print('温度={
    
    0:0.1f}°C  湿度={
    
    1:0.1f}%'.format(temperature, humidity))
    else:
        print('无法获取传感器数据')
  1. First, we need to install the Adafruit_DHT library, which can be used to communicate with the DHT series sensors. You can install this library using the following command:
    pip install Adafruit_DHT

  2. In the code, we use the DHT11 constant from the Adafruit_DHT library to specify that we are using a DHT11 sensor. If you are using another model of sensor, you can change it to DHT22 or AM2302 accordingly.

  3. The pin variable specifies the GPIO pin on the Raspberry Pi to which the sensor is connected. In this example, we used GPIO 4.

  4. In the while loop, we use the Adafruit_DHT.read_retry function to read the sensor data. This function will automatically retry if the read fails.

  5. If the temperature and humidity data are successfully read, they will be printed out. Otherwise, "Unable to obtain sensor data" will be displayed.

This case demonstrates how to use Python and the DHT11 sensor to implement a simple temperature and humidity monitoring system. You can modify and extend it according to your needs.

2. Smart home system-light control

import RPi.GPIO as GPIO
import time

# 设置GPIO模式为BCM
GPIO.setmode(GPIO.BCM)

# 定义LED灯的GPIO引脚
led_pin = 18

# 设置GPIO引脚为输出模式
GPIO.setup(led_pin, GPIO.OUT)

# 控制灯光的函数
def control_light(state):
    if state == "on":
        GPIO.output(led_pin, GPIO.HIGH)
        print("灯光已打开")
    elif state == "off":
        GPIO.output(led_pin, GPIO.LOW)
        print("灯光已关闭")
    else:
        print("无效的指令")

# 主程序
while True:
    command = input("请输入指令(on/off):")
    control_light(command)
time.sleep(1)


  1. First, we need to install the RPi.GPIO library, which can be used to communicate with the Raspberry Pi's GPIO pins. You can install this library using the following command:
    pip install RPi.GPIO

  2. In the code, we use the RPi.GPIO library to control the GPIO pins on the Raspberry Pi. In this example, we use GPIO 18 to connect the LED light.

  3. GPIO.setup(led_pin, GPIO.OUT) This line of code sets the GPIO pin to output mode to control the LED light on and off.

  4. The control_light function controls the state of the light according to the input instructions. When the input is "on", set the GPIO pin to high level and the light turns on; when the input is "off", set the GPIO pin to low level and the light turns off.

  5. In the main program, we use an infinite loop to receive user input instructions and call the control_light function to control the state of the light. After each cycle, the program will pause for 1 second.

This case demonstrates how to use Python and the GPIO pins of the Raspberry Pi to control the light on and off. You can modify and extend it according to your needs.

Summarize

In short, the use of Python as a hardware interface language in the Internet of Things reminds me of the C language in microcontroller control. Python's language style is a bit like the simplicity of C language. Maybe it's an object-oriented high-level walk and then returns to the concise way, but the processing thinking is already a high-level language thinking.

Guess you like

Origin blog.csdn.net/qq_38628970/article/details/131962278