Quickstart: Connect an MXCHIP AZ3166 devkit to IoT Hub

Applies to: Embedded device development
Total completion time: 30 minutes

Browse code

In this quickstart, you use Azure RTOS to connect an MXCHIP AZ3166 IoT DevKit (hereafter, MXCHIP DevKit) to Azure IoT.

You'll also use IoT Explorer and IoT Plug and Play to manage the MXCHIP DevKit. IoT Plug and Play provides an open device model that lets applications programmatically query a device's capabilities and interact with it. A device uses this model to broadcast its capabilities to an IoT Plug and Play-enabled application. By using this model, you can streamline and enhance the tasks of adding, configuring, and managing devices. For more information, see the IoT Plug and Play documentation.

You'll complete the following tasks:

  • Install a set of embedded development tools for programming the MXChip DevKit in C
  • Build an image and flash it onto the MXCHIP DevKit
  • Use Azure CLI to create and manage an Azure IoT hub that the MXCHIP DevKit will securely connect to
  • Use Azure IoT Explorer to register a device with your IoT hub, view device properties, view device telemetry, and call direct commands on the device

Prerequisites

  • A PC running Windows 10

  • If you don't have an Azure subscription, create one for free before you begin.

  • Git for cloning the repository

  • Azure CLI. You have two options for running Azure CLI commands in this quickstart:

    • Use the Azure Cloud Shell, an interactive shell that runs CLI commands in your browser. This option is recommended because you don't need to install anything. If you're using Cloud Shell for the first time, sign in to the Azure portal. Follow the steps in Cloud Shell quickstart to Start Cloud Shell and Select the Bash environment.
    • Optionally, run Azure CLI on your local machine. If Azure CLI is already installed, run az upgrade to upgrade the CLI and extensions to the current version. To install Azure CLI, see Install Azure CLI.
  • Azure IoT Explorer: Cross-platform utility to monitor and manage Azure IoT

  • Hardware

Prepare the development environment

To set up your development environment, first you clone a GitHub repo that contains all the assets you need for the quickstart. Then you install a set of programming tools.

Clone the repo for the quickstart

Clone the following repo to download all sample device code, setup scripts, and offline versions of the documentation. If you previously cloned this repo in another quickstart, you don't need to do it again.

To clone the repo, run the following command:

git clone --recursive https://github.com/azure-rtos/getting-started.git

Install the tools

The cloned repo contains a setup script that installs and configures the required tools. If you installed these tools in another embedded device quickstart, you don't need to do it again.

Note

The setup script installs the following tools:

  • CMake: Build
  • ARM GCC: Compile
  • Termite: Monitor serial port output for connected devices resources

To install the tools:

  1. From File Explorer, navigate to the following path in the repo and run the setup script named get-toolchain.bat:

    getting-started\tools\get-toolchain.bat

  2. After the installation, open a new console window to recognize the configuration changes made by the setup script. Use this console to complete the remaining programming tasks in the quickstart. You can use Windows CMD, PowerShell, or Git Bash for Windows.

  3. Run the following code to confirm that CMake version 3.14 or later is installed.

    cmake --version
    

Create the cloud components

Create an IoT hub

You can use Azure CLI to create an IoT hub that handles events and messaging for your device.

To create an IoT hub:

  1. Launch your CLI app. To run the CLI commands in the rest of this quickstart, copy the command syntax, paste it into your CLI app, edit variable values, and press Enter.

    • If you prefer to use Cloud Shell, right-click the link for Cloud Shell and select the option to open in a new tab.
    • If you're using Azure CLI locally, start your CLI console app and sign in to Azure CLI.
  2. Run az extension add to install or upgrade the azure-iot extension to the current version.

    az extension add --upgrade --name azure-iot
    
  3. Run the az group create command to create a resource group. The following command creates a resource group named MyResourceGroup in the centralus region.

    Note

    You can optionally set an alternate location. To see available locations, run az account list-locations.

    az group create --name MyResourceGroup --location centralus
    
  4. Run the az iot hub create command to create an IoT hub. It might take a few minutes to create an IoT hub.

    YourIotHubName. Replace this placeholder below with the name you chose for your IoT hub. An IoT hub name must be globally unique in Azure. This placeholder is used in the rest of this quickstart to represent your unique IoT hub name.

    The --sku F1 parameter creates the IoT hub in the Free tier. Free tier hubs have a limited feature set and are used for proof of concept applications. For more information on IoT Hub tiers, features, and pricing, see Azure IoT Hub pricing.

    az iot hub create --resource-group MyResourceGroup --name {YourIoTHubName} --sku F1 --partition-count 2
    
  5. After the IoT hub is created, view the JSON output in the console, and copy the hostName value to use in a later step. The hostName value looks like the following example:

    {Your IoT hub name}.azure-devices.net

Configure IoT Explorer

In the rest of this quickstart, you'll use IoT Explorer to register a device to your IoT hub, to view the device properties and telemetry, and to send commands to your device. In this section, you configure IoT Explorer to connect to the IoT hub you just created and to read plug and play models from the public model repository.

To add a connection to your IoT hub:

  1. In your CLI app, run the az iot hub connection-string show command to get the connection string for your IoT hub.

    az iot hub connection-string  show --hub-name {YourIoTHubName}
    
  2. Copy the connection string without the surrounding quotation characters.

  3. In Azure IoT Explorer, select IoT hubs on the left menu, then select + Add connection.

  4. Paste the connection string into the Connection string box.

  5. Select Save.

    Screenshot of adding a connection in IoT Explorer

  6. If the connection succeeds, IoT Explorer switches to the Devices view.

To add the public model repository:

  1. In IoT Explorer, select Home to return to the home view.

  2. On the left menu, select IoT Plug and Play Settings, then select +Add and select Public repository from the drop-down menu.

  3. An entry appears for the public model repository at https://devicemodels.azure.com.

    Screenshot of adding the public model repository in IoT Explorer

  4. Select Save.

Register a device

In this section, you create a new device instance and register it with the IoT hub you created. You will use the connection information for the newly registered device to securely connect your physical device in a later section.

To register a device:

  1. From the home view in IoT Explorer, select IoT hubs.

  2. The connection you previously added should appear. Select View devices in this hub below the connection properties.

  3. Select + New and enter a device ID for your device; for example, mydevice. Leave all other properties the same.

  4. Select Create.

    Screenshot of Azure IoT Explorer device identity

  5. Use the copy buttons to copy and note down the Device ID and Primary key fields.

Before continuing to the next section, confirm that you've copied the following values:

  • hostName
  • deviceId
  • primaryKey

Prepare the device

To connect the MXCHIP DevKit to Azure, you'll modify a configuration file for Wi-Fi and Azure IoT settings, rebuild the image, and flash the image to the device.

Add configuration

  1. Open the following file in a text editor:

    getting-started\MXChip\AZ3166\app\azure_config.h

  2. Comment out the following line near the top of the file as shown:

    // #define ENABLE_DPS
    
  3. Set the Wi-Fi constants to the following values from your local environment.

    Constant name Value
    WIFI_SSID {Your Wi-Fi SSID}
    WIFI_PASSWORD {Your Wi-Fi password}
    WIFI_MODE {One of the enumerated Wi-Fi mode values in the file}
  4. Set the Azure IoT device information constants to the values that you saved after you created Azure resources.

    Constant name Value
    IOT_HUB_HOSTNAME {Your Iot hub hostName value}
    IOT_DPS_REGISTRATION_ID {Your Device ID value}
    IOT_DEVICE_SAS_KEY {Your Primary key value}
  5. Save and close the file.

Build the image

  1. In your console or in File Explorer, run the script rebuild.bat at the following path to build the image:

    getting-started\MXChip\AZ3166\tools\rebuild.bat

  2. After the build completes, confirm that the binary file was created in the following path:

    getting-started\MXChip\AZ3166\build\app\mxchip_azure_iot.bin

Flash the image

  1. On the MXCHIP DevKit, locate the Reset button, and the Micro USB port. You use these components in the following steps. Both are highlighted in the following picture:

    Locate key components on the MXChip devkit board

  2. Connect the Micro USB cable to the Micro USB port on the MXCHIP DevKit, and then connect it to your computer.

  3. In File Explorer, find the binary file that you created in the previous section.

  4. Copy the binary file mxchip_azure_iot.bin.

  5. In File Explorer, find the MXCHIP DevKit device connected to your computer. The device appears as a drive on your system with the drive label AZ3166.

  6. Paste the binary file into the root folder of the MXCHIP Devkit. Flashing starts automatically and completes in a few seconds.

    Note

    During the flashing process, a green LED toggles on MXCHIP DevKit.

Confirm device connection details

You can use the Termite app to monitor communication and confirm that your device is set up correctly.

  1. Start Termite.

    Tip

    If you are unable to connect Termite to your devkit, install the ST-LINK driver and try again. See Troubleshooting for additional steps.

  2. Select Settings.

  3. In the Serial port settings dialog, check the following settings and update if needed:

    • Baud rate: 115,200
    • Port: The port that your MXCHIP DevKit is connected to. If there are multiple port options in the dropdown, you can find the correct port to use. Open Windows Device Manager, and view Ports to identify which port to use.

    Screenshot of serial port settings in the Termite app

  4. Select OK.

  5. Press the Reset button on the device. The button is labeled on the device and located near the Micro USB connector.

  6. In the Termite app, check the following checkpoint values to confirm that the device is initialized and connected to Azure IoT.

    Starting Azure thread
    
    Initializing WiFi
         MAC address: C8:93:46:8A:4C:43
         Connecting to SSID 'iot'
    SUCCESS: WiFi connected to iot
    
    Initializing DHCP
         IP address: 192.168.0.18
         Mask: 255.255.255.0
         Gateway: 192.168.0.1
    SUCCESS: DHCP initialized
    
    Initializing DNS client
         DNS address: 75.75.75.75
    SUCCESS: DNS client initialized
    
    Initializing SNTP client
         SNTP server 0.pool.ntp.org
         SNTP IP address: 157.245.166.169
         SNTP time update: Jun 8, 2021 18:16:50.807 UTC
    SUCCESS: SNTP initialized
    
    Initializing Azure IoT Hub client
         Hub hostname: ***.azure-devices.net
         Device id: mydevice
         Model id: dtmi:azurertos:devkit:gsgmxchip;1
    Connected to IoT Hub
    SUCCESS: Azure IoT Hub client initialized
    

Keep Termite open to monitor device output in the following steps.

View device properties

You can use Azure IoT Explorer to view and manage the properties of your devices. In this section and the following sections, you'll use the Plug and Play capabilities surfaced in IoT Explorer to manage and interact with the MXCHIP DevKit. These capabilities rely on the device model published for the MXCHIP DevKit in the public model repository. You configured IoT Explorer to search this repository for device models earlier in this quickstart. In many cases, you can perform the same action without using plug and play by selecting the same action from the left side menu of your device pane in IoT Explorer; however, using plug and play often provides an enhanced experience. This is because IoT Explorer can read the device model specified by a plug and play device and present information specific to that device.

To access IoT Plug and Play components for the device in IoT Explorer:

  1. From the home view in IoT Explorer, select IoT hubs, then select View devices in this hub.

  2. Select your device.

  3. Select IoT Plug and Play components.

  4. Select Default component. IoT Explorer displays the IoT Plug and Play components that are implemented on your device.

    Screenshot of MXCHIP DevKit default component in IoT Explorer

  5. On the Interface tab, view the JSON content in the device model Description. The JSON contains configuration details for each of the IoT Plug and Play components in the device model.

    Each tab in IoT Explorer corresponds to one of the IoT Plug and Play components in the device model.

    Tab Type Name Description
    Interface Interface MXCHIP Getting Started Guide Example model for the MXCHIP DevKit
    Properties (read-only) Property -- The model currently doesn't have any read-only properties
    Properties (writable) Property telemetryInterval The interval that the device sends telemetry
    Commands Command setLedState Turn the LED on or off
    Telemetry Telemetry temperature The temperature in Celsius

To view device properties using Azure IoT Explorer:

  1. Select the Properties (read-only) tab. Currently, there aren't any read-only properties exposed by the device model.

  2. Select the Properties (writable) tab. It displays the interval that telemetry is sent.

  3. Change the telemetryInterval to 5, and then select Update desired value. Your device now uses this interval to send telemetry.

    Screenshot of setting telemetry interval on MXCHIP DevKit in IoT Explorer

  4. IoT Explorer responds with a notification. You can also observe the update in Termite.

  5. Set the telemetry interval back to 10.

To use Azure CLI to view device properties:

  1. Run the az iot hub device-identity show command.

    az iot hub device-identity show --device-id mydevice --hub-name {YourIoTHubName}
    
  2. Inspect the properties for your device in the console output.

View telemetry

With Azure IoT Explorer, you can view the flow of telemetry from your device to the cloud. Optionally, you can perform the same task using Azure CLI.

To view telemetry in Azure IoT Explorer:

  1. From the IoT Plug and Play components (Default Component) pane for your device in IoT Explorer, select the Telemetry tab. Confirm that Use built-in event hub is set to Yes.

  2. Select Start.

  3. View the telemetry as the device sends messages to the cloud.

    Screenshot of device telemetry in IoT Explorer

    Note

    You can also monitor telemetry from the device by using the Termite app.

  4. Select the Show modeled events checkbox to view the events in the data format specified by the device model.

    Screenshot of modeled telemetry events in IoT Explorer

  5. Select Stop to end receiving events.

To use Azure CLI to view device telemetry:

  1. Run the az iot hub monitor-events command. Use the names that you created previously in Azure IoT for your device and IoT hub.

    az iot hub monitor-events --device-id mydevice --hub-name {YourIoTHubName}
    
  2. View the JSON output in the console.

    {
        "event": {
            "origin": "mydevice",
            "module": "",
            "interface": "dtmi:azurertos:devkit:gsgmxchip;1",
            "component": "",
            "payload": "{\"humidity\":41.21,\"temperature\":31.37,\"pressure\":1005.18}"
        }
    }
    
  3. Select CTRL+C to end monitoring.

Call a direct method on the device

You can also use Azure IoT Explorer to call a direct method that you've implemented on your device. Direct methods have a name, and can optionally have a JSON payload, configurable connection, and method timeout. In this section, you call a method that turns an LED on or off. Optionally, you can perform the same task using Azure CLI.

To call a method in Azure IoT Explorer:

  1. From the IoT Plug and Play components (Default Component) pane for your device in IoT Explorer, select the Commands tab.

  2. For the setLedState command, set the state to true.

  3. Select Send command. You should see a notification in IoT Explorer, and the yellow User LED light on the device should turn on.

    Screenshot of calling the setLedState method in IoT Explorer

  4. Set the state to false, and then select Send command. The yellow User LED should turn off.

  5. Optionally, you can view the output in Termite to monitor the status of the methods.

To use Azure CLI to call a method:

  1. Run the az iot hub invoke-device-method command, and specify the method name and payload. For this method, setting method-payload to true turns on the LED, and setting it to false turns it off.

    az iot hub invoke-device-method --device-id mydevice --method-name setLedState --method-payload true --hub-name {YourIoTHubName}
    

    The CLI console shows the status of your method call on the device, where 204 indicates success.

    {
        "payload": {},
        "status": 200
    }    
    
  2. Check your device to confirm the LED state.

  3. View the Termite terminal to confirm the output messages:

    Receive direct method: setLedState
         Payload: true
    LED is turned ON
    Device twin property sent: {"ledState":true}
    

Troubleshoot and debug

If you experience issues building the device code, flashing the device, or connecting, see Troubleshooting.

For debugging the application, see Debugging with Visual Studio Code.

Clean up resources

If you no longer need the Azure resources created in this quickstart, you can use the Azure CLI to delete the resource group and all of its resources.

Important

Deleting a resource group is irreversible. The resource group and all the resources contained in it are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources.

To delete a resource group by name:

  1. Run the az group delete command. This removes the resource group, the IoT Hub, and the device registration you created.

    az group delete --name MyResourceGroup
    
  2. Run the az group list command to confirm the resource group is deleted.

    az group list
    

Next steps

In this quickstart, you built a custom image that contains Azure RTOS sample code, and then flashed the image to the MXCHIP DevKit device. You also used the Azure CLI and/or IoT Explorer to create Azure resources, connect the MXCHIP DevKit securely to Azure, view telemetry, and send messages.

As a next step, explore the following articles to learn more about using the IoT device SDKs to connect devices to Azure IoT.

Important

Azure RTOS provides OEMs with components to secure communication and to create code and data isolation using underlying MCU/MPU hardware protection mechanisms. However, each OEM is ultimately responsible for ensuring that their device meets evolving security requirements.