{"id":3649,"date":"2022-08-03T00:17:22","date_gmt":"2022-08-03T00:17:22","guid":{"rendered":"https:\/\/www.petecodes.co.uk\/?p=3649"},"modified":"2022-08-04T22:08:07","modified_gmt":"2022-08-04T22:08:07","slug":"connecting-a-raspberry-pi-pico-w-to-microsoft-azure-iot-hub-using-micropython-and-mqtt","status":"publish","type":"post","link":"https:\/\/www.petecodes.co.uk\/connecting-a-raspberry-pi-pico-w-to-microsoft-azure-iot-hub-using-micropython-and-mqtt\/","title":{"rendered":"Connecting a Raspberry Pi Pico W to Microsoft Azure IoT Hub using MicroPython and MQTT"},"content":{"rendered":"\n
In this blog post I’ll take you through how to connect a Raspberry Pi Pico W to a Microsoft Azure IoT Hub using MicroPython and MQTT.<\/p>\n\n\n\n
For this tutorial you’ll need the following;<\/p>\n\n\n\n
Fair warning here… The Amazon links above are my affiliate links and help me to continue creating free content!<\/p>\n\n\n\n
MQTT stands for MQ (Message Queue) Telemetry Transport, and is one of the most popular network protocols for IoT Applications due to it’s light-weight nature.<\/p>\n\n\n\n
MQTT is a Publish-Subscribe protocol, where Devices are able to publish telemetry messages using a Topic and receiving devices can Subscribe to that topic to receive those messages.<\/p>\n\n\n\n
The Microsoft Azure IoT Hub is a service which sits at the edge of Azure, allowing millions of devices to connect to the IoT Hub and then route those messages to other Azure services along the line.<\/p>\n\n\n\n
The IoT Hub has the concept of a Device Registry, where each connecting device has it’s own set of credentials to connect to the IoT Hub.<\/p>\n\n\n\n
IoT Hub is based on Azure Event Hubs, however where Event Hub communication is one way from Sender to Receiver, IoT hubs allows bi-directional communication between the IoT Hub and the connected device.<\/p>\n\n\n\n
IoT Hub supports communication using both AMQP (Advanced Message Queueing Protocol) and MQTT, which is the protocol we’ll be using today.<\/p>\n\n\n\n
The first thing we need to do is set up our Raspberry Pi Pico W with the MicroPython Firmware.<\/p>\n\n\n\n
I’ve already created a blog post helping you to do this here<\/a>, where you can follow along until the end of the “Testing MicroPython on the Raspberry Pi Pico W<\/em>” section.<\/p>\n\n\n\n Now that you have your Raspberry Pi Pico W all set up it’s time to build the circuit.<\/p>\n\n\n\n We’ll be hooking an LED and a Resistor up to our Pico W so we can send messages when we connect the button and control the LED from the IoT Hub.<\/p>\n\n\n\n The circuit you’ll need to build is;<\/p>\n\n\n\n Here we’re connecting a button to Pin 14 and an LED to Pin 15.<\/p>\n\n\n\n In order to complete this tutorial you’ll need an Azure Subscription. You can go ahead and sign up for a free trial here.<\/p>\n\n\n\n We’ll be able to make use of the Free Tier of the Azure IoT Hub, so this won’t cost us a penny.<\/p>\n\n\n\n Once you’ve got your Azure Subscription all set up, head to the Azure Portal and click the “+ Create a Resource” button;<\/p>\n\n\n\n Type “IoT Hub” into the search bar and hit the enter key;<\/p>\n\n\n\n Click on the IoT Hub item in the Marketplace results;<\/p>\n\n\n\n Now click the “Create” button;<\/p>\n\n\n\n On the IoT Hub Basics page, start by selecting your Subscription. <\/p>\n\n\n\n Next, we need to organise our resources, so create a new resource group… Something like “picowresources<\/em><\/strong>“<\/p>\n\n\n\n Next we need to name our IoT Hub, call it something like “picowhub1<\/em><\/strong>“. This name must be unique, so choose something with that in mind. The page will warn you if your name isn’t unique.<\/p>\n\n\n\n Next choose a Region which is somewhere near you. I’ve chose “North Europe<\/em><\/strong>” here as it is close and tends to have the latest goodies.<\/p>\n\n\n\n You should have something resembling the following;<\/p>\n\n\n\n Press the “Next: Networking<\/em><\/strong>” button, we can simply skip this page and press the “Next: Management<\/em><\/strong>” button;<\/p>\n\n\n\n On the “Management” screen, from the “Pricing and Scale tier<\/em><\/strong>” drop down, select “F1: Free tier<\/em><\/strong>“.<\/p>\n\n\n\n Note: You can only have one of these per subscription, and the page will warn you if you’ve already used yours.<\/p>\n\n\n\n We can now hit the blue “Review + create” button in the bottom left corner to review our choices (I’ve opted for a Standard Tier as I’ve already used my free IoT hub for this subscription!);<\/p>\n\n\n\n Finally, press the blue “Create” button to create your IoT Hub.<\/p>\n\n\n\n When the process has completed, click the blue “Go to resource” button to navigate to your IoT Hub;<\/p>\n\n\n\n Now that we have an IoT Hub, we need to create a Device in the IoT Hub Device Registry which will allow our Pico W to connect and send and receive messages.<\/p>\n\n\n\n From the IoT Hub page, within the “Device Management” section in the menu on the left hand side, click the “Devices” menu item;<\/p>\n\n\n\n You’ll now be shown the IoT hub Device Registry, which is a list of all of the devices which have been registered with the IoT Hub.<\/p>\n\n\n\n We need to create a new device for our Pico W to connect to, so click the “+ Add Device” button;<\/p>\n\n\n\n On the “Create a device” page, we can give our device a name, I chose “picow”.<\/p>\n\n\n\n Leave the “Authentication type” set to “Symmetric key”, the “Auto-generate keys” option should be checked, and the “Connect this device to an IoT Hub” set to “Enable”.<\/p>\n\n\n\n Go ahead and press the “Save” button to create your new device;<\/p>\n\n\n\n You will then be returned to the “Devices” page, where you should see your new device… You may need to press the “Refresh” button if it’s not showing yet.<\/p>\n\n\n\n As part of our solution we’ll be sending telemetry messages from our Raspberry Pi Pico W to the IoT Hub.<\/p>\n\n\n\n In order to monitor those messages we’ll be using a tool called the Azure IoT Explorer.<\/p>\n\n\n\n This app will also let us create the relevant connection details to allow our Pico W to connect to the IoT Hub and authenticate.<\/p>\n\n\n\n Go ahead and download and install the latest version of the Azure IoT Hub Explorer from GitHub<\/a>. At the time of writing the file to download is Azure.IoT.Explorer.Preview.0.14.10.msi<\/a><\/p>\n\n\n\n Once you’ve installed the Azure IoT Explorer App, start it up. Once it’s loaded, click the “+ Add connection” button to add a new connection to our IoT hub;<\/p>\n\n\n\n We now need a connection string from the IoT Hub in order to allow the Azure IoT Explorer to connect.<\/p>\n\n\n\n Switch back over to your IoT Hub and from the “Security Settings” menu section, click the “Shared access policies” item;<\/p>\n\n\n\n The “Shared access policies” page allows us to setup authentication for apps and services to connect to our IoT Hub to carry out functions.<\/p>\n\n\n\n We can control the level of access for each app and service by using a “Shared Access policy” with the relevant permissions for the operations we want to perform.<\/p>\n\n\n\n There are a set of built in policies which are created automatically for us when we create an IoT Hub.<\/p>\n\n\n\n The policy we are going to use for the Azure IoT Explorer tool is the “iothubowner” policy which has full access to all operations. Click the “iothubowner” item in the list of policies;<\/p>\n\n\n\n A fly-out will appear with the various details for this policy.<\/p>\n\n\n\n We need the “Primary connection string”, so press the copy button next to this item;<\/p>\n\n\n\n Return to the Azure IoT Explorer tool and paste in the connection string and press the “Save” button;<\/p>\n\n\n\n You’ll now be shown your list of devices with your “picow” device showing as the only device;<\/p>\n\n\n\n As i mentioned earlier, to allow us to communicate between our Pico W and the IoT Hub, we’ll be using MQTT.<\/p>\n\n\n\n To enable this, we’re going to be using a MicroPython Module called umqtt.simple<\/a>.<\/p>\n\n\n\n The easiest way for us to get this Module onto our Pico is to download it directly.<\/p>\n\n\n\n With your Pico W connected to your PC, open up the Thonny IDE and make sure that you’ve selected your Pico W from the Targets in the bottom right corner. It should read “MicroPython (Raspberry Pi Pico)<\/em><\/strong>“;<\/p>\n\n\n\n Next we’re going to run some commands in the “Shell” area at the bottom of the screen to connect our Pico W to our local Wi-Fi.<\/p>\n\n\n\n Place your cursor next to the last set of “>>>” brackets in the Shell;<\/p>\n\n\n\n First we need to import the Network Module, so paste in the following and hit enter;<\/p>\n\n\n\n Next we can define the SSID of our Wi-Fi network. Replace SSID_NAME <\/em><\/strong>with the name of your Wi-Fi;<\/p>\n\n\n\n We can now define the password for our Wi-Fi. Replace WIFI_PASSWORD with your Wi-Fi password;<\/p>\n\n\n\n Next we can create our Wi-Fi connection;<\/p>\n\n\n\n We can now activate the Wi-Fi with;<\/p>\n\n\n\n Finally we can connect to our Wi-Fi with;<\/p>\n\n\n\n Now that we’ve connected to our Wi-Fi, we can install the umqtt.simple MicroPython Module.<\/p>\n\n\n\n First we need to import upip which we’ll use to install the Module;<\/p>\n\n\n\n Finally, we can install the umqtt.simple Module with;<\/p>\n\n\n\n If everything has gone to plan, you should see a message saying “Installing to: \/lib\/<\/em><\/strong>“, followed by an innocious warning about the SSL certificate, and finally that it’s “Installing umqtt.simple<\/em><\/strong>“;<\/p>\n\n\n\n You may now need to hit the “Stop\/Restart” button in the toolbar to reconnect to the Pico W.<\/p>\n\n\n\n Create a new file and paste in the following code;<\/p>\n\n\n\n At the start of the code, we import the various modules needed to support our code;<\/p>\n\n\n\n We make use of the “network<\/em><\/strong>” for our Wi-Fi connection, “time<\/em><\/strong>” for any delays we need and machine to allow us to interact with the Pico W GPIO. <\/p>\n\n\n\n We also import “MQTTClient<\/em><\/strong>” from the “umqtt.simple<\/em><\/strong>” Module.<\/p>\n\n\n\n Next up we setup and connect to Wi-Fi;<\/p>\n\n\n\nStep 2: Build the Circuit<\/h2>\n\n\n\n
Step 3: Create an Azure IoT Hub<\/h2>\n\n\n\n
Step 4: Create an Azure IoT Hub Device<\/h2>\n\n\n\n
Step 5: Connect the Azure IoT Explorer Tool<\/h2>\n\n\n\n
Step 6: Install the umqtt.simple python package<\/h2>\n\n\n\n
import network<\/code><\/pre><\/div>\n\n\n\n
ssid = 'SSID_NAME'<\/code><\/pre><\/div>\n\n\n\n
password = 'WIFI_PASSWORD'<\/code><\/pre><\/div>\n\n\n\n
wlan = network.WLAN(network.STA_IF)<\/code><\/pre><\/div>\n\n\n\n
wlan.active(True)<\/code><\/pre><\/div>\n\n\n\n
wlan.connect(ssid, password)<\/code><\/pre><\/div>\n\n\n\n
import upip<\/code><\/pre><\/div>\n\n\n\n
upip.install('umqtt.simple')<\/code><\/pre><\/div>\n\n\n\n
Step 7: The Azure IoT Hub MQTT Code<\/h2>\n\n\n\n
import network\nimport time\nimport machine\n\nfrom umqtt.simple import MQTTClient\nfrom machine import Pin\n \nssid = 'SSID_NAME'\npassword = 'WIFI_PASSWORD'\n \nwlan = network.WLAN(network.STA_IF)\nwlan.active(True)\nwlan.connect(ssid, password)\n \n# Wait for connect or fail\nmax_wait = 10\nwhile max_wait > 0:\n if wlan.status() < 0 or wlan.status() >= 3:\n break\n max_wait -= 1\n print('waiting for connection...')\n time.sleep(1)\n\n# Handle connection error\nif wlan.status() != 3:\n raise RuntimeError('network connection failed')\nelse:\n print('connected')\n status = wlan.ifconfig()\n print( 'ip = ' + status[0] )\n \nled = Pin(15, Pin.OUT)\nbutton = Pin(14, Pin.IN, Pin.PULL_DOWN)\n\nhostname = 'YOUR_IOT_HUB_NAME.azure-devices.net'\nclientid = 'picow'\nuser_name = 'YOUR_IOT_HUB_NAME.azure-devices.net\/picow\/?api-version=2021-04-12'\npassw = 'YOUR_SAS_TOKEN'\ntopic_pub = b'devices\/picow\/messages\/events\/'\ntopic_msg = b'{"buttonpressed":"1"}'\nport_no = 0\nsubscribe_topic = "devices\/picow\/messages\/devicebound\/#"\n\ndef mqtt_connect():\n\n certificate_path = "baltimore.cer"\n print('Loading Blatimore Certificate')\n with open(certificate_path, 'r') as f:\n cert = f.read()\n print('Obtained Baltimore Certificate')\n sslparams = {'cert':cert}\n \n client = MQTTClient(client_id=clientid, server=hostname, port=port_no, user=user_name, password=passw, keepalive=3600, ssl=True, ssl_params=sslparams)\n client.connect()\n print('Connected to IoT Hub MQTT Broker')\n return client\n\ndef reconnect():\n print('Failed to connect to the MQTT Broker. Reconnecting...')\n time.sleep(5)\n machine.reset()\n\ndef callback_handler(topic, message_receive):\n print("Received message")\n print(message_receive)\n if message_receive.strip() == b'led_on':\n led.value(1)\n else:\n led.value(0)\n\ntry:\n client = mqtt_connect()\n client.set_callback(callback_handler)\n client.subscribe(topic=subscribe_topic)\nexcept OSError as e:\n reconnect()\n\nwhile True:\n \n client.check_msg()\n \n if button.value():\n client.publish(topic_pub, topic_msg)\n time.sleep(0.5)\n else:\n pass<\/code><\/pre><\/div>\n\n\n\n
Explaining the Code<\/h2>\n\n\n\n
Module Imports<\/h3>\n\n\n\n
import network\nimport time\nimport machine\n\nfrom umqtt.simple import MQTTClient\nfrom machine import Pin<\/code><\/pre><\/div>\n\n\n\n
Wi-FI Setup and Connection<\/h3>\n\n\n\n
ssid = 'SSID_NAME'\npassword = 'WIFI_PASSWORD'\n\nwlan = network.WLAN(network.STA_IF)\nwlan.active(True)\nwlan.connect(ssid, password)\n \n# Wait for connect or fail\nmax_wait = 10\nwhile max_wait > 0:\n if wlan.status() < 0 or wlan.status() >= 3:\n break\n max_wait -= 1\n print('waiting for connection...')\n time.sleep(1)\n\n# Handle connection error\nif wlan.status() != 3:\n raise RuntimeError('network connection failed')\nelse:\n print('connected')\n status = wlan.ifconfig()\n print( 'ip = ' + status[0] )<\/code><\/pre><\/div>\n\n\n\n