Sending Telemetry to Azure IoT Hub

As I promised in my previous article, I will show you how to connect a temperature sensor to a Raspberry Pi, read real telemetry data, and send it to the Azure IoT Hub:

I am using a Raspberry Pi 4, a DHT11 temperature sensor, and a GPIO Extension Board to connect the sensor to the Raspberry. We’ll be using Azure IoT Python SDK enabling connection to the Azure IoT Hub. And we need DHT11 Python library for reading temperature and humidity from DHT11 sensor on Raspberry Pi.

First, we need to create an IoT Hub and to set up a Raspberry Pi. Repeat the steps described in my article “Connect Raspberry Pi 4 to Azure IoT Hub“:

Connect the sensor to Raspberry Pi

The DHT11 sensor can collect temperature and humidity data. Use the following wiring to connect the sensor to GPIO pins:

DHT11 Sensor pinsGPIO pins
Vcc (+)5V (pin 2)
Ground (-)GND (pin 6)
DataGPIO17 (pin 11)

Turn on your Raspberry Pi and connect it to your network.

Run the application

When it is done, clone the azure-iot-blog GitHub repository into a folder in your Raspberry Pi:

git clone https://github.com/jevgenij-p/azure-iot-blog.git

Find the Python application send_sensor_data.py in the raspberry-to-iot-hub/send-telemetry folder:

import asyncio
import time
import board
import RPi.GPIO as GPIO
import dht11
from azure.iot.device import Message
from azure.iot.device.aio import IoTHubDeviceClient

CONNECTION_STRING = ""

DELAY = 5
TEMPERATURE = 20.0
HUMIDITY = 60
PAYLOAD = '{{"temperature": {temperature}, "humidity": {humidity}}}'

async def main():

    try:
        # Create instance of the device client
        client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)

        # Initialize GPIO
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.cleanup()

        # Read data using pin GPIO17
        dhtDevice = dht11.DHT11(pin=17)

        print("Simulated device started. Press Ctrl-C to exit")
        while True:

            try:
                result = dhtDevice.read()
                if result.is_valid():
                    temperature = result.temperature
                    humidity = result.humidity

                    data = PAYLOAD.format(temperature=temperature, humidity=humidity)
                    message = Message(data)

                    # Send a message to the IoT hub
                    print(f"Sending message: {message}")
                    await client.send_message(message)
                    print("Message successfully sent")
                else:
                    # print("Error: %d" % result.error_code)
                    continue

                await asyncio.sleep(DELAY)

            except KeyboardInterrupt:
                print("Simulated device stopped")
                GPIO.cleanup()
                break

    except Exception as error:
        print(error.args[0])

if __name__ == '__main__':
    asyncio.run(main())

IMPORTANT

Make sure you copy-paste the Primary Connection String you saved when you created your IoT device, into the quotes in the Line 9.

Now, open your Raspberry Pi terminal and install Python packages:

pip3 install azure-iot-device
pip3 install asyncio
pip2 install dht11

Run the application:

python3 send_sensor_data.py

If everything is configured and connected correctly, the program will be sending sensor data every 5 seconds to your IoT hub:

Open Azure Portal, find your IoT hub, and select Overview in the left navigation menu. You should see number of messages received by your IoT hub from your device:

Stay tuned. I’ll continue the “Azure IoT” series.

7 thoughts on “Sending Telemetry to Azure IoT Hub

  1. yhhaw June 18, 2021 / 9:14 am

    pi@raspberrypi:~/azure-iot-blog/raspberry-to-iot-hub/send-telemetry $ pip2 install dht11
    Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
    Collecting dht11
    Could not find a version that satisfies the requirement dht11 (from versions: )
    No matching distribution found for dht11

    Like

    • yhhaw June 18, 2021 / 9:18 am

      pi@raspberrypi:~/azure-iot-blog/raspberry-to-iot-hub/send-telemetry $ python3 send_sensor_data.py
      Traceback (most recent call last):
      File “send_sensor_data.py”, line 5, in
      import dht11
      ModuleNotFoundError: No module named ‘dht11’

      Like

      • yhhaw June 18, 2021 / 2:27 pm

        Great. It works! Thank you very much.

        Like

      • yhhaw June 19, 2021 / 2:58 am

        Is there DHT22 Python library?

        Like

  2. yhhaw June 19, 2021 / 1:49 pm

    Thanks for the help. I tried to use the code in DHT22 article and “blend” into code in DHT11 article, but it didn’t work.. is it possible to check my code and correct my mistakes?

    Here is my code:

    import asyncio
    import time
    import board
    import adafruit_dht
    from azure.iot.device import Message
    from azure.iot.device.aio import IoTHubDeviceClient

    CONNECTION_STRING = “XXXX”

    DELAY = 5
    TEMPERATURE = 20.0
    HUMIDITY = 60.0
    PAYLOAD = ‘{{“temperature”: {temperature}, “humidity”: {humidity}}}’

    async def main():

    dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)

    print(“Measurement started. Press Ctrl-C to exit”)
    while True:
    try:
    temperature = dhtDevice.temperature
    humidity = dhtDevice.humidity
    data = PAYLOAD.format(temperature=temperature, humidity=humidity)
    message = Message(data)

    # Send a message to the IoT hub
    print(f”Sending message: {message}”)
    await client.send_message(message)
    print(“Message successfully sent”)

    except KeyboardInterrupt:
    dhtDevice.exit()
    raise SystemExit
    except RuntimeError as error:
    print(error.args[0])
    time.sleep(DELAY)
    continue

    time.sleep(DELAY)

    if __name__ == ‘__main__’:
    asyncio.run(main())

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s