Azure IoT Hub / Raspberry Pi IoT Project – Connecting Pi and Azure (Raspberry Pi / Python)

Azure and Raspberry Pi successfully communicating

I have looked at the best Raspberry Pi & sensor for my IoT Temperature Project, setup the hardware, took measurements and outputted them to a Twitter bot. Then yesterday I created an Azure IoT Hub, which means I now need to connect the Raspberry Pi to the Azure IoT Hub.

The first step is to register the Pi in the Azure IoT hub. Whilst logged into the Azure portal look towards the top of the screen for >_ icon. This is the Command Line Interface (CLI).

>_ CLI - Command Line Interface
>_ CLI – Command Line Interface

Click the CLI to open it and with the CLI open we can register a device via the following commands:

  • az extension add –name azure-cli-iot-ext
  • az iot hub device-identity create –hub-name YourIoTHubName –device-id MyPythonDevice

Replacing YourIoTHubName with the name of your IoT Hub and optionally replacing MyPythonDevice with the name of your device. Then enter:

  • az iot hub device-identity show-connection-string –hub-name YourIoTHubName –device-id MyPythonDevice –output table

This command will output a string containing the device connection details, I would recommend copying and pasting it into a text file as it is needed later.

My Connection string looks like this (I’ve replaced some characters with ?’s):

CONNECTION_STRING = “;DeviceId=MyPythonDevice;SharedAccessKey=?????????????????????????????????=”


Now to the Raspberry Pi. On the Raspberry Pi open terminal and prepare to enter some commands.

Whilst trying to connect I ran into a few issues which I think were based around pip installing modules for Python 2 rather than Python 3 (which I currently use).  So:

Python 2

sudo pip install azure-iothub-device-client

sudo pip install azure-iothub-service-client

Python 3

sudo pip3 install azure-iothub-device-client

sudo pip3 install azure-iothub-service-client

And this should mean the Pi is ready to do a test connection to Azure. During my initial testing I hit two issues.

1.  A libboost-all-dev error along the lines of “ImportError: cannot open shared object file: No such file or directory on raspbian“. Basically due to a missing dependency, this if fixed with the following command which installs missing dependency:

  • sudo apt-get install libboost-all-dev

2. A error message in my Python script that was Azure responding to say there was an error. This error messages said BECAUSE_DESTROY and has instantly become my favourite error message. I imagine it being said by a Decepticon from Transformers or Magneto in the early 1990’s X-Men arcade game (where the classic line, “Welcome to die!” was said). For me this error was caused by my connection string missing a closing speech mark.

Microsoft offer some template test files (located at: ) but to keep inline with my IoT project I decided to modify one of these with the functions I created/used previously to take measurements from the temperature sensor. I’ve put my changes in green below:


# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

import random
import time
import sys

# imports the modules for the sensor
from bmp280 import BMP280
from smbus2 import SMBus
except ImportError:
from smbus import SMBus

bmp280 = BMP280(i2c_dev=bus)

def get_temp():
temperature = bmp280.get_temperature()
temperature = temperature – 2.00

def get_pressure():
pressure = bmp280.get_pressure()

# Using the Python Device SDK for IoT Hub:
# The sample connects to a device-specific MQTT endpoint on your IoT Hub.
import iothub_client
# pylint: disable=E0611
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult
from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError, DeviceMethodReturnValue

# The device connection string to authenticate the device with your IoT hub.
# Using the Azure CLI:
# az iot hub device-identity show-connection-string –hub-name {YourIoTHubName} –device-id MyNodeDevice –output table

# Using the MQTT protocol.
PROTOCOL = IoTHubTransportProvider.MQTT

# Define the JSON message to send to IoT Hub.
TEMPERATURE = get_temp()
PRESSURE = get_pressure()
MSG_TXT = “{\”temperature\”: %.2f,\“pressure\“: %.2f}”

def send_confirmation_callback(message, result, user_context):
print ( “IoT Hub responded to message with status: %s” % (result) )

def iothub_client_init():
# Create an IoT Hub client
return client

def iothub_client_telemetry_sample_run():

client = iothub_client_init()
print ( “IoT Hub device sending periodic messages, press Ctrl-C to exit” )

while True:
# Build the message with simulated telemetry values.
temperature = TEMPERATURE
pressure = PRESSURE
msg_txt_formatted = MSG_TXT % (temperature, pressure)
message = IoTHubMessage(msg_txt_formatted)

# Add a custom application property to the message.
# An IoT hub can filter on these properties without access to the message body.
prop_map =
if temperature > 30:
prop_map.add(“temperatureAlert”, “true”)
prop_map.add(“temperatureAlert”, “false”)

# Send the message.
print( “GeekTechStuff Azure Sending Message: %s” % message.get_string() )
client.send_event_async(message, send_confirmation_callback, None)

except IoTHubError as iothub_error:
print ( “Unexpected error %s from IoTHub” % iothub_error )
except KeyboardInterrupt:
print ( “IoTHubClient sample stopped” )

if __name__ == ‘__main__’:
print ( “IoT Hub Quickstart #1 – Simulated device” )
print ( “Press Ctrl-C to exit” )


With the program running on the Pi it is time to jump back into Azure.

With the Azure CLI enter the command:

  • az iot hub monitor-events –hub-name YourIoTHubName –device-id MyPythonDevice

Again replaying YourIoTHubName with the IoT Hub Name you are using and if you used a different name for your Python device then change MyPythonDevice to the that now.

Hopefully after a few minutes (if you’ve used my script it sends a signal every 300 seconds, aka 5 minutes) the Azure CLI should show some data coming through.

Azure and Raspberry Pi successfully communicating
Azure and Raspberry Pi successfully communicating

I’ve saved my modified Azure Python file at:

One thought on “Azure IoT Hub / Raspberry Pi IoT Project – Connecting Pi and Azure (Raspberry Pi / Python)

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.