Connect Raspberry Pi 4 to Azure IoT Hub

I have a Raspberry Pi 4 running Raspbian and I wanted to implement the simplest IoT Architectural pattern of direct connecting an IoT device to an Azure IoT Hub:

Create IoT Hub

First, we need to create an Azure IoT Hub. Login to Microsoft Azure Portal, find an “IoT Hub” in the Azure Marketplace, and create it:

Then, we need to specify as existing Resource Group, or create a new one, specify a Region closest to you, and a globally unique IoT hub name:

On the Management tab, select F1: Free tier and press Review + create button to create the hub:

When the hub is created, we need to create a device identity in the identity registry in your IoT hub. In the left navigation menu, open IoT devices, and then press New to add a device:

In Create a device panel, provide a name for your device (Device ID), and press Save:

Soon, you will see your device in IoT devices:

Click on it to open its properties. You need to copy its Primary Connection String and save it somewhere in a text file. We will need this string a bit later to establish connection between your device and the IoT hub.

Set up your Raspberry Pi

Before we continue, you need to prepare you Raspberry Pi. First, make sure SSH and SPI interfaces are enabled in your Raspberry Pi Configuration.

You can use PuTTY to connect to your Raspberry. Copy the IP address of your Raspberry Pi into the Host name and select SSH as the connection type:

Then, open your terminal and log in to your device:

Run the application

I created a simple Python application, sending simulated data to the Azure IoT hub. The code is in the azure-iot-blog GitHub repository. You can clone it into a folder in your Raspberry Pi:

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

Or, you can clone it to a folder on your computer, and copy only the send_simulated_messages.py file to the Raspberry Pi using WinSCP (if you are working on a machine with Windows).

The Python application is send_simulated_messages.py in the raspberry-to-iot-hub/send-telemetry folder:

import asyncio
import random
from azure.iot.device import Message
from azure.iot.device.aio import IoTHubDeviceClient

CONNECTION_STRING = ""

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)

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

            temperature = round(TEMPERATURE + (random.random() * 15), 2)
            humidity = round(HUMIDITY + (random.random() * 20), 2)
            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")

            await asyncio.sleep(5)

    except KeyboardInterrupt:
        print("Simulated device stopped")

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

IMPORTANT

Make sure you copy-paste the Primary Connection String you saved before, into the quotes in the Line 6.

Next, open your Raspberry Pi terminal and install some Python packages:

pip3 install azure-iot-device
pip3 install asyncio

Azure IoT Python SDK is a library, providing functionality for communicating between IoT devices and the Azure IoT Hub.

Now, you can run the application:

python3 send_simulated_messages.py

The program is sending data every 5 seconds to your IoT hub:

Let it work a few minutes and open Microsoft Azure Portal. Find your IoT hub, and select Overview in the left navigation menu to see your IoT Hub Usage:

Now you know how to send telemetry data (simulated in this case) to your Azure IoT hub. Next time I will show you how to send real data.

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