Sensor Data Upload ================== This example demonstrates how to connect a mPython Module DHT11 temperature and humidity sensor to mPython IoT, periodically read temperature and humidity data, and upload it to an IoT platform via MQTT for distributed environmental data acquisition. Hardware Connection ------------------- Connect the DHT11 temperature and humidity sensor to any expansion interface on mPython IoT via the HY2.0-4PIN connector. The sensor uses a standard HY2.0 interface with a reverse-insertion prevention design, making the connection simple and reliable. .. Hint:: The mPython Module offers a wide range of sensors and actuators. For more models, see :doc:`mPython Module Sensor Documentation ` . Reading Sensor Data ------------------- Use the ``dht`` module to read temperature and humidity data:: import dht from machine import Pin import time # Create DHT11 object based on the actual connected pin sensor = dht.DHT11(Pin(0)) def read_dht(): try: sensor.measure() # Trigger a measurement temp = sensor.temperature() # Read temperature (ā„ƒ) humi = sensor.humidity() # Read humidity (%RH) return temp, humi except Exception as e: print("Read failed: ", e) return None, None .. Note:: Replace ``Pin(0)`` with the actual GPIO pin number the sensor is connected to. The recommended DHT11 sampling interval is no less than 2 seconds. Uploading Data to MQTT Platform ------------------------------- Combining Wi-Fi connection and MQTT publishing, periodically upload the collected data:: from umqtt.simple import MQTTClient import network import dht from machine import Pin import time # Connect to Wi-Fi sta = network.WLAN(network.STA_IF) sta.active(True) sta.connect('your_ssid', 'your_password') while not sta.isconnected(): time.sleep(0.5) # MQTT configuration SERVER = "192.168.1.100" PORT = 1883 CLIENT_ID = "mpython_iot_001" TOPIC_TEMP = "classroom/temperature" TOPIC_HUMI = "classroom/humidity" sensor = dht.DHT11(Pin(0)) client = MQTTClient(CLIENT_ID, SERVER, PORT) client.connect() print("Connected to MQTT server") while True: try: sensor.measure() temp = sensor.temperature() humi = sensor.humidity() client.publish(TOPIC_TEMP, str(temp)) # Upload temperature client.publish(TOPIC_HUMI, str(humi)) # Upload humidity print("Temp: %dā„ƒ, Humidity: %d%%RH" % (temp, humi)) except Exception as e: print("Acquisition or upload failed: ", e) time.sleep(5) # Sample every 5 seconds .. Hint:: After successful upload, you can view data records and real-time curves on the SIoT or other IoT platform web interface. For SIoT platform usage, see :doc:`3_3_siot` . Related Documentation --------------------- - :doc:`3_2_mqtt` - :doc:`3_3_siot` - :doc:`3_5_remote`