Connect Raspberry Pi to Azure IoT Hub (C)

In this tutorial, you begin by learning the basics of working with Raspberry Pi that's running Raspberry Pi OS. You then learn how to seamlessly connect your devices to the cloud by using Azure IoT Hub. For Windows 10 IoT Core samples, go to the Windows Dev Center.

Don't have a kit yet? Try Raspberry Pi online simulator. Or buy a new kit here.

What you do

  • Create an IoT hub.

  • Register a device for Pi in your IoT hub.

  • Setup Raspberry Pi.

  • Run a sample application on Pi to send sensor data to your IoT hub.

Connect Raspberry Pi to an IoT hub that you create. Then you run a sample application on Pi to collect temperature and humidity data from a BME280 sensor. Finally, you send the sensor data to your IoT hub.

What you learn

  • How to create an Azure IoT hub and get your new device connection string.

  • How to connect Pi with a BME280 sensor.

  • How to collect sensor data by running a sample application on Pi.

  • How to send sensor data to your IoT hub.

What you need

What you need

  • The Raspberry Pi 2 or Raspberry Pi 3 board.

  • An active Azure subscription. If you don't have an Azure account, create a free Azure trial account in just a few minutes.

  • A monitor, a USB keyboard, and mouse that connect to Pi.

  • A Mac or a PC that is running Windows or Linux.

  • An Internet connection.

  • A 16 GB or above microSD card.

  • A USB-SD adapter or microSD card to burn the operating system image onto the microSD card.

  • A 5-volt 2-amp power supply with the 6-foot micro USB cable.

The following items are optional:

  • An assembled Adafruit BME280 temperature, pressure, and humidity sensor.

  • A breadboard.

  • 6 F/M jumper wires.

  • A diffused 10-mm LED.

Note

These items are optional because the code sample supports simulated sensor data.

Create an IoT hub

This section describes how to create an IoT hub using the Azure portal.

  1. Sign in to the Azure portal.

  2. On the Azure homepage, select the + Create a resource button.

  3. From the Categories menu, select Internet of Things, and then select IoT Hub.

  4. On the Basics tab, complete the fields as follows:

    Important

    Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

    Property Value
    Subscription Select the subscription to use for your hub.
    Resource group Select a resource group or create a new one. To create a new one, select Create new and fill in the name you want to use.
    IoT hub name Enter a name for your hub. This name must be globally unique, with a length between 3 and 50 alphanumeric characters. The name can also include the dash ('-') character.
    Region Select the region, closest to you, where you want your hub to be located. Some features, such as IoT Hub device streams, are only available in specific regions. For these limited features, you must select one of the supported regions.
    Tier Select the tier that you want to use for your hub. Tier selection depends on how many features you want and how many messages you send through your solution per day.

    The free tier is intended for testing and evaluation. The free tier allows 500 devices to be connected to the hub and up to 8,000 messages per day. Each Azure subscription can create one IoT hub in the free tier.

    To compare the features available to each tier, select Compare tiers. For more information, see Choose the right IoT Hub tier for your solution.
    Daily message limit Select the maximum daily quota of messages for your hub. The available options depend on the tier you've selected for your hub. To see the available messaging and pricing options, select See all options and select the option that best matches the needs of your hub. For more information, see IoT Hub quotas and throttling.

    Screen capture that shows how to create an IoT hub in the Azure portal.

    Note

    Prices shown are for example purposes only.

  5. Select Next: Networking to continue creating your hub.

  6. On the Networking tab, complete the fields as follows:

    Property Value
    Connectivity configuration Choose the endpoints that devices can use to connect to your IoT hub. Accept the default setting, Public access, for this example. You can change this setting after the IoT hub is created. For more information, see Managing public network access for your IoT hub.
    Minimum TLS Version Select the minimum TLS version to be supported by your IoT hub. Once the IoT hub is created, this value can't be changed. Accept the default setting, 1.0, for this example.

    Screen capture that shows how to choose the endpoints that can connect to a new IoT hub.

  7. Select Next: Management to continue creating your hub.

  8. On the Management tab, accept the default settings. If desired, you can modify any of the following fields:

    Property Value
    Permission model Part of role-based access control, this property decides how you manage access to your IoT hub. Allow shared access policies or choose only role-based access control. For more information, see Control access to IoT Hub by using Azure Active Directory.
    Assign me You may need access to IoT Hub data APIs to manage elements within an instance. If you have access to role assignments, select IoT Hub Data Contributor role to grant yourself full access to the data APIs.

    To assign Azure roles, you must have Microsoft.Authorization/roleAssignments/write permissions, such as User Access Administrator or Owner.
    Device-to-cloud partitions This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most IoT hubs need only four partitions.

    Screen capture that shows how to set the role-based access control and scale for a new IoT hub.

  9. Select Next: Add-ons to continue to the next screen.

  10. On the Add-ons tab, accept the default settings. If desired, you can modify any of the following fields:

    Property Value
    Enable Device Update for IoT Hub Turn on Device Update for IoT Hub to enable over-the-air updates for your devices. If you select this option, you're prompted to provide information to provision a Device Update for IoT Hub account and instance. For more information, see What is Device Update for IoT Hub?
    Enable Defender for IoT Turn Defender for IoT on to add an extra layer of protection to IoT and your devices. This option isn't available for hubs in the free tier. Learn more about security recommendations for IoT Hub in Defender for IoT.

    Screen capture that shows how to set the optional add-ons for a new IoT hub.

    Note

    Prices shown are for example purposes only.

  11. Select Next: Tags to continue to the next screen.

    Tags are name/value pairs. You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. In this document, you won't be adding any tags. For more information, see Use tags to organize your Azure resources.

    Screen capture that shows how to assign tags for a new IoT hub.

  12. Select Next: Review + create to review your choices.

  13. Select Create to start the deployment of your new hub. Your deployment will be in progress a few minutes while the hub is being created. Once the deployment is complete, select Go to resource to open the new hub.

Register a new device in the IoT hub

In this section, you create a device identity in the identity registry in your IoT hub. A device can't connect to a hub unless it has an entry in the identity registry. For more information, see the IoT Hub developer guide.

  1. In your IoT hub navigation menu, open Devices, then select Add Device to add a device in your IoT hub.

    Screen capture that shows how to create a device identity in the portal.

  2. In Create a device, provide a name for your new device, such as myDeviceId, and select Save. This action creates a device identity for your IoT hub. Leave Auto-generate keys checked so that the primary and secondary keys will be generated automatically.

    Screen capture that shows how to add a new device.

    Important

    The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

  3. After the device is created, open the device from the list in the Devices pane. Copy the value of Primary connection string. This connection string is used by device code to communicate with the IoT hub.

    By default, the keys and connection strings are masked because they're sensitive information. If you click the eye icon, they're revealed. It's not necessary to reveal them to copy them with the copy button.

    Screen capture that shows the device connection string.

Note

The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. It stores device IDs and keys to use as security credentials, and an enabled/disabled flag that you can use to disable access for an individual device. If your application needs to store other device-specific metadata, it should use an application-specific store. For more information, see IoT Hub developer guide.

Set up Raspberry Pi

Now set up the Raspberry Pi.

Install the Raspberry Pi OS

Prepare the microSD card for installation of the Raspberry Pi OS image.

  1. Download Raspberry Pi OS.

    1. Download Raspberry Pi OS with Desktop (the .zip file).

    2. Extract the image to a folder on your computer.

  2. Install Raspberry Pi OS to the microSD card.

    1. Download and install the Etcher SD card burner utility.

    2. Run Etcher and select the Raspberry Pi OS image that you extracted in step 1.

    3. Select the microSD card drive. Note that Etcher may have already selected the correct drive.

    4. Click Flash to install Raspberry Pi OS to the microSD card.

    5. Remove the microSD card from your computer when installation is complete. It's safe to remove the microSD card directly because Etcher automatically ejects or unmounts the microSD card upon completion.

    6. Insert the microSD card into Pi.

Enable SSH and SPI

  1. Connect Pi to the monitor, keyboard and mouse, start Pi and then sign in to Raspberry Pi OS by using pi as the user name and raspberry as the password.

  2. Click the Raspberry icon > Preferences > Raspberry Pi Configuration.

    The Raspberry Pi OS Preferences menu

  3. On the Interfaces tab, set SPI and SSH to Enable, and then click OK. If you don't have physical sensors and want to use simulated sensor data, this step is optional.

    Enable SPI and SSH on Raspberry Pi

Note

To enable SSH and SPI, you can find more reference documents on raspberrypi.org and RASPI-CONFIG.

Connect the sensor to Pi

Use the breadboard and jumper wires to connect an LED and a BME280 to Pi as follows. If you don’t have the sensor, skip this section.

The Raspberry Pi and sensor connection

The BME280 sensor can collect temperature and humidity data. And the LED will blink if there is a communication between device and the cloud.

For sensor pins, use the following wiring:

Start (Sensor & LED) End (Board) Cable Color
LED VDD (Pin 5G) GPIO 4 (Pin 7) White cable
LED GND (Pin 6G) GND (Pin 6) Black cable
VDD (Pin 18F) 3.3V PWR (Pin 17) White cable
GND (Pin 20F) GND (Pin 20) Black cable
SCK (Pin 21F) SPI0 SCLK (Pin 23) Orange cable
SDO (Pin 22F) SPI0 MISO (Pin 21) Yellow cable
SDI (Pin 23F) SPI0 MOSI (Pin 19) Green cable
CS (Pin 24F) SPI0 CS (Pin 24) Blue cable

Click to view Raspberry Pi 2 & 3 Pin mappings for your reference.

After you've successfully connected BME280 to your Raspberry Pi, it should be like below image.

Connected Pi and BME280

Connect Pi to the network

Turn on Pi by using the micro USB cable and the power supply. Use the Ethernet cable to connect Pi to your wired network or follow the instructions from the Raspberry Pi Foundation to connect Pi to your wireless network. After your Pi has been successfully connected to the network, you need to take a note of the IP address of your Pi.

Connected to wired network

Run a sample application on Pi

Sign into your Raspberry Pi

  1. Use one of the following SSH clients from your host computer to connect to your Raspberry Pi.

    Windows Users

    1. Download and install PuTTY for Windows.
    2. Copy the IP address of your Pi into the Host name (or IP address) section and select SSH as the connection type.

    PuTTy

    Mac and Ubuntu Users

    Use the built-in SSH client on Ubuntu or macOS. You might need to run ssh pi@<ip address of pi> to connect Pi via SSH.

    Note

    The default username is pi , and the password is raspberry.

Configure the sample application

  1. Clone the sample application by running the following command:

    git clone https://github.com/Azure-Samples/iot-hub-c-raspberrypi-client-app.git
    
  2. A setup script is provided with the sample to prepare the development environment, and build the sample. Run setup script:

    cd ./iot-hub-c-raspberrypi-client-app
    sudo chmod u+x setup.sh
    sudo ./setup.sh
    

    Note

    If you don't have a physical BME280, you can use '--simulated-data' as command line parameter to simulate temperature&humidity data. sudo ./setup.sh --simulated-data

Build and run the sample application

  1. The setup script should have already built the sample. However, if you make changes and need to rebuild the sample application, run the following command:

    cmake . && make
    

    Build output

  2. Run the sample application by running the following command:

    sudo ./app '<DEVICE CONNECTION STRING>'
    

    Note

    Make sure you copy-paste the device connection string into the single quotes.

You should see the following output that shows the sensor data and the messages that are sent to your IoT hub.

Output - sensor data sent from Raspberry Pi to your IoT hub

Read the messages received by your hub

One way to monitor messages received by your IoT hub from your device is to use the Azure IoT Hub extension for Visual Studio Code. To learn more, see Use the Azure IoT Hub extension for Visual Studio Code to send and receive messages between your device and IoT Hub.

For more ways to process data sent by your device, continue on to the next section.

Clean up resources

You can use the resources created in this topic with other tutorials and quickstarts in this document set. If you plan to continue on to work with other quickstarts or with the tutorials, do not clean up the resources created in this topic. If you do not plan to continue, use the following steps to delete all resources created by this topic in the Azure portal.

  1. From the left-hand menu in the Azure portal, select All resources and then select the IoT Hub you created.
  2. At the top of the IoT Hub overview pane, click Delete.
  3. Enter your hub name and click Delete again to confirm permanently deleting the IoT Hub.

Next steps

You’ve run a sample application to collect sensor data and send it to your IoT hub.

To continue to get started with Azure IoT Hub and to explore all extended IoT scenarios, see the following: