Azure IoT with Raspberry Pi-Send Temperature and Humidity Sensor Data to Azure IoT Hub using Python

Transmitting Temperature and Humidity Sensor Data from Raspberry Pi to Azure IoT Hub using Python

Prabhashi Wijesinghe
LinkIT

--

Artwork by Author

Azure IoT Hub is a cloud service provided by Microsoft that allows developers to easily connect, monitor, and manage a large number of IoT devices from a single platform. It finds wide applications in areas like home automation, security systems, and monitoring setups. In this tutorial, we will demonstrate the capabilities of the Azure IoT hub by building a basic circuit using a Raspberry Pi and a DHT11 Temperature and Humidity Sensor. We will then utilize this circuit to process sensor data and publish it to the Azure IoT server using the MQTT protocol. By following this tutorial, you will learn how to set up and configure an Azure server and efficiently transmit data using a Raspberry Pi.

Let’s first understand the process of publishing sensor data to Azure IoT Hub.

Process of Publishing Sensor Data to Azure IoT Hub

Artwork by Author

This diagram shows how data flows from the sensor to the Azure cloud.

We are utilizing Raspberry Pi to send sensor data to Azure, you can use any Raspberry Pi as long as it can support MQTT protocol. There are several models of Raspberry Pi devices such as Raspberry Pi 1 Model A+ and B+, Raspberry Pi 2 Model B, Raspberry Pi 3 Model B and B+, and Raspberry Pi 4 Model B. You can use any of these that support the MQTT protocol. As well as we are using sensor source data, which can be any sensor of your choice. For this article, I am using DHT11 Temperature and Humidity sensor. You can connect the sensor to a Raspberry Pi device through wires.

Raspberry Pi device can communicate with Azure IoT hub through MQTT protocol to send sensor data. MQTT stands for Message Queuing Telemetry Transport Protocol. This protocol allows you to send telemetry data from your device to the cloud.

We are using Microsoft Azure Cloud as the cloud service and we utilize very specific resources of Azure Cloud.

The first resource that we are going to use is IoT Hub. Azure IoT Hub is a cloud service provided by Microsoft that allows developers to easily connect, monitor, and manage a large number of IoT devices from a single platform. It supports D-to-C and C-to-D communication. That means device-to-cloud and cloud-to-device communication. Another feature of an IoT hub is it has the ability to connect to many resources.

As well as we are utilizing Stream Analytics, which is a resource that allows you to stream real-time data from an IoT hub to an output. The output can be blob storage if we want to store data, the output can be power BI if you want to draw more advanced insights, and if you want to manipulate your data more you can use Azure functions. You can also get your data to the event grid for more advanced operations or you can store data in a SQL database or Cosmos DB.

For the tutorial, we are going to display real-time DHT11 temperature and humidity sensor data using Azure Command-Line Interface (CLI).

Next, let’s understand what Azure IoT hub is.

What is Azure IoT Hub?

Azure IoT hub is a suite of services offered by Microsoft that enables seamless connectivity, monitoring, and control of IoT devices. It provides secure communication, data analysis, and visualization capabilities, empowering device manufacturers to build and manage IoT applications using Azure Cloud. With Azure IoT Hub, we can receive real-time data from connected devices and send commands and notifications to them. For example, in a smart agriculture system, we can gather data from soil moisture sensors, temperature sensors, and humidity sensors deployed across a field. This data can be sent to the Azure IoT hub for analysis, visualization, and decision-making. We can also send commands to actuators to control irrigation systems or adjust temperature and humidity levels based on the analyzed data. Azure IoT hub acts as a central hub for efficient communication and management of IoT devices in diverse applications.

The first task we need to do is create an Azure IoT hub.

Creating a Microsoft Azure IoT Hub

Before beginning the setup process, ensure that you have a Microsoft account. If you don’t have one, you can easily sign up for an account by visiting Microsoft Azure Cloud Computing Services. Afterward, you can access the Azure portal by providing your Microsoft account credentials.

Once you have logged in, navigate to the Azure homepage and click on the Create a resource button. In the search field search for IoT hub. From the search results, select IoT Hub, and then click on the Create button. The steps mentioned above are visually illustrated in the below images, providing a clearer understanding of the process.

Screenshot of Azure portal captured by Author
Screenshot of Azure Create a resource captured by Author
Screenshot of Azure marketplace captured by Author
Screenshot of creating an Azure IoT hub captured by Author

After clicking on Create button you have to provide some details to create the IoT hub. First, we have to provide a resource group. In Microsoft Azure, a resource group is a logical container that helps you manage and organize related Azure resources. It acts as a boundary for grouping resources that share a common lifecycle. If you already have a resource group you can provide that or you can create a new resource group. The subscription will be automatically filled according to your Microsoft Azure subscription.

Screenshot of creating an Azure IoT hub captured by Author

As well as you have to provide instance details such as IoT hub name, Region, Tier, and Daily message limit. You can give any name for the IoT hub as your preference but always try to give a meaningful name. You can use the basic tier or free tier to minimize your cost. The daily message limit will be automatically filled according to your tier. The message limit will be less for the free tier and the basic tier. If you want to send more messages within a day you can use the standard tier. Therefore select the tier according to your need for daily messages. After providing the required details you have to click on the Review + Create button and then you will display a list of details of your IoT hub and click on the Create button to start the deployment of your IoT hub.

After several minutes your IoT hub will be available and you can register a device in your IoT hub. Go into your IoT hub and click on Devices on the navigation bar. Then you can add a device by providing a Device ID. The device ID can be any name according to your preference and then you have to click on the Save button to register the device.

Screenshot of Adding a device to IoT hub captured by Author
Screenshot of Adding a device to IoT hub captured by Author

After refreshing the page you will get your device. You can go into the device and it will display some important details that you need to connect your Raspberry Pi device to the Azure IoT hub. You need a Primary Connection String to connect your Raspberry Pi device to the Azure IoT hub.

Screenshot of Azure IoT hub captured by Author
Screenshot of device details in IoT hub captured by Author

Now we have created an Azure IoT hub and registered a device. Next, we have to set up our circuit and write a program to send sensor data to the Azure IoT hub.

Essential Components for Constructing the Circuit for Azure IoT with Raspberry Pi

Since the hardware part of this circuit is straightforward, the list of components you’ll need is also quite simple. Here’s a list of the required components for our tutorial:

  • Raspberry Pi 3B (We can also use any other models of Pi)
  • Micro SD Card-16 GB
  • DHT11 Sensor
  • Micro USB 5V, 2.4A Power supply

Establishing the Hardware Configuration

Below is the circuit diagram I have created for the tutorial. Simply follow the circuit and make the necessary connections to assemble the circuit on your own.

Photo by Author

In the above circuit, we have a DHT11 sensor responsible for gathering temperature and humidity data. We use a Raspberry Pi 3 Model B as a device to process this data. The DHT11 sensor has three pins: VCC and GND for power supply, and the data output pin is connected to GPIO4 on the Raspberry Pi; the fourth pin of the inner line of pins of Raspberry Pi. You can connect the VCC and GND of the sensor to the first and the third pin of the outer line of pins of the Raspberry Pi device. This setup allows us to send real-time sensor data to the Microsoft Azure IoT hub.

You can connect a mouse and a keyboard to Raspberry Pi to work with it. I have connected a mouse and a keyboard to the above circuit. I have connected the Raspberry Pi device to a power source using a Micro USB 5V, 2.4A power supply. We can connect the Raspberry Pi device to a monitor using the HDMI port and then the operating system of the Raspberry Bi device will be boosted.

Next, we have to program our Raspberry Pi to send real-time sensor data to the Azure IoT hub.

Programming Raspberry Pi to Publish Data on Azure IoT Hub

To enable smooth communication between the Raspberry Pi and the DHT11 sensor, as well as simplify the integration with Azure IoT services, it is essential to install the necessary dependencies on the Raspberry Pi before writing the program.

First, we have to download DHT Library for Raspberry Pi and extract the library. Then open the file in the terminal and execute the below command to install the library and ensure it is properly set up on the Raspberry Pi.

sudo python setup.py install
Screenshot of Raspberry Pi device captured by Author

Once the installation process is complete, execute the following commands to install all the required packages on Azure IoT Hub.

sudo pip3 install azure-iot-device  
sudo pip3 install azure-iot-hub

After successfully installing all the necessary prerequisites, we can proceed to write the Python program to publish sensor data on the Azure IoT hub. First, we have to create a file with a .py extension to write the program.

To begin, import all the required libraries by adding the appropriate import statements at the beginning of your code.

import random  
import Adafruit_DHT
import time
from azure.iot.device import IoTHubDeviceClient, Message

In this project, we utilize pin 4 of the Raspberry Pi to handle the data coming from the DHT11 sensor. Therefore, it is necessary to declare pin 4 in the code as demonstrated to ensure proper data processing.

sensor = Adafruit_DHT.DHT11
pin = 4

Moving forward, we proceed to specify the connection string within the code. Remember to substitute it with the device's primary connection string that you had previously received when registering a device to the IoT hub.

CONNECTION_STRING = "HostName=RaspberryConnectHub.azure-devices.net;DeviceId=XXXXXXX;SharedAccessKey=XXXXXXXXXXXXXXXXXX"  

Afterward, we generate an array that will be utilized for sending the data to Azure IoT Hub. You can accomplish this by following the code snippet provided below.

MSG_SND = '{{"temperature": {temperature},"humidity": {humidity}}}'  

Next, we utilize a while loop to continuously execute a set of instructions. Within this loop, the Adafruit_DHT.read_retry function is employed to process the humidity and temperature data. Additionally, we create two specific variables and assign the corresponding data output to these variables.

while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

The next function is implemented to establish a connection with the IoT hub using the pre-defined connection parameters.

def iothub_client_init():  
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
return client

Finally, we send both the temperature and humidity data to the Azure IoT hub using the format specified in the code. To ensure smooth execution, we employ a try-catch method to catch and handle any potential errors that may occur during the process.

def iothub_client_telemetry_sample_run():  
try:
client = iothub_client_init()
print ( "Sending data to IoT Hub, press Ctrl-C to exit" )
while True:
msg_txt_formatted = MSG_SND.format(temperature=temperature, humidity=humidity)
message = Message(msg_txt_formatted)
print( "Sending message: {}".format(message) )
client.send_message(message)
print ( "Message successfully sent" )
time.sleep(3)

Here is the complete Python program to publish DHT11 sensor data on the Azure IoT hub using Raspberry Pi.

Now we have to run this program to publish sensor data on the Azure IoT hub. Before that, we need to create an Azure cloud shell (CLI) in the Azure portal. For that, click on the Azure cloud shell button within the portal. Then, click on the Create Storage option, which is marked in red. Once you have completed this step, you can open the CLI and run a series of commands to install the required Azure add-ons. These add-ons are essential for showcasing the sensor data effectively.

Screenshot of creating Azure cloud shell captured by Author

After completing the previous steps, you can open the CLI and execute the following command to install the necessary Azure add-ons.

az extension add --name azure-iot 

Now we have to run the Python program on our Raspberry Pi. For that, we have to run python3 <File Name> on the terminal of Raspberry Pi. Since I have written my code on a file named raspberryprogram.py I use the following command to run the program.

python3 raspberryprogram.py

Now you will get the temperature and humidity sensor data to your Raspberry Pi as shown in the below image.

Screenshot of the raspberry pi device getting data from the sensor captured by Author

Now go to your Microsoft Azure portal and navigate to the CLI Terminal to view the data in Azure IoT Hub. Then, execute the following command in the terminal while substituting your own credentials.

az iot hub monitor-events --hub-name xxx --device-id xxx

In the above command replace first xxx with your Azure IoT hub name and second xxx with the device ID.

Then you can see the real-time temperature and humidity sensor data coming from the DHT11 sensor on the Azure CLI.

In this tutorial, I discussed showing the sensor data in Azure CLI. To learn about how to store sensor data in a container of blob storage refer to my tutorial on YouTube. In this tutorial, I have clearly explained the full process of publishing sensor data to the Azure IoT hub and storing them in a container of blob storage.

Video by Author

With that, I conclude this tutorial. I hope you found the article enjoyable and gained valuable insights from it. Thanks for reading!!!

--

--

Prabhashi Wijesinghe
LinkIT
Writer for

A dedicated and hardworking IT undergraduate, willing to share and gain information related to IT industry👩‍💻