{"id":151437,"date":"2024-04-17T12:51:16","date_gmt":"2024-04-17T12:51:16","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=151437"},"modified":"2024-05-06T10:47:42","modified_gmt":"2024-05-06T10:47:42","slug":"raspberry-pi-pico-w-mqtt-micropython","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-mqtt-micropython\/","title":{"rendered":"Raspberry Pi Pico W: Getting Started with MQTT (MicroPython)"},"content":{"rendered":"\n<p>This is a complete guide to using MQTT with Raspberry Pi Pico programmed with MicroPython. MQTT is a communication protocol widely used in Home Automation and IoT applications to connect multiple devices. In this tutorial, you&#8217;ll learn how to choose and set up an MQTT broker and how to publish and subscribe to MQTT messages with the Raspberry Pi Pico.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-MQTT-Guide-MicroPython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Getting Started with MQTT MicroPython\" class=\"wp-image-151503\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-MQTT-Guide-MicroPython.jpg?w=1920&amp;quality=100&amp;strip=all&amp;ssl=1 1920w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-MQTT-Guide-MicroPython.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-MQTT-Guide-MicroPython.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-MQTT-Guide-MicroPython.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-MQTT-Guide-MicroPython.jpg?resize=1536%2C864&amp;quality=100&amp;strip=all&amp;ssl=1 1536w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgreen\"><strong>New to the Raspberry Pi Pico?<\/strong>&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/\">Get started with the Raspberry Pi Pico here<\/a>.<\/p>\n\n\n\n<p><strong>Table of Contents:<\/strong><\/p>\n\n\n\n<p>Throughout this guide we&#8217;ll cover the following topics:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#intro-mqtt\" title=\"\">Introducing MQTT<\/a><\/li>\n\n\n\n<li><a href=\"#MQTT-basic-concepts\" title=\"\">MQTT Basic Concepts<\/a><\/li>\n\n\n\n<li><a href=\"#set-up-broker\" title=\"\">Set Up the MQTT Broker<\/a><\/li>\n\n\n\n<li><a href=\"#micropython-modules\" title=\"\">Installing MQTT MicroPython Modules<\/a><\/li>\n\n\n\n<li><a href=\"#configuration-file\" title=\"\">Creating a Configuration File<\/a><\/li>\n\n\n\n<li><a href=\"#publish\" title=\"\">Publishing MQTT Messages<\/a><\/li>\n\n\n\n<li><a href=\"#subscribe\" title=\"\">Subscribing to MQTT Topics<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>Before proceeding, make sure you check the following prerequisites:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"prerequisites\">MicroPython Firmware<\/h3>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board.<\/p>\n\n\n\n<p>The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\">Programming Raspberry Pi Pico using MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Parts Required<\/h3>\n\n\n\n<p>To follow the examples in this tutorial, you need the following parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-pico-w\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Pico W<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/bme280-sensor-module\/\" target=\"_blank\" rel=\"noopener\" title=\"\">BME280<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Breadboard<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Jumper wires<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"intro-mqtt\">Introducing MQTT<\/h2>\n\n\n\n<p><strong>Already familiar with MQTT?<\/strong> <a href=\"#set-up-broker\" title=\"\">Jump to the next section<\/a>.<\/p>\n\n\n\n<p>MQTT stands for&nbsp;Message&nbsp;Queuing&nbsp;Telemetry&nbsp;Transport. MQTT is a simple messaging protocol designed for constrained devices with low bandwidth. So, it\u2019s the perfect solution to exchange data between multiple IoT devices. MQTT communication works as a&nbsp;<em>publish<\/em>&nbsp;and&nbsp;<em>subscribe<\/em>&nbsp;system. Devices can <em>publish <\/em>messages on a specific topic. All devices that are&nbsp;<em>subscribed<\/em>&nbsp;to that topic receive the message.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"268\" height=\"149\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/09\/Publish-subscribe-MQTT.png?resize=268%2C149&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MQTT Publish Subscribe\" class=\"wp-image-108443\"\/><\/figure><\/div>\n\n\n<p>Its main applications include sending messages to control outputs, reading and publishing data from sensor nodes, and much more.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"MQTT-basic-concepts\">MQTT Basic Concepts<\/h2>\n\n\n\n<p>In MQTT, there are a few basic concepts that you need to understand:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Publish\/Subscribe<\/li>\n\n\n\n<li>Messages<\/li>\n\n\n\n<li>Topics<\/li>\n\n\n\n<li>Broker<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Publish\/Subscribe<\/h3>\n\n\n\n<p>The first concept is the<em>&nbsp;<strong>publish<\/strong> and <strong>subscribe<\/strong><\/em>&nbsp;system. In a publish and subscribe system, a device can publish a message on a topic or be subscribed to a particular topic to receive messages.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"743\" height=\"125\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/09\/Publish-Subscribe-Topic-MQTT.png?resize=743%2C125&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Publish Subscribe Topic MQTT\" class=\"wp-image-108444\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/09\/Publish-Subscribe-Topic-MQTT.png?w=743&amp;quality=100&amp;strip=all&amp;ssl=1 743w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/09\/Publish-Subscribe-Topic-MQTT.png?resize=300%2C50&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 743px) 100vw, 743px\" \/><\/figure><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>For example,&nbsp;<strong>Device 1<\/strong>&nbsp;publishes on a topic;<\/li>\n\n\n\n<li><strong>Device 2<\/strong>&nbsp;is subscribed to the same topic that&nbsp;<strong>Device 1<\/strong>&nbsp;is publishing in;<\/li>\n\n\n\n<li>So,&nbsp;<strong>Device 2<\/strong>&nbsp;receives the message.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">MQTT Messages<\/h3>\n\n\n\n<p><em>Messages<\/em> are the information that you want to exchange between your devices. It can be a message like a command to control an output or data like sensor readings.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Topics<\/h3>\n\n\n\n<p>Another important concept is the&nbsp;<em>topics<\/em>. Topics are the way you register interest in incoming messages or how you specify where you want to publish the message.<\/p>\n\n\n\n<p>Topics are represented with strings separated by a forward slash. Each forward slash indicates a topic level. Here\u2019s an example of how you would create a topic for a lamp in your home office:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"442\" height=\"246\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?resize=442%2C246&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MQTT topic name examples\" class=\"wp-image-31609\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?w=442&amp;quality=100&amp;strip=all&amp;ssl=1 442w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?resize=150%2C83&amp;quality=100&amp;strip=all&amp;ssl=1 150w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?resize=300%2C167&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?resize=80%2C45&amp;quality=100&amp;strip=all&amp;ssl=1 80w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?resize=220%2C122&amp;quality=100&amp;strip=all&amp;ssl=1 220w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?resize=180%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 180w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?resize=270%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 270w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/5mqtt-topics.jpg?resize=428%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 428w\" sizes=\"(max-width: 442px) 100vw, 442px\" \/><\/figure><\/div>\n\n\n<p><strong>Note:<\/strong>&nbsp;topics are case-sensitive, which makes the following topics different.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"188\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/7case-sensitive-300x188.jpg?resize=300%2C188&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MQTT topic name examples and differences\" class=\"wp-image-31611\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/7case-sensitive-300x188.jpg?resize=300%2C188&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/7case-sensitive-300x188.jpg?resize=150%2C94&amp;quality=100&amp;strip=all&amp;ssl=1 150w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/7case-sensitive-300x188.jpg?resize=80%2C50&amp;quality=100&amp;strip=all&amp;ssl=1 80w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/7case-sensitive-300x188.jpg?resize=220%2C138&amp;quality=100&amp;strip=all&amp;ssl=1 220w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/7case-sensitive-300x188.jpg?resize=160%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 160w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/7case-sensitive-300x188.jpg?resize=239%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 239w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/figure><\/div>\n\n\n<p>If you would like to turn on a lamp in your home office using MQTT you can imagine the following scenario:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"307\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/MQTT-Example-Raspberry-Pi-Pico-Subscribe.png?resize=750%2C307&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Subscribe to MQTT Topics Example\" class=\"wp-image-151443\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/MQTT-Example-Raspberry-Pi-Pico-Subscribe.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/MQTT-Example-Raspberry-Pi-Pico-Subscribe.png?resize=300%2C123&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<ol class=\"wp-block-list\">\n<li>A device publishes on and off messages on the <span class=\"rnthl rntliteral\">home\/office\/lamp<\/span> topic.<\/li>\n\n\n\n<li>You have a device that controls a lamp (it can be your Raspberry Pi Pico, or any other board or device). The Pico, that controls your lamp, is subscribed to that same topic: <span class=\"rnthl rntliteral\">home\/office\/lamp<\/span>.<\/li>\n\n\n\n<li>So, when a new message is published on that topic, the Pico receives the on or off messages and turns the lamp on or off.<\/li>\n<\/ol>\n\n\n\n<p>The device that is publishing the messages can be another microcontroller board, or a Home Automation controller platform with MQTT support like Node-RED, Home Assistant, Adafruit IO, Domoticz, or OpenHAB, for example.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Broker<\/h3>\n\n\n\n<p>Finally, another important concept is the&nbsp;<em>broker<\/em>.<\/p>\n\n\n\n<p>The MQTT broker is responsible for receiving all messages, filtering&nbsp;the messages,&nbsp;deciding&nbsp;who is interested in them, and then&nbsp;publishing&nbsp;the message to all subscribed clients.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"303\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/mqtt_broker.png?resize=750%2C303&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MQTT Broker overview and how it works\" class=\"wp-image-73565\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/mqtt_broker.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/mqtt_broker.png?resize=300%2C121&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/mqtt_broker.png?resize=250%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 250w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>There are several brokers you can use. For example:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Cloud MQTT Broker solutions<\/strong>: you can use commercial MQTT broker solutions like HiveMQ, for example. You don\u2019t need to set up anything. You just need to create an account and you\u2019re ready to go (this is the one we\u2019ll use in this tutorial).<\/li>\n\n\n\n<li><strong>Local MQTT broker<\/strong>: you can install an MQTT broker locally on your computer or on your Raspberry Pi. The <strong>Mosquitto<\/strong> MQTT broker hosted on a Raspberry Pi is widely used in many hobbyist projects and it\u2019s also the solution we use more often.<\/li>\n\n\n\n<li><strong>Cloud MQTT Broker<\/strong>: as an alternative to the previous solution, you can also install MQTT broker on your own cloud server.<\/li>\n<\/ol>\n\n\n\n<p>In summary:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>MQTT is a communication protocol very useful in Internet of Things projects;<\/li>\n\n\n\n<li>In MQTT, devices can publish messages on specific topics and can be subscribed to topics to receive messages;<\/li>\n\n\n\n<li>You need a broker when using MQTT. It receives all the messages and sends them to the subscribed devices.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"set-up-broker\">Set Up the MQTT Broker<\/h2>\n\n\n\n<p>To use MQTT, you need an MQTT broker. The broker receives all MQTT messages and sends them to all subscribed clients.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MQTT Broker Solutions<\/h3>\n\n\n\n<p>There are many MQTT broker solutions you can use. Here we\u2019ll describe the ones we\u2019re more familiar with:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\">Mosquitto MQTT broker installed on a Raspberry Pi<\/a>: this is an open-source MQTT broker that you can install locally on your Raspberry Pi (the Raspberry Pi computer, not the Pico board). We\u2019ve been using this option a lot and it always worked well for us.<\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/cloud-mqtt-mosquitto-broker-access-anywhere-digital-ocean\/\">Mosquitto MQTT broker installed on a cloud server<\/a>: a great alternative if you want your broker to be accessible worldwide.<\/li>\n\n\n\n<li><a href=\"https:\/\/www.hivemq.com\/\" target=\"_blank\" rel=\"noopener nofollow\" title=\"\">HiveMQ Broker<\/a>: this is a cloud MQTT broker service. You just need to create an account and choose a plan. They provide a free plan that is suitable for most IoT hobbyist projects.<\/li>\n<\/ol>\n\n\n\n<p>For simplicity, in this guide we\u2019ll use HiveMQ because you don\u2019t need to install or configure anything like in the Mosquitto MQTT broker. You just need to create an account, set up a cluster and you\u2019re ready to go. Alternatively, if you want to use Mosquitto broker or any other broker of your choice, don\u2019t worry. The code will be compatible with any broker as long as you fill in the right broker details.<\/p>\n\n\n\n<p>Regardless of the MQTT broker you use, you need to have the MQTT URL, username, and password before proceeding to the following sections.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Setting Up the HiveMQ MQTT Broker<\/h3>\n\n\n\n<p>In this section, we\u2019ll show you how to set up your HiveMQ MQTT broker.<\/p>\n\n\n\n<p><strong>1)<\/strong> First, you need to create an account. Go to <a href=\"https:\/\/www.hivemq.com\/\" target=\"_blank\" rel=\"noopener nofollow\" title=\"\">hivemq.com<\/a> and click on <strong>Start free<\/strong>.<\/p>\n\n\n\n<p><strong>2)<\/strong> Choose the <strong>HiveMQ Cloud plan<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"488\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-free-plan.png?resize=750%2C488&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ MQTT broker different plans\" class=\"wp-image-151444\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-free-plan.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-free-plan.png?resize=300%2C195&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p><strong>3)<\/strong> Login or create a new account and fill in the details to complete your profile.<\/p>\n\n\n\n<p><strong>4)<\/strong> You should have a new cluster created by default. Click on <strong>Manage Cluster<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"349\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQT-manage-cluster-1.png?resize=750%2C349&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ Manage Cluster\" class=\"wp-image-151506\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQT-manage-cluster-1.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQT-manage-cluster-1.png?resize=300%2C140&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p><strong>5)<\/strong> Copy the Cluster URL to a safe place because you\u2019ll need it later.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"532\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-cluster-url-1.png?resize=750%2C532&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ Cluster URL\" class=\"wp-image-151454\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-cluster-url-1.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-cluster-url-1.png?resize=300%2C213&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p><strong>6)<\/strong> Click on the <strong>Access Management<\/strong> tab at the top.<\/p>\n\n\n\n<p><strong>7)<\/strong> Fill in the form with a username and password. You\u2019ll need to remember these details later to connect to the MQTT broker. Set the permission to <em>Publish and Subscribe<\/em>.<\/p>\n\n\n\n<p><strong>8)<\/strong> Finally, click <strong>Create Credential<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"389\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-create-credential.png?resize=750%2C389&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ Access Management\" class=\"wp-image-151449\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-create-credential.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-create-credential.png?resize=300%2C156&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>If your credentials are successfully created, your MQTT broker is set up.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"120\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-credentials-created.png?resize=750%2C120&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"username and permission hivemq\" class=\"wp-image-151450\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-credentials-created.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/HiveMQ-credentials-created.png?resize=300%2C48&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Make sure you have the following information before proceeding to the next section:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>MQTT Server:\n<ul class=\"wp-block-list\">\n<li>Cluster URL (for HiveMQ)<\/li>\n\n\n\n<li>MQTT broker IP address or URL (if you\u2019re using a different MQTT Broker)<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>MQTT username<\/li>\n\n\n\n<li>MQTT password<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"micropython-modules\">Installing MQTT MicroPython Modules<\/h2>\n\n\n\n<p>To write code in MicroPython to use the MQTT communication protocol, we\u2019ll use two MQTT modules: <em>umqtt.simply.py<\/em>, and <em>umqtt.robust.py<\/em>.<\/p>\n\n\n\n<p>Follow the next steps to upload the modules to your Raspberry Pi Pico.<\/p>\n\n\n\n<p>With the Raspberry Pi Pico connected to your computer and with a connection established with Thonny IDE, go to <strong>View<\/strong> &gt; <strong>Files<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"428\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/thonny-ide-view-files.png?resize=750%2C428&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE View Files\" class=\"wp-image-151455\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/thonny-ide-view-files.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/thonny-ide-view-files.png?resize=300%2C171&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>A new sidebar will show up with all the files on the Raspberry Pi Pico filesystem.<\/p>\n\n\n\n<p>Right-click on the Raspberry Pi Pico sidebar and click on <strong>New directory\u2026<\/strong><\/p>\n\n\n\n<p>This new directory should be called <strong><em>umqtt<\/em><\/strong>. Click <strong>Ok<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"257\" height=\"170\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Thonny-IDE-Create-directory-umqtt.png?resize=257%2C170&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE cerating umqtt folder\" class=\"wp-image-151456\"\/><\/figure><\/div>\n\n\n<p>The new directory will show up on the left sidebar.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"288\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/umqtt-folder-created-Thonny-IDE.png?resize=750%2C288&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE cerating umqtt folder\" class=\"wp-image-151457\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/umqtt-folder-created-Thonny-IDE.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/umqtt-folder-created-Thonny-IDE.png?resize=300%2C115&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Right-click on the <em>umqtt <\/em>folder and select <strong>New file\u2026<\/strong><\/p>\n\n\n\n<p>That new file should be called<em> simple.py<\/em>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"738\" height=\"421\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-umqtt-simple-file.png?resize=738%2C421&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE Creating umqtt file\" class=\"wp-image-151458\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-umqtt-simple-file.png?w=738&amp;quality=100&amp;strip=all&amp;ssl=1 738w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-umqtt-simple-file.png?resize=300%2C171&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 738px) 100vw, 738px\" \/><\/figure><\/div>\n\n\n<p>Copy the <em>simple.py<\/em> code into that new file. The code can be found on the link below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/blob\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/mqtt\/umqtt\/simple.py\" target=\"_blank\" rel=\"noopener\" title=\"\">Click here to download <em>simple.py<\/em><\/a><\/li>\n<\/ul>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># forked from: https:\/\/github.com\/micropython\/micropython-lib\/tree\/master\/micropython\/umqtt.simple\nimport usocket as socket\nimport ustruct as struct\nfrom ubinascii import hexlify\n\n\nclass MQTTException(Exception):\n    pass\n\n\nclass MQTTClient:\n    def __init__(\n        self,\n        client_id,\n        server,\n        port=0,\n        user=None,\n        password=None,\n        keepalive=0,\n        ssl=False,\n        ssl_params={},\n    ):\n        if port == 0:\n            port = 8883 if ssl else 1883\n        self.client_id = client_id\n        self.sock = None\n        self.server = server\n        self.port = port\n        self.ssl = ssl\n        self.ssl_params = ssl_params\n        self.pid = 0\n        self.cb = None\n        self.user = user\n        self.pswd = password\n        self.keepalive = keepalive\n        self.lw_topic = None\n        self.lw_msg = None\n        self.lw_qos = 0\n        self.lw_retain = False\n\n    def _send_str(self, s):\n        self.sock.write(struct.pack(&quot;!H&quot;, len(s)))\n        self.sock.write(s)\n\n    def _recv_len(self):\n        n = 0\n        sh = 0\n        while 1:\n            b = self.sock.read(1)[0]\n            n |= (b &amp; 0x7F) &lt;&lt; sh\n            if not b &amp; 0x80:\n                return n\n            sh += 7\n\n    def set_callback(self, f):\n        self.cb = f\n\n    def set_last_will(self, topic, msg, retain=False, qos=0):\n        assert 0 &lt;= qos &lt;= 2\n        assert topic\n        self.lw_topic = topic\n        self.lw_msg = msg\n        self.lw_qos = qos\n        self.lw_retain = retain\n\n    def connect(self, clean_session=True):\n        self.sock = socket.socket()\n        addr = socket.getaddrinfo(self.server, self.port)[0][-1]\n        self.sock.connect(addr)\n        if self.ssl:\n            import ssl\n\n            self.sock = ssl.wrap_socket(self.sock, **self.ssl_params)\n        premsg = bytearray(b&quot;\\x10\\0\\0\\0\\0\\0&quot;)\n        msg = bytearray(b&quot;\\x04MQTT\\x04\\x02\\0\\0&quot;)\n\n        sz = 10 + 2 + len(self.client_id)\n        msg[6] = clean_session &lt;&lt; 1\n        if self.user is not None:\n            sz += 2 + len(self.user) + 2 + len(self.pswd)\n            msg[6] |= 0xC0\n        if self.keepalive:\n            assert self.keepalive &lt; 65536\n            msg[7] |= self.keepalive &gt;&gt; 8\n            msg[8] |= self.keepalive &amp; 0x00FF\n        if self.lw_topic:\n            sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)\n            msg[6] |= 0x4 | (self.lw_qos &amp; 0x1) &lt;&lt; 3 | (self.lw_qos &amp; 0x2) &lt;&lt; 3\n            msg[6] |= self.lw_retain &lt;&lt; 5\n\n        i = 1\n        while sz &gt; 0x7F:\n            premsg[i] = (sz &amp; 0x7F) | 0x80\n            sz &gt;&gt;= 7\n            i += 1\n        premsg[i] = sz\n\n        self.sock.write(premsg, i + 2)\n        self.sock.write(msg)\n        # print(hex(len(msg)), hexlify(msg, &quot;:&quot;))\n        self._send_str(self.client_id)\n        if self.lw_topic:\n            self._send_str(self.lw_topic)\n            self._send_str(self.lw_msg)\n        if self.user is not None:\n            self._send_str(self.user)\n            self._send_str(self.pswd)\n        resp = self.sock.read(4)\n        assert resp[0] == 0x20 and resp[1] == 0x02\n        if resp[3] != 0:\n            raise MQTTException(resp[3])\n        return resp[2] &amp; 1\n\n    def disconnect(self):\n        self.sock.write(b&quot;\\xe0\\0&quot;)\n        self.sock.close()\n\n    def ping(self):\n        self.sock.write(b&quot;\\xc0\\0&quot;)\n\n    def publish(self, topic, msg, retain=False, qos=0):\n        pkt = bytearray(b&quot;\\x30\\0\\0\\0&quot;)\n        pkt[0] |= qos &lt;&lt; 1 | retain\n        sz = 2 + len(topic) + len(msg)\n        if qos &gt; 0:\n            sz += 2\n        assert sz &lt; 2097152\n        i = 1\n        while sz &gt; 0x7F:\n            pkt[i] = (sz &amp; 0x7F) | 0x80\n            sz &gt;&gt;= 7\n            i += 1\n        pkt[i] = sz\n        # print(hex(len(pkt)), hexlify(pkt, &quot;:&quot;))\n        self.sock.write(pkt, i + 1)\n        self._send_str(topic)\n        if qos &gt; 0:\n            self.pid += 1\n            pid = self.pid\n            struct.pack_into(&quot;!H&quot;, pkt, 0, pid)\n            self.sock.write(pkt, 2)\n        self.sock.write(msg)\n        if qos == 1:\n            while 1:\n                op = self.wait_msg()\n                if op == 0x40:\n                    sz = self.sock.read(1)\n                    assert sz == b&quot;\\x02&quot;\n                    rcv_pid = self.sock.read(2)\n                    rcv_pid = rcv_pid[0] &lt;&lt; 8 | rcv_pid[1]\n                    if pid == rcv_pid:\n                        return\n        elif qos == 2:\n            assert 0\n\n    def subscribe(self, topic, qos=0):\n        assert self.cb is not None, &quot;Subscribe callback is not set&quot;\n        pkt = bytearray(b&quot;\\x82\\0\\0\\0&quot;)\n        self.pid += 1\n        struct.pack_into(&quot;!BH&quot;, pkt, 1, 2 + 2 + len(topic) + 1, self.pid)\n        # print(hex(len(pkt)), hexlify(pkt, &quot;:&quot;))\n        self.sock.write(pkt)\n        self._send_str(topic)\n        self.sock.write(qos.to_bytes(1, &quot;little&quot;))\n        while 1:\n            op = self.wait_msg()\n            if op == 0x90:\n                resp = self.sock.read(4)\n                # print(resp)\n                assert resp[1] == pkt[2] and resp[2] == pkt[3]\n                if resp[3] == 0x80:\n                    raise MQTTException(resp[3])\n                return\n\n    # Wait for a single incoming MQTT message and process it.\n    # Subscribed messages are delivered to a callback previously\n    # set by .set_callback() method. Other (internal) MQTT\n    # messages processed internally.\n    def wait_msg(self):\n        res = self.sock.read(1)\n        self.sock.setblocking(True)\n        if res is None:\n            return None\n        if res == b&quot;&quot;:\n            raise OSError(-1)\n        if res == b&quot;\\xd0&quot;:  # PINGRESP\n            sz = self.sock.read(1)[0]\n            assert sz == 0\n            return None\n        op = res[0]\n        if op &amp; 0xF0 != 0x30:\n            return op\n        sz = self._recv_len()\n        topic_len = self.sock.read(2)\n        topic_len = (topic_len[0] &lt;&lt; 8) | topic_len[1]\n        topic = self.sock.read(topic_len)\n        sz -= topic_len + 2\n        if op &amp; 6:\n            pid = self.sock.read(2)\n            pid = pid[0] &lt;&lt; 8 | pid[1]\n            sz -= 2\n        msg = self.sock.read(sz)\n        self.cb(topic, msg)\n        if op &amp; 6 == 2:\n            pkt = bytearray(b&quot;\\x40\\x02\\0\\0&quot;)\n            struct.pack_into(&quot;!H&quot;, pkt, 2, pid)\n            self.sock.write(pkt)\n        elif op &amp; 6 == 4:\n            assert 0\n        return op\n\n    # Checks whether a pending message from server is available.\n    # If not, returns immediately with None. Otherwise, does\n    # the same processing as wait_msg.\n    def check_msg(self):\n        self.sock.setblocking(False)\n        return self.wait_msg()\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/mqtt\/umqtt\/simple.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>After copying the code to the <em>simple.py<\/em> file, save the code.<\/p>\n\n\n\n<p>Now, if you expand the <em>umqtt <\/em>folder, you\u2019ll see that the <em>simple.py<\/em> file is there.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"321\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/install-MQTT-libraries-simple-py-created.png?resize=750%2C321&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE simple.py file created\" class=\"wp-image-151461\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/install-MQTT-libraries-simple-py-created.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/install-MQTT-libraries-simple-py-created.png?resize=300%2C128&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Right-click again on the <em>umqtt<\/em> folder and create another file by clicking on <strong>New file\u2026<\/strong><\/p>\n\n\n\n<p>This new file should be called <em>robust.py<\/em>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"192\" height=\"155\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/install-libraries-MQTT-Thonny-IDE-robust-py.png?resize=192%2C155&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"create robust.py thonny ide mqtt\" class=\"wp-image-151462\"\/><\/figure><\/div>\n\n\n<p>Copy the <em>robust.py<\/em> code into that new file. The code can be found on the link below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/blob\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/mqtt\/umqtt\/robust.py\" target=\"_blank\" rel=\"noopener\" title=\"\">Click here to download <em>robust.py<\/em><\/a><\/li>\n<\/ul>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># forked from: https:\/\/github.com\/micropython\/micropython-lib\/tree\/master\/micropython\/umqtt.robust\nimport utime\nfrom . import simple\n\n\nclass MQTTClient(simple.MQTTClient):\n    DELAY = 2\n    DEBUG = False\n\n    def delay(self, i):\n        utime.sleep(self.DELAY)\n\n    def log(self, in_reconnect, e):\n        if self.DEBUG:\n            if in_reconnect:\n                print(&quot;mqtt reconnect: %r&quot; % e)\n            else:\n                print(&quot;mqtt: %r&quot; % e)\n\n    def reconnect(self):\n        i = 0\n        while 1:\n            try:\n                return super().connect(False)\n            except OSError as e:\n                self.log(True, e)\n                i += 1\n                self.delay(i)\n\n    def publish(self, topic, msg, retain=False, qos=0):\n        while 1:\n            try:\n                return super().publish(topic, msg, retain, qos)\n            except OSError as e:\n                self.log(False, e)\n            self.reconnect()\n\n    def wait_msg(self):\n        while 1:\n            try:\n                return super().wait_msg()\n            except OSError as e:\n                self.log(False, e)\n            self.reconnect()\n\n    def check_msg(self, attempts=2):\n        while attempts:\n            self.sock.setblocking(False)\n            try:\n                return super().wait_msg()\n            except OSError as e:\n                self.log(False, e)\n            self.reconnect()\n            attempts -= 1\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/mqtt\/umqtt\/robust.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>After copying the code to the <em>robust.py<\/em> file, save the code. At this moment, you should have the <em>umqtt<\/em> folder with the <em>simple.py<\/em> and<em> robust.py<\/em> files inside.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"279\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/umqtt-modules-installed-successfully-thonny-ide.png?resize=750%2C279&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MQTT MicroPython modules Thonny IDE\" class=\"wp-image-151464\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/umqtt-modules-installed-successfully-thonny-ide.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/umqtt-modules-installed-successfully-thonny-ide.png?resize=300%2C112&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>The modules required for MQTT were successfully uploaded to the Raspberry Pi Pico.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"configuration-file\">Creating a Configuration File<\/h2>\n\n\n\n<p>We\u2019ll create a configuration file to save the SSID, password, and your MQTT broker details: URL, username, and password.<\/p>\n\n\n\n<p>Create a new file called <em>config.py<\/em> on Thonny IDE and copy the following code:<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\">wifi_ssid = 'REPLACE_WITH_YOUR_SSID'\nwifi_password = 'REPLACE_WITH_YOUR_PASSWORD'\nmqtt_server = b'MQTT_BROKER_URL'\nmqtt_username = b'BROKER_USERNAME'\nmqtt_password = b'BROKER_PASSWORD'\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/mqtt\/config.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>Replace the variables with your own details.<\/p>\n\n\n\n<p>If you&#8217;re using a<a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\" title=\"\"> local Mosquitto MQTT broker<\/a>, you should pass the broker IP address without the port. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>mqtt_server = b'192.168.1.79'<\/code><\/pre>\n\n\n\n<p>Then, go to <strong>File<\/strong> &gt; <strong>Save as&#8230;<\/strong> and select <strong>Raspberry Pi Pico<\/strong>. Save the file as <em>config.py<\/em> (overwrite any existing files with the same name). This file should be saved on the root of the Raspberry Pi Pico and <strong>not <\/strong>inside the <em>umqtt <\/em>folder.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"publish\">Publishing MQTT Messages<\/h2>\n\n\n\n<p>In this example, you\u2019ll learn how to publish MQTT messages on a certain topic with your Raspberry Pi Pico. As an example, we\u2019ll publish temperature, humidity, and pressure readings from a BME280 sensor. Alternatively, you can use any other sensor or random values to test the project and concepts.<\/p>\n\n\n\n<p><strong>Before proceeding, make sure that:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You connect a BME280 sensor to the Raspberry Pi Pico. Use GPIO 4 (SDA) and GPIO 5 (SCL); <\/li>\n\n\n\n<li>You must upload the <em>BME280.py<\/em> module to control the BME280 with your Raspberry Pi Pico \u2014<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-bme280-micropython\/#bme280-micropython-library\" title=\"\"> check this tutorial<\/a> and install the library as indicated there.<\/li>\n<\/ul>\n\n\n\n<p class=\"rntbox rntclgreen\"><strong>Related content<\/strong>: Raspberry Pi Pico: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-bme280-micropython\/\" title=\"\">BME280 Get Temperature, Humidity, and Pressure (MicroPython)<\/a><\/p>\n\n\n\n<p>The following code gets sensor data from the BME280 sensor and publishes the readings on different MQTT topics.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-w-mqtt-micropython\/\n\nfrom machine import Pin, I2C\nfrom time import sleep\nimport network\nfrom umqtt.simple import MQTTClient\nimport config\nimport BME280\n\n# Constants for MQTT Topics\nMQTT_TOPIC_TEMPERATURE = 'pico\/temperature'\nMQTT_TOPIC_PRESSURE = 'pico\/pressure'\nMQTT_TOPIC_HUMIDITY = 'pico\/humidity'\n\n# MQTT Parameters\nMQTT_SERVER = config.mqtt_server\nMQTT_PORT = 0\nMQTT_USER = config.mqtt_username\nMQTT_PASSWORD = config.mqtt_password\nMQTT_CLIENT_ID = b&quot;raspberrypi_picow&quot;\nMQTT_KEEPALIVE = 7200\nMQTT_SSL = True   # set to False if using local Mosquitto MQTT broker\nMQTT_SSL_PARAMS = {'server_hostname': MQTT_SERVER}\n\n# Initialize I2C communication\ni2c = I2C(id=0, scl=Pin(5), sda=Pin(4), freq=10000)\n\n# Initialize BME280 sensor\nbme = BME280.BME280(i2c=i2c, addr=0x76)\n\ndef get_sensor_readings():\n    temp = bme.temperature[:-1]\n    hum = bme.humidity[:-1]\n    pres = bme.pressure[:-3]\n    return temp, hum, pres\n\ndef initialize_wifi(ssid, password):\n    wlan = network.WLAN(network.STA_IF)\n    wlan.active(True)\n\n    # Connect to the network\n    wlan.connect(ssid, password)\n\n    # Wait for Wi-Fi connection\n    connection_timeout = 10\n    while connection_timeout &gt; 0:\n        if wlan.status() &gt;= 3:\n            break\n        connection_timeout -= 1\n        print('Waiting for Wi-Fi connection...')\n        sleep(1)\n\n    # Check if connection is successful\n    if wlan.status() != 3:\n        return False\n    else:\n        print('Connection successful!')\n        network_info = wlan.ifconfig()\n        print('IP address:', network_info[0])\n        return True\n\ndef connect_mqtt():\n    try:\n        client = MQTTClient(client_id=MQTT_CLIENT_ID,\n                            server=MQTT_SERVER,\n                            port=MQTT_PORT,\n                            user=MQTT_USER,\n                            password=MQTT_PASSWORD,\n                            keepalive=MQTT_KEEPALIVE,\n                            ssl=MQTT_SSL,\n                            ssl_params=MQTT_SSL_PARAMS)\n        client.connect()\n        return client\n    except Exception as e:\n        print('Error connecting to MQTT:', e)\n        raise  # Re-raise the exception to see the full traceback\n\ndef publish_mqtt(topic, value):\n    client.publish(topic, value)\n    print(topic)\n    print(value)\n    print(&quot;Publish Done&quot;)\n\ntry:\n    if not initialize_wifi(config.wifi_ssid, config.wifi_password):\n        print('Error connecting to the network... exiting program')\n    else:\n        # Connect to MQTT broker, start MQTT client\n        client = connect_mqtt()\n        while True:\n            # Read sensor data\n            temperature, humidity, pressure = get_sensor_readings()\n\n            # Publish as MQTT payload\n            publish_mqtt(MQTT_TOPIC_TEMPERATURE, str(temperature))\n            publish_mqtt(MQTT_TOPIC_PRESSURE, str(pressure))\n            publish_mqtt(MQTT_TOPIC_HUMIDITY, str(humidity))\n\n            # Delay 10 seconds\n            sleep(10)\n\nexcept Exception as e:\n    print('Error:', e)\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/mqtt\/mqtt_publish.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>We use the following MQTT topics to publish data:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For the temperature \u2014 <span class=\"rnthl rntliteral\">pico\/temperature<\/span><\/li>\n\n\n\n<li>For the humidity \u2014 <span class=\"rnthl rntliteral\">pico\/humidity<\/span><\/li>\n\n\n\n<li>For the pressure \u2014 <span class=\"rnthl rntliteral\">pico\/pressure<\/span><\/li>\n<\/ul>\n\n\n\n<p>And the workflow to publish data is the following:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Connect the Pico to the internet;<\/li>\n\n\n\n<li>Connect to the MQTT broker;<\/li>\n\n\n\n<li>After connecting to the broker, we can continuously publish MQTT messages.<\/li>\n<\/ol>\n\n\n\n<p>Let\u2019s take a look at how the code works.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Importing Libraries<\/h4>\n\n\n\n<p>First, we need to import the required libraries. We import the <span class=\"rnthl rntliteral\">Pin<\/span> and <span class=\"rnthl rntliteral\">I2C<\/span> from the <span class=\"rnthl rntliteral\">machine<\/span> module, and the <span class=\"rnthl rntliteral\">BME280<\/span> to interface with the BME280 sensor. The <span class=\"rnthl rntliteral\">network<\/span> module to connect to Wi-Fi and the <span class=\"rnthl rntliteral\">MQTTClient<\/span> class from umqtt.simple to use MQTT functions.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from machine import Pin, I2C\nfrom time import sleep\nimport network\nfrom umqtt.simple import MQTTClient\nimport config\nimport BME280<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">MQTT Topics<\/h4>\n\n\n\n<p>On the following variables we save the topics where we want to publish our messages (sensor readings).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Constants for MQTT Topics\nMQTT_TOPIC_TEMPERATURE = 'pico\/temperature'\nMQTT_TOPIC_PRESSURE = 'pico\/pressure'\nMQTT_TOPIC_HUMIDITY = 'pico\/humidity'<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">MQTT Details<\/h4>\n\n\n\n<p>In the following lines we set up the MQTT parameters to connect to our MQTT broker. We import the server URL, username, and password from the <strong><em>config.py<\/em><\/strong> file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># MQTT Parameters\nMQTT_SERVER = config.mqtt_server\nMQTT_PORT = 0\nMQTT_USER = config.mqtt_username\nMQTT_PASSWORD = config.mqtt_password\nMQTT_CLIENT_ID = b\"raspberrypi_picow\"\nMQTT_KEEPALIVE = 7200\nMQTT_SSL = True\nMQTT_SSL_PARAMS = {'server_hostname': MQTT_SERVER}<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">MQTT_CLIENT_ID<\/span> should be a unique ID to identify the MQTT client. You can give it wherever name you want, but it needs to be unique among the MQTT clients connected to your broker. In our case, it\u2019s <span class=\"rnthl rntliteral\">raspberrypi_picow<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>MQTT_CLIENT_ID = b\"raspberrypi_picow\"<\/code><\/pre>\n\n\n\n<p><strong>If you\u2019re using a local Mosquitto MQTT broker, you should set the <span class=\"rnthl rntliteral\">MQTT_SSL<\/span> parameter to <span class=\"rnthl rntliteral\">False<\/span>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code><strong>MQTT_SSL = False<\/strong><\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">BME280 Sensor<\/h4>\n\n\n\n<p>In the following lines, we initialize the BME280 sensor and create a function called <span class=\"rnthl rntliteral\">get_sensor_readings()<\/span> that gets data from the BME280 and returns the temperature, humidity, and pressure.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Initialize I2C communication\ni2c = I2C(id=0, scl=Pin(5), sda=Pin(4), freq=10000)\n\n# Initialize BME280 sensor\nbme = BME280.BME280(i2c=i2c, addr=0x76)\n\ndef get_sensor_readings():\n    temp = bme.temperature&#091;:-1]\n    hum = bme.humidity&#091;:-1]\n    pres = bme.pressure&#091;:-3]\n    return temp, hum, pres<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Initialize Wi-Fi<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">initialize_wifi()<\/span> function connects the Raspberry Pi Pico to a network. You need to initialize Wi-Fi to connect to the MQTT broker and exchange messages.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def initialize_wifi(ssid, password):\n    wlan = network.WLAN(network.STA_IF)\n    wlan.active(True)\n\n    # Connect to the network\n    wlan.connect(ssid, password)\n\n    # Wait for Wi-Fi connection\n    connection_timeout = 10\n    while connection_timeout &gt; 0:\n        if wlan.status() &gt;= 3:\n            break\n        connection_timeout -= 1\n        print('Waiting for Wi-Fi connection...')\n        sleep(1)\n\n    # Check if connection is successful\n    if wlan.status() != 3:\n        return False\n    else:\n        print('Connection successful!')\n        network_info = wlan.ifconfig()\n        print('IP address:', network_info&#091;0])\n        return True<\/code><\/pre>\n\n\n\n<p class=\"rntbox rntclgreen\"><strong>You may also like:<\/strong> <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\">Raspberry Pi Pico: Web Server (MicroPython)<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Connect to MQTT<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">connect_mqtt()<\/span> function connects to the MQTT broker using the details about the MQTT broker you\u2019ve set up previously.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def connect_mqtt():\n    try:\n        client = MQTTClient(client_id=MQTT_CLIENT_ID,\n                            server=MQTT_SERVER,\n                            port=MQTT_PORT,\n                            user=MQTT_USER,\n                            password=MQTT_PASSWORD,\n                            keepalive=MQTT_KEEPALIVE,\n                            ssl=MQTT_SSL,\n                            ssl_params=MQTT_SSL_PARAMS)\n        client.connect()\n        return client\n    except Exception as e:\n        print('Error connecting to MQTT:', e)\n        raise  # Re-raise the exception to see the full traceback<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Publish MQTT Messages<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">publish_mqtt()<\/span> function publishes a message on a topic. Pass as argument the topic and the message you want to send.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def publish_mqtt(topic, value):\n    client.publish(topic, value)\n    print(topic)\n    print(value)\n    print(\"Publish Done\")<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Publishing Sensor Readings<\/h4>\n\n\n\n<p>Now that we have all functions and variables defined, we can finally connect to the internet and to the broker to start publishing messages.<\/p>\n\n\n\n<p>First, we try to connect to Wi-Fi using the SSID and password stored on the <em><strong>config.py<\/strong><\/em> file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>try:\n    if not initialize_wifi(config.wifi_ssid, config.wifi_password):\n        print('Error connecting to the network... exiting program')<\/code><\/pre>\n\n\n\n<p>If we succeed in connecting to Wi-Fi, we can connect to the MQTT broker.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>else:\n    # Connect to MQTT broker, start MQTT client\n    client = connect_mqtt()<\/code><\/pre>\n\n\n\n<p>After connecting, we get new sensor data and save it on the temperature, humidity, and pressure variables.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Read sensor data\ntemperature, humidity, pressure = get_sensor_readings()<\/code><\/pre>\n\n\n\n<p>Finally, we use the <span class=\"rnthl rntliteral\">publish_mqtt()<\/span> function to publish the readings on their specific topics. The message must be a string. So, we need to convert the sensor data using the <span class=\"rnthl rntliteral\">str()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Publish as MQTT payload\npublish_mqtt(MQTT_TOPIC_TEMPERATURE, str(temperature))\npublish_mqtt(MQTT_TOPIC_PRESSURE, str(pressure))\npublish_mqtt(MQTT_TOPIC_HUMIDITY, str(humidity))<\/code><\/pre>\n\n\n\n<p>We publish new readings every 10 seconds.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sleep(10)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Testing the Code<\/h3>\n\n\n\n<p>Run the previous code on your Raspberry Pi Pico. It will connect to the internet and start publishing messages every 10 seconds.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"755\" height=\"820\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/publishing-mqtt-messages-thonny-ide.png?resize=755%2C820&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"RPi Pico Thonny IDE Publish MQTT Messages\" class=\"wp-image-151470\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/publishing-mqtt-messages-thonny-ide.png?w=755&amp;quality=100&amp;strip=all&amp;ssl=1 755w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/publishing-mqtt-messages-thonny-ide.png?resize=276%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 276w\" sizes=\"(max-width: 755px) 100vw, 755px\" \/><\/figure><\/div>\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-BME280-circuit.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico connected to BME280\" class=\"wp-image-136809\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-BME280-circuit.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-BME280-circuit.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Now, we can check if we can receive the messages on an MQTT Client subscribed to those topics. HiveMQ provides a Web Client interface that allows you to subscribe and publish to topics for testing purposes.<\/p>\n\n\n\n<p>Go to your HiveMQ cluster, and click on the <strong>Web Client<\/strong> tab. Insert your MQTT broker username and password and click <strong>Connect Client<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"273\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-hivemq-http-subscribe-1.png?resize=750%2C273&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ Web Client\" class=\"wp-image-151491\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-hivemq-http-subscribe-1.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-hivemq-http-subscribe-1.png?resize=300%2C109&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Subscribe to the topics that the Raspberry Pi Pico is publishing to. Fill in <span class=\"rnthl rntliteral\">pico\/temperature<\/span> and then click on <strong>+Subscribe<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"569\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-subscribe-1.png?resize=750%2C569&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ Web Client Subscribe to Topics\" class=\"wp-image-151493\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-subscribe-1.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-subscribe-1.png?resize=300%2C228&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p> Repeat the process for <span class=\"rnthl rntliteral\">pico\/humidity<\/span> and <span class=\"rnthl rntliteral\">pico\/pressure<\/span>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"694\" height=\"229\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-subscribe-to-topics.png?resize=694%2C229&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Subscribing to topics HiveMQ\" class=\"wp-image-151494\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-subscribe-to-topics.png?w=694&amp;quality=100&amp;strip=all&amp;ssl=1 694w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-subscribe-to-topics.png?resize=300%2C99&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 694px) 100vw, 694px\" \/><\/figure><\/div>\n\n\n<p>After subscribing to those topics, scroll down to the bottom of the page. You should start receiving the Raspberry Pi Pico MQTT messages.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"685\" height=\"389\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-subscribed-to-topics-4.png?resize=685%2C389&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Messages received via MQTT HiveMQ\" class=\"wp-image-151495\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-subscribed-to-topics-4.png?w=685&amp;quality=100&amp;strip=all&amp;ssl=1 685w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-subscribed-to-topics-4.png?resize=300%2C170&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 685px) 100vw, 685px\" \/><\/figure><\/div>\n\n\n<p>And that\u2019s it. You successfully published MQTT messages with the Raspberry Pi Pico. Now, you can use any other MQTT Client to subscribe to those messages and receive the data. For example, having <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-node-red-raspberry-pi\/\" title=\"\">Node-RED nodes<\/a> or Adafruit IO widgets subscribed to MQTT topics and displaying the data on charts and gauges.<\/p>\n\n\n\n<p>You can also have any other microcontroller subscribed to those topics to receive the data\u2014it can be another Raspberry Pi Pico, an ESP32, an ESP8266, or another board.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"subscribe\">Subscribe to MQTT Topics<\/h2>\n\n\n\n<p>To show you how to subscribe to MQTT topics using the Raspberry Pi Pico we\u2019ll create a simple example, in which the Pico is subscribed to the <span class=\"rnthl rntliteral\">pico\/led<\/span> topic. Then, with the Web Client from HiveMQ, we\u2019ll publish ON and OFF messages on that topic. The Pico will receive the messages and will control an LED accordingly.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"309\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Rpi-Pico-Subscribe-MQTT-messages-example.png?resize=750%2C309&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico subscribing to MQTT messages\" class=\"wp-image-151496\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Rpi-Pico-Subscribe-MQTT-messages-example.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Rpi-Pico-Subscribe-MQTT-messages-example.png?resize=300%2C124&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Here\u2019s the workflow to subscribe to MQTT topics.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Connect the Raspberry Pi Pico to the internet;<\/li>\n\n\n\n<li>Connect to the MQTT broker;<\/li>\n\n\n\n<li>Subscribe to the MQTT topic;<\/li>\n\n\n\n<li>Create and assign a callback function that will run when a message is received;<\/li>\n\n\n\n<li>Create a loop that is constantly checking for new MQTT messages.<\/li>\n<\/ol>\n\n\n\n<p>The following code subscribes to the <span class=\"rnthl rntliteral\">pico\/led<\/span> topic and controls an LED according to the received message.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-w-mqtt-micropython\/\n\nfrom machine import Pin\nfrom time import sleep\nimport network\nfrom umqtt.simple import MQTTClient\nimport config\n\n# Define LED\nled = Pin('LED', Pin.OUT)\n\n# Constants for MQTT Topics\nMQTT_TOPIC_LED = 'pico\/led'\n\n# MQTT Parameters\nMQTT_SERVER = config.mqtt_server\nMQTT_PORT = 0\nMQTT_USER = config.mqtt_username\nMQTT_PASSWORD = config.mqtt_password\nMQTT_CLIENT_ID = b'raspberrypi_picow'\nMQTT_KEEPALIVE = 7200\nMQTT_SSL = True   # set to False if using local Mosquitto MQTT broker\nMQTT_SSL_PARAMS = {'server_hostname': MQTT_SERVER}\n\n# Init Wi-Fi Interface\ndef initialize_wifi(ssid, password):\n    wlan = network.WLAN(network.STA_IF)\n    wlan.active(True)\n\n    # Connect to the network\n    wlan.connect(ssid, password)\n\n    # Wait for Wi-Fi connection\n    connection_timeout = 10\n    while connection_timeout &gt; 0:\n        if wlan.status() &gt;= 3:\n            break\n        connection_timeout -= 1\n        print('Waiting for Wi-Fi connection...')\n        sleep(1)\n\n    # Check if connection is successful\n    if wlan.status() != 3:\n        return False\n    else:\n        print('Connection successful!')\n        network_info = wlan.ifconfig()\n        print('IP address:', network_info[0])\n        return True\n\n# Connect to MQTT Broker\ndef connect_mqtt():\n    try:\n        client = MQTTClient(client_id=MQTT_CLIENT_ID,\n                            server=MQTT_SERVER,\n                            port=MQTT_PORT,\n                            user=MQTT_USER,\n                            password=MQTT_PASSWORD,\n                            keepalive=MQTT_KEEPALIVE,\n                            ssl=MQTT_SSL,\n                            ssl_params=MQTT_SSL_PARAMS)\n        client.connect()\n        return client\n    except Exception as e:\n        print('Error connecting to MQTT:', e)\n\n# Subcribe to MQTT topics\ndef subscribe(client, topic):\n    client.subscribe(topic)\n    print('Subscribe to topic:', topic)\n    \n# Callback function that runs when you receive a message on subscribed topic\ndef my_callback(topic, message):\n    # Perform desired actions based on the subscribed topic and response\n    print('Received message on topic:', topic)\n    print('Response:', message)\n    # Check the content of the received message\n    if message == b'ON':\n        print('Turning LED ON')\n        led.value(1)  # Turn LED ON\n    elif message == b'OFF':\n        print('Turning LED OFF')\n        led.value(0)  # Turn LED OFF\n    else:\n        print('Unknown command')\n    \ntry:\n    # Initialize Wi-Fi\n    if not initialize_wifi(config.wifi_ssid, config.wifi_password):\n        print('Error connecting to the network... exiting program')\n    else:\n        # Connect to MQTT broker, start MQTT client\n        client = connect_mqtt()\n        client.set_callback(my_callback)\n        subscribe(client, MQTT_TOPIC_LED)\n        \n        # Continuously checking for messages\n        while True:\n            sleep(5)\n            client.check_msg()\n            print('Loop running')\nexcept Exception as e:\n    print('Error:', e)\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/mqtt\/mqtt_subscribe.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>Let\u2019s take a quick look at the relevant sections of code for this example.<\/p>\n\n\n\n<p><strong>If you\u2019re using a local Mosquitto MQTT broker, you should set the <span class=\"rnthl rntliteral\">MQTT_SSL<\/span> parameter to <span class=\"rnthl rntliteral\">False<\/span>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code><strong>MQTT_SSL = False<\/strong><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Subscribe to MQTT Topics<\/h3>\n\n\n\n<p>We create a function called <span class=\"rnthl rntliteral\">subscribe()<\/span> that accepts as arguments the MQTT client and the topic we want to subscribe to.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def subscribe(client, topic):\n    client.subscribe(topic)\n    print('Subscribe to topic:', topic)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Callback Function<\/h3>\n\n\n\n<p>We need to create a callback function that will run when a new message is received on a topic we are subscribed to. The topic and message arguments are automatically passed to the function when it is called.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def my_callback(topic, message):\n    # Perform desired actions based on the subscribed topic and response\n    print('Received message on topic:', topic)\n    print('Response:', message)\n    # Check the content of the received message\n    if message == b'ON':\n        print('Turning LED ON')\n        led.value(1)  # Turn LED ON\n    elif message == b'OFF':\n        print('Turning LED OFF')\n        led.value(0)  # Turn LED OFF\n    else:\n        print('Unknown command')<\/code><\/pre>\n\n\n\n<p>In this function, we check the content of the message. If it is <span class=\"rnthl rntliteral\">ON<\/span>, we\u2019ll turn the Raspberry Pi Pico built-in LED ON.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>if message == b'ON':\n    print('Turning LED ON')\n    led.value(1)  # Turn LED ON<\/code><\/pre>\n\n\n\n<p>If the message is <span class=\"rnthl rntliteral\">OFF<\/span>, it will turn the LED off.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>elif message == b'OFF':\n    print('Turning LED OFF')\n    led.value(0)  # Turn LED OFF<\/code><\/pre>\n\n\n\n<p>If we receive any other messages, we print <span class=\"rnthl rntliteral\">Unknown command<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>else:\n    print('Unknown command')<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Connecting to Wi-Fi, MQTT Broker and Checking Messages<\/h3>\n\n\n\n<p>To subscribe to the MQTT broker and constantly check for incoming messages, first we need to connect to the internet.<\/p>\n\n\n\n<p>The following lines try to connect to the internet:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>try:\n    # Initialize Wi-Fi\n    if not initialize_wifi(config.wifi_ssid, config.wifi_password):\n        print('Error connecting to the network... exiting program')<\/code><\/pre>\n\n\n\n<p>If we succeed, we also connect to the MQTT broker.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>client = connect_mqtt()<\/code><\/pre>\n\n\n\n<p>Then, assign the callback function by using the <span class=\"rnthl rntliteral\">set_callback()<\/span> and passing as argument the callback function we created previously <span class=\"rnthl rntliteral\">my_callback<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>client.set_callback(my_callback)<\/code><\/pre>\n\n\n\n<p>Finally, we can subscribe to MQTT topics. In this case, we\u2019re just subscribing to the <span class=\"rnthl rntliteral\">MQTT_TOPIC_LED<\/span>, but you can subscribe to multiple topics.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>subscribe(client, MQTT_TOPIC_LED)<\/code><\/pre>\n\n\n\n<p>Then, create a while loop to constantly check for incoming messages using the <span class=\"rnthl rntliteral\">check_msg()<\/span> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>while True:\n    sleep(5)\n    client.check_msg()\n    print('Loop running')<\/code><\/pre>\n\n\n\n<p>You can also add other tasks to the loop. We check for new messages every five seconds, but you can use a smaller or longer delay time depending on how often you\u2019re expecting to receive messages.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Testing the Code<\/h2>\n\n\n\n<p>Run the previous code on your Raspberry Pi Pico. It will connect to the internet and subscribe to the MQTT topic.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"675\" height=\"339\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/subscribe-MQTT-Topic-RPi-Pico-Thonny-IDE.png?resize=675%2C339&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"RPi Pico subscribe to MQTT topics Thonny IDE\" class=\"wp-image-151497\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/subscribe-MQTT-Topic-RPi-Pico-Thonny-IDE.png?w=675&amp;quality=100&amp;strip=all&amp;ssl=1 675w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/subscribe-MQTT-Topic-RPi-Pico-Thonny-IDE.png?resize=300%2C151&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 675px) 100vw, 675px\" \/><\/figure><\/div>\n\n\n<p>Now, let\u2019s publish some messages on the <span class=\"rnthl rntliteral\">pico\/led<\/span> topic to control the LED using HiveMQ Web Client.<\/p>\n\n\n\n<p>Go to your HiveMQ cluster Web Client. Insert your MQTT broker username and password and click <strong>Connect Client<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"273\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-hivemq-http-subscribe-1.png?resize=750%2C273&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ Web Client\" class=\"wp-image-151491\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-hivemq-http-subscribe-1.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-interface-hivemq-http-subscribe-1.png?resize=300%2C109&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Scroll down the page to the <em>Publish Message<\/em> section.<\/p>\n\n\n\n<p>Insert <span class=\"rnthl rntliteral\">pico\/led<\/span> on the <strong>Topic Name<\/strong> field, and type <strong>ON <\/strong>in the <strong>Message<\/strong> field.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"654\" height=\"508\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-web-client-publish.png?resize=654%2C508&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ publish MQTT message Web Client\" class=\"wp-image-151498\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-web-client-publish.png?w=654&amp;quality=100&amp;strip=all&amp;ssl=1 654w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/hivemq-web-client-publish.png?resize=300%2C233&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 654px) 100vw, 654px\" \/><\/figure><\/div>\n\n\n<p>Finally, press the <strong>Publish<\/strong> button.<\/p>\n\n\n\n<p>Your Raspberry Pi Pico will receive the message, and will turn the on-board LED on.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"755\" height=\"351\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/subscribe-receive-ON-message.png?resize=755%2C351&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"RPi Pico receive Messages via MQTT Thonny IDE\" class=\"wp-image-151499\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/subscribe-receive-ON-message.png?w=755&amp;quality=100&amp;strip=all&amp;ssl=1 755w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/subscribe-receive-ON-message.png?resize=300%2C139&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 755px) 100vw, 755px\" \/><\/figure><\/div>\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Blinking-LED-On.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico W onboard LED on\" class=\"wp-image-130907\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Blinking-LED-On.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Blinking-LED-On.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Go back to HiveMQ Client and send an OFF message.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"665\" height=\"386\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-publish-off.png?resize=665%2C386&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HiveMQ publish MQTT message Web Client\" class=\"wp-image-151500\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-publish-off.png?w=665&amp;quality=100&amp;strip=all&amp;ssl=1 665w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/web-client-publish-off.png?resize=300%2C174&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 665px) 100vw, 665px\" \/><\/figure><\/div>\n\n\n<p>The Raspberry Pi Pico will receive the message and turn off the LED.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Blinking-LED-Off.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico W onboard LED off\" class=\"wp-image-130908\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Blinking-LED-Off.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Blinking-LED-Off.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>And that\u2019s it. You successfully subscribed to an MQTT topic and executed a different task according to the received message. Now, instead of HiveMQ Web Client, you can use any Home Automation or IoT platform with MQTT support that allows you to build a web interface with buttons or switches to send MQTT messages.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this guide, you&#8217;ve learned all the essential concepts to start using MQTT with the Raspberry Pi Pico. We&#8217;ve set up an MQTT broker and published and subscribed to MQTT topics with the Pico.<\/p>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful. <\/p>\n\n\n\n<p>Learn more about the Raspberry Pi Pico with our eBook:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\" title=\"\"><strong>Learn Raspberry Pi Pico\/Pico W with MicroPython<\/strong><\/a><\/li>\n<\/ul>\n\n\n\n<p>We have other guides that you may also like:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\">Raspberry Pi Pico: Web Server (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-ssd1306-oled-micropython\/\">Raspberry Pi Pico: SSD1306 OLED Display (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\">Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi-pico\/\" title=\"\">More Raspberry Pi Pico Tutorials and Guides<\/a><\/li>\n<\/ul>\n\n\n\n<p>If you want to use MQTT with the ESP32 or ESP8266 you can follow the next tutorials:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-mqtt-esp32-esp8266\/\">MicroPython \u2013 Getting Started with MQTT on ESP32\/ESP8266<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-mqtt-publish-bme280-esp32-esp8266\/\">MicroPython: MQTT \u2013 Publish BME280 Sensor Readings (ESP32\/ESP8266)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-mqtt-publish-subscribe-arduino-ide\/\">ESP32 MQTT \u2013 Publish and Subscribe with Arduino IDE<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-mqtt-publish-bme280-arduino\/\">ESP32 MQTT \u2013 Publish BME280 Sensor Readings (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-mqtt-publish-bme280-arduino\/\">ESP8266 NodeMCU MQTT \u2013 Publish BME280 Sensor Readings (Arduino IDE)<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is a complete guide to using MQTT with Raspberry Pi Pico programmed with MicroPython. MQTT is a communication protocol widely used in Home Automation and IoT applications to connect &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico W: Getting Started with MQTT (MicroPython)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-mqtt-micropython\/#more-151437\" aria-label=\"Read more about Raspberry Pi Pico W: Getting Started with MQTT (MicroPython)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":151503,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[324,326],"tags":[],"class_list":["post-151437","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-raspberry-pi-pico","category-raspberry-pi-pico-micropython"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-MQTT-Guide-MicroPython.jpg?fit=1920%2C1080&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/151437","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=151437"}],"version-history":[{"count":16,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/151437\/revisions"}],"predecessor-version":[{"id":154855,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/151437\/revisions\/154855"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/151503"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=151437"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=151437"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=151437"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}