Update tech_docs/python/IoT_python_information.md

This commit is contained in:
2024-06-27 06:56:23 +00:00
parent 6915d7f449
commit 9afb4aa241

View File

@@ -145,3 +145,141 @@ if __name__ == '__main__':
### Conclusion ### Conclusion
IoT applications involve integrating various components and technologies to collect, process, and analyze sensor data. By understanding the key concepts and following the steps outlined above, you can develop comprehensive IoT solutions that leverage sensor data for various applications. Whether you're building a simple home automation system or a complex industrial monitoring solution, Python and its rich ecosystem of libraries can greatly simplify the development process. IoT applications involve integrating various components and technologies to collect, process, and analyze sensor data. By understanding the key concepts and following the steps outlined above, you can develop comprehensive IoT solutions that leverage sensor data for various applications. Whether you're building a simple home automation system or a complex industrial monitoring solution, Python and its rich ecosystem of libraries can greatly simplify the development process.
---
Sure, let's break down the code snippet and understand how and where each of the imported libraries is used:
### 1. `import machine`
The `machine` module is used to interact with the hardware of the microcontroller. It provides functions to control pins, I2C, SPI, etc.
**Usage in the code:**
- `machine.Pin(4)`: This line creates a pin object for GPIO pin 4, which is used to interface with the DHT22 sensor.
```python
sensor = dht.DHT22(machine.Pin(4))
```
### 2. `import dht`
The `dht` module is specifically for interacting with DHT sensors (DHT11, DHT22). It provides methods to initialize the sensor and read temperature and humidity data.
**Usage in the code:**
- `dht.DHT22(machine.Pin(4))`: Initializes the DHT22 sensor on pin 4.
- `sensor.measure()`: Triggers the sensor to take a measurement.
- `sensor.temperature()`: Retrieves the temperature reading.
- `sensor.humidity()`: Retrieves the humidity reading.
```python
sensor = dht.DHT22(machine.Pin(4))
def read_sensor_data():
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
return temp, humidity
```
### 3. `import time`
The `time` module provides various time-related functions. It is commonly used for adding delays and getting the current time.
**Usage in the code:**
- `time.sleep(1)`: Pauses the execution for 1 second (used while waiting for the Wi-Fi connection).
- `time.sleep(60)`: Pauses the execution for 60 seconds in the main loop to wait before reading the sensor data again.
```python
while not wifi.isconnected():
time.sleep(1)
while True:
temperature, humidity = read_sensor_data()
print(f'Temperature: {temperature}C, Humidity: {humidity}%')
send_data(temperature, humidity)
time.sleep(60) # Wait for 60 seconds before reading again
```
### 4. `import network`
The `network` module provides functions to configure and control the network interfaces. It is used for connecting the microcontroller to a Wi-Fi network.
**Usage in the code:**
- `network.WLAN(network.STA_IF)`: Initializes the Wi-Fi interface in station mode.
- `wifi.active(True)`: Activates the Wi-Fi interface.
- `wifi.connect('your_ssid', 'your_password')`: Connects to the specified Wi-Fi network.
- `wifi.isconnected()`: Checks if the microcontroller is connected to the Wi-Fi network.
```python
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect('your_ssid', 'your_password')
while not wifi.isconnected():
time.sleep(1)
```
### 5. `import urequests`
The `urequests` module is a simplified version of the `requests` library, used to make HTTP requests from microcontrollers. It is used to send data to a server.
**Usage in the code:**
- `urequests.post(url, json=data, headers=headers)`: Sends an HTTP POST request to the specified URL with the sensor data in JSON format.
```python
def send_data(temp, humidity):
url = 'http://your_server_endpoint'
data = {'temperature': temp, 'humidity': humidity}
headers = {'Content-Type': 'application/json'}
response = urequests.post(url, json=data, headers=headers)
print(response.text)
```
### Complete Code Snippet with Comments
```python
# Import necessary libraries
import machine # Interacts with the microcontroller's hardware (pins, I2C, etc.)
import dht # Interacts with DHT sensors to read temperature and humidity
import time # Provides time-related functions (delays, etc.)
import network # Manages network connections (Wi-Fi)
import urequests # Simplified HTTP requests library for microcontrollers
# Set up Wi-Fi connection
wifi = network.WLAN(network.STA_IF) # Initialize Wi-Fi in station mode
wifi.active(True) # Activate Wi-Fi interface
wifi.connect('your_ssid', 'your_password') # Connect to Wi-Fi network
# Wait for Wi-Fi connection
while not wifi.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
# Set up the sensor
sensor = dht.DHT22(machine.Pin(4)) # Initialize DHT22 sensor on GPIO pin 4
# Function to read sensor data
def read_sensor_data():
sensor.measure() # Trigger measurement
temp = sensor.temperature() # Get temperature reading
humidity = sensor.humidity() # Get humidity reading
return temp, humidity
# Function to send data to a server
def send_data(temp, humidity):
url = 'http://your_server_endpoint'
data = {'temperature': temp, 'humidity': humidity}
headers = {'Content-Type': 'application/json'}
response = urequests.post(url, json=data, headers=headers) # Send POST request
print(response.text)
# Main loop
while True:
temperature, humidity = read_sensor_data() # Read sensor data
print(f'Temperature: {temperature}C, Humidity: {humidity}%')
send_data(temperature, humidity) # Send data to server
time.sleep(60) # Wait for 60 seconds before reading again
```
This code snippet demonstrates a complete IoT application where a microcontroller reads data from a DHT22 sensor, connects to a Wi-Fi network, and sends the sensor data to a server at regular intervals. Each import plays a specific role in the operation of the application, from hardware interaction to network communication and data transmission.