Kevin Richmond
Published © GPL3+

Connect to Adafruit IO using Arduino Portenta

Publish different types of data into Adafruit IO (MQTT) through an Arduino Portenta

BeginnerProtip1 hour1,102
Connect to Adafruit IO using Arduino Portenta

Things used in this project

Hardware components

Arduino Portenta H7
Arduino Portenta H7
×1
Arduino Portenta Vision Shield - Ethernet
Arduino Portenta Vision Shield - Ethernet
×1

Software apps and online services

OpenMV
Adafruit IO

Story

Read more

Code

main.py

Python
Connect to Adafruit IO (MQTT broker) and send text, numbers and images.
import time, network, pyb
from mqtt import MQTTClient
import sensor, image, ubinascii

start_led = pyb.LED(2) # green led 2 seconds blink will indicate that Wi Fi connection was successful
working_led = pyb.LED(3) # blue led fast blink will indicate that the data has been sent to MQTT server

sensor.reset() # Reset and initialize the sensor.
sensor.set_pixformat(sensor.GRAYSCALE)  # Arduino Vision Shield in monochromatic
sensor.set_framesize(sensor.QQVGA)  # Set frame size to QQVGA for reducing size of the image to be sent
sensor.skip_frames(time=2000)  # Wait for settings take effect.

SSID = 'your-wifi-network-name'
KEY = 'your-wifi-network-password'

print("Trying to connect. Note this may take a while...") # Init wlan module and connect to network

wlan = network.WLAN(network.STA_IF)
wlan.deinit()
wlan.active(True)
wlan.connect(SSID, KEY, timeout=30000)

print("WiFi Connected ", wlan.ifconfig()) # We should have a valid IP now via DHCP
start_led.on()
time.sleep(2) # Green LED will turn ON for 2 seconds indicating that the connection was successful
start_led.off()

client = MQTTClient("openmv", "io.adafruit.com", user="adafruit-io-user", password="adafruit-io-key", port=1883)
client.connect()

i = 0

while (True):
    i_t = str(i) # data to be published requires to be in a string format
    text = "Running for " + i_t + " sec" # i.e. "Running for 450 sec"
    
    if i%2 == 0:
        ledstatus = "0"
    
    else:
        ledstatus = "1"

    img = sensor.snapshot()
    img = img.compress(quality=90) # to reduce image size to keep it below 1KB
    img_bytes = ubinascii.b2a_base64(img) # converts the image to bytes
    img_t = img_bytes.decode("utf-8")  # converts bytes to string
    img_t = img_t.strip()  # removes the " " at the beginning of the string

    working_led.on()
    client.publish("adafruit-io-user/feeds/temperature", i_t)
    client.publish("adafruit-io-user/feeds/text", text)
    client.publish("adafruit-io-user/feeds/image", img_t)
    client.publish("adafruit-io-user/feeds/ledstatus", ledstatus)
    working_led.off()

    time.sleep(10)
    i += 1

Credits

Kevin Richmond

Kevin Richmond

7 projects • 2 followers
Engineer passionate about automation, IoT, Machine Learning and sustainability.
Thanks to Alex Bucknall.

Comments