DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. IoT
  4. Sending Sensor Data From Raspberry Pi Pico W to HiveMQ Cloud

Sending Sensor Data From Raspberry Pi Pico W to HiveMQ Cloud

The Pico W is a very inexpensive microcontroller that can be used for any project where you want to exchange data with an (online) MQTT broker.

Frank Delporte user avatar by
Frank Delporte
·
Dec. 09, 22 · Review
Like (2)
Save
Tweet
Share
4.00K Views

Join the DZone community and get the full member experience.

Join For Free

In a previous post, "MQTT Messaging With Java and Raspberry Pi," I described how data could be sent from a Raspberry Pi Linux board and Raspberry Pi Pico microcontroller to HiveMQ Cloud.

Raspberry Pi Pico W

On June 30, 2022, Raspberry Pi released a new product: the Pico W, a new version of the original Pico, but with Wi-Fi onboard. The new board is for sale for $6, compared to the $4 of the original Pico. The new Pico W has the same form factor as the original Pico. There is a minor change in the wiring as the connection of the onboard LED has changed. You should be able to swap to the new version in most existing projects without any problems. With this new Pico W, we can simplify the setup of the previous article, as the separate Wi-Fi module is no longer needed.

Pico

About HiveMQ Cloud

HiveMQ Cloud is an online MQTT-compatible service that is totally free for up to 100 devices! Even for the most enthusiastic maker, that’s a lot of microcontrollers or computers!

On the HiveMQ Blog, an article by Kudzai Manditereza was published that also describes how to use the Pico W.

MicroPython

In the previous project with Pico, CircuitPython was used to code the program. Unfortunately, when I started this project to connect Pico W to HiveMQ Cloud, CircuitPython was not yet available with support for the WiFi module of the Pico W. That ticket on GitHub now seems to be closed and resolved, so I leave it up to you to try out. In this post, we will be using MicroPython.

“MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimized to run on microcontrollers and in constrained environments.”.

To install MicroPython on the Pico W, follow this step-by-step provided by Raspberry Pi.

Source Code

The full info to set up the project, all required libraries, and the full code can be found in this post. The full source code is also available on GitHub. 

Let's take a look at the most important parts of the code.

Connecting to Wi-Fi

By using a secrets.py-file we can separate the credentials into a separate file and load it into our main code with

Python
 
from secrets import secrets


From then on, we can use all its values where needed, e.g. for the W-Fi credentials:

Python
 
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(secrets["ssid"], secrets["password"])


For a secure connection to the MQTT broker, our device must have a valid timestamp. This can be easily achieved with ntptime:

Python
 
ntptime.host = "de.pool.ntp.org"
ntptime.settime()


Connecting to the MQTT broker and sending a message can be quickly done using the library /lib/umqtt/simple.py provided on GitHub in the MicroPython project, and the following code:

Python
 
sslparams = {'server_hostname': secrets["broker"]}
mqtt_client = MQTTClient(client_id="picow",
                    server=secrets["broker"],
                    port=secrets["port"],
                    user=secrets["mqtt_username"],
                    password=secrets["mqtt_key"],
                    keepalive=3600,
                    ssl=True,
                    ssl_params=sslparams) 
mqtt_client.connect()
print('Connected to MQTT Broker: ' + secrets["broker"])

# Send a test message to HiveMQ
mqtt_client.publish('test', 'HelloWorld')


As you can read in the full blog post and on the HiveMQ forum, connecting this way to HiveMQ Cloud is not fully secured and requires additional steps to get a copy of the certificate to be validated on the Pico W. But for most projects, the above approach will be sufficient.

Another library /lib/hcsr04/hcsr04.py that is available on GitHub in a project by rsc1975 (Roberto), helps us to get the value from a distance sensor to send to the MQTT broker like this:

Python
 
distance = hcsr04.distance_cm()
json = "{\"value\": " + str(distance) + "}"
mqtt_client.publish("picow/distance", json)


Conclusion

Although it took me some time to find a good library and the correct connection parameters to connect to HiveMQ Cloud, it turned out to be a fun project with a lot of possibilities to be further extended!

MQTT Cloud Pico (text editor) raspberry pi

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Agile Scrum and the New Way of Work in 2023
  • Problems of Cloud Cost Management: A Socio-Technical Analysis
  • Learning by Doing: An HTTP API With Rust
  • How To Avoid “Schema Drift”

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: