다음을 통해 공유


Azure Cloud Services for Raspberry Pi 4: How to send sensor data to Azure IoT Hub

Introduction

Microsoft Azure provides a variety of cloud computing services including artificial intelligence, machine learning, IoT, storage, security, networking, media, integration and so on. For IoT applications, Azure IoT Hub provides a cloud-hosted solution back end to connect any device over the internet. Among tens of thousands of IoT end devices, Raspberry Pi is one of the most popular and useful platforms that used in many areas because of its low cost, modularity, and open design. Raspberry Pi 4 is the latest powerful model with Quad core Cortex-A72 64-bit processor, 2 HDMI ports, 40 pin GPIO header and hardware video decode capability. 
In this article, we will walk you through the steps required to send the sensor data to Azure IoT Hub on Raspberry Pi 4 model B with Python Azure IoT SDK.

Prerequisites

  1. Raspberry Pi 4 model B
  2. Python Azure IoT Device SDK
  3. DHT11 Temperature & Humidity sensor, PIR sensor.

Hardware Connection

Here we use BCM Pin 17 as the communication channel between Raspberry Pi and DHT 11. And BCM Pin 4 is configured as the data input from PIR sensor to Raspberry Pi. The hardware scheme is shown in Fig. 1 as follows.

Fig. 1 Hardware scheme

Install Python Azure IoT SDK

Open your Raspberry Pi terminal and install Python Azure IoT SDK:

1.pip3 install azure-iot-device
2.pip3 install asyncio

Create an Azure IoTHub and Register a New Device

We can create an IoT hub using the Azure Portal. Please refer to the “Create an IoT hub” section on this page: Connect Raspberry Pi to Azure IoT Hub. Then, in order to send the data to Azure IoT Hub, we should register a new device in the IoT hub. The “Register a new device in the IoT hub” section is available to help you with this. After the device is created, open the device from the list in the Devices pane. Copy the Primary Connection String. This connection string will be used by Python code to communicate with the hub.

Create and Debug Python Code on Raspberry Pi

Currently, there are several Python IDE on Raspberry Pi. Thonny Python IDE is bundled with the Raspbian OS. We can launch it by click Programming -> Thonny Python IDE. Then copy and paste the following code.

01.import asyncio
02.import time
03.import board
04.import RPi.GPIO as GPIO
05.import dht11
06.from azure.iot.device import Message
07.from azure.iot.device.aio import IoTHubDeviceClient
08. 
09.CONNECTION_STRING="HostName=***.azure-devices.net;DeviceId=**;SharedAccessKey=***"
10. 
11.DELAY =  5
12.TEMPERATURE =  20.0
13.HUMIDITY =  60
14.PAYLOAD =  '{{"temperature": {temperature}, "humidity": {humidity}, "PIR": {pir}}}'
15. 
16.async def  main():
17. 
18.    try:
19.        # Create instance of the device client
20.        client =  IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
21. 
22.        # Initialize GPIO
23.        GPIO.setwarnings(False)
24.        GPIO.setmode(GPIO.BCM)
25.        GPIO.cleanup()
26. 
27.        # Read data using pin GPIO17
28.        dhtDevice =  dht11.DHT11(pin=17)
29.         
30.        GPIO.setup(4, GPIO.IN) #PIR
31. 
32.        print("Sending serivce started. Press Ctrl-C to exit")
33.        while True:
34. 
35.            try:
36.                #DHT11
37.                result =  dhtDevice.read()
38.                #PIR
39.                if GPIO.input(4):
40.                    pir =  1
41.                else:
42.                    pir =  0
43.                     
44.                if result.is_valid():
45.                    temperature =  result.temperature
46.                    humidity =  result.humidity
47. 
48.                    data =  PAYLOAD.format(temperature=temperature, humidity=humidity, pir=pir)
49.                    message =  Message(data)
50. 
51.                    # Send a message to the IoT hub
52.                    print(f"Sending message: {message}")
53.                    await client.send_message(message)
54.                    print("Message successfully sent")
55.                else:
56.                    print("Error: %d" %  result.error_code)
57.                    continue
58. 
59.                await asyncio.sleep(DELAY)
60. 
61.            except KeyboardInterrupt:
62.                print("Service stopped")
63.                GPIO.cleanup()
64.                break
65. 
66.    except Exception as error:
67.        print(error.args[0])
68. 
69.if __name__ == '__main__':
70.asyncio.run(main())

Please do substitute the connection string with yours that created in section “Create an Azure IoTHub and Register a New Device”. Then, press Run or Debug button to start the process. You will see the output in Shell window as shown in Fig. 2.

Fig. 2 Debug information on Shell window

Monitor the Message with Azure IoT Explorer

Install and run Azure IoT Explorer, choose the device that you created. And then click telemetry. We will see the data as soon as the Python application send out the message. It is shown in Fig. 3.

Fig. 3 Telemetry monitor by Azure IoT Explorer

Summary

In this tutorial, we have presented how to send sensor data to Azure IoT Hub on Raspberry Pi 4, including temperature, humidity and PIR sensor data.

Resources

1.  MS Docs for Azure IoT Hub.
2.  MS Docs for Connect Raspberry Pi to Azure IoT Hub.
3.  Azure IoT Explorer: Install and use Azure IoT Explorer

See Also

1.  How to use Python Azure IoT SDK with Visual Studio
2.  Python Azure IoT SDK: How to receive direct methods from IoT Hub
3.  Python Azure IoT SDK: How to use device twins in IoT Hub
4.  Python Azure IoT SDK: How to use device provision service with symmetric keys