Internet Connect!
Once you have CircuitPython setup and libraries installed, you can get your project connected to the Internet over WiFi.
To do this, you'll be editing CircuitPython code and will need an editor. We suggest using Mu, a lightweight text editor with support for CircuitPython built-in.
Click the button below to get instructions on how to install the Mu Editor.
If you have not yet connected your CircuitPython WiFi board to the Internet, follow one of the guides below and come back when you've successfully connected to the internet:
- If you have an ESP32-S2 board (such as the MagTag), follow this page to connect to the internet.
- If you have an AirLift All-in-One board (such as the PyPortal), follow this page to connect to the internet.
- If you have an externally connected AirLift (such as the AirLift FeatherWing or AirLift breakout), follow this page to connect to the internet.
settings.toml File Setup for Adafruit IO
While you created a settings.toml file and connected to the internet in the previous step, as described in the Create Your settings.toml File page earlier in the guide. You'll need to edit the settings.toml file to include your Adafruit IO Username and Active Key.
Add the following lines to your settings.toml file, replacing _your_adafruit_io_username
with your Adafruit IO username.
Then, replace _your_big_huge_super_long_aio_key_
with your Adafruit IO Active Key.
CIRCUITPY_WIFI_SSID = "your-ssid-here" CIRCUITPY_WIFI_PASSWORD = "your-ssid-password-here" aio_username = "_your_adafruit_io_username_" aio_key = "_your_big_huge_super_long_aio_key_"
Make sure you save this file before proceeding as settings.toml in the root directory of your board CIRCUITPY drive.
ESP32-S2 Code
CircuitPython boards using the ESP32-S2 such as the MagTag or Metro ESP32-S2 have internet connectivity built into the CircuitPython firmware.
Copy the following code to your code.py file on your microcontroller:
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import os import ssl import time import socketpool import wifi import adafruit_minimqtt.adafruit_minimqtt as MQTT # Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys # with your WiFi credentials. DO NOT share that file or commit it into Git or other # source control. # Set your Adafruit IO Username, Key and Port in settings.toml # (visit io.adafruit.com if you need to create an account, # or if you need your Adafruit IO key.) aio_username = os.getenv("aio_username") aio_key = os.getenv("aio_key") print(f"Connecting to {os.getenv('CIRCUITPY_WIFI_SSID')}") wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) print(f"Connected to {os.getenv('CIRCUITPY_WIFI_SSID')}!") ### Feeds ### # Setup a feed named 'photocell' for publishing to a feed photocell_feed = aio_username + "/feeds/photocell" # Setup a feed named 'onoff' for subscribing to changes onoff_feed = aio_username + "/feeds/onoff" ### Code ### # Define callback methods which are called when events occur def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. print(f"Connected to Adafruit IO! Listening for topic changes on {onoff_feed}") # Subscribe to all changes on the onoff_feed. client.subscribe(onoff_feed) def disconnected(client, userdata, rc): # This method is called when the client is disconnected print("Disconnected from Adafruit IO!") def message(client, topic, message): # This method is called when a topic the client is subscribed to # has a new message. print(f"New message on topic {topic}: {message}") # Create a socket pool pool = socketpool.SocketPool(wifi.radio) ssl_context = ssl.create_default_context() # If you need to use certificate/key pair authentication (e.g. X.509), you can load them in the # ssl context by uncommenting the lines below and adding the following keys to your settings.toml: # "device_cert_path" - Path to the Device Certificate # "device_key_path" - Path to the RSA Private Key # ssl_context.load_cert_chain( # certfile=os.getenv("device_cert_path"), keyfile=os.getenv("device_key_path") # ) # Set up a MiniMQTT Client mqtt_client = MQTT.MQTT( broker="io.adafruit.com", port=1883, username=aio_username, password=aio_key, socket_pool=pool, ssl_context=ssl_context, ) # Setup the callback methods above mqtt_client.on_connect = connected mqtt_client.on_disconnect = disconnected mqtt_client.on_message = message # Connect the client to the MQTT broker. print("Connecting to Adafruit IO...") mqtt_client.connect() photocell_val = 0 while True: # Poll the message queue mqtt_client.loop(timeout=1) # Send a new message print(f"Sending photocell value: {photocell_val}...") mqtt_client.publish(photocell_feed, photocell_val) print("Sent!") photocell_val += 1 time.sleep(5)
ESP32 AirLift Code
CircuitPython boards using an ESP32 "AirLift" Co-Processor such as the PyPortal require a helper library to connect to the internet.
Copy the following code to your code.py file on your microcontroller:
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import os import time import adafruit_connection_manager import board import busio import neopixel from adafruit_esp32spi import adafruit_esp32spi from digitalio import DigitalInOut import adafruit_minimqtt.adafruit_minimqtt as MQTT # Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys # with your WiFi credentials. Add your Adafruit IO username and key as well. # DO NOT share that file or commit it into Git or other source control. aio_username = os.getenv("aio_username") aio_key = os.getenv("aio_key") # If you are using a board with pre-defined ESP32 Pins: esp32_cs = DigitalInOut(board.ESP_CS) esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_reset = DigitalInOut(board.ESP_RESET) # If you have an externally connected ESP32: # esp32_cs = DigitalInOut(board.D9) # esp32_ready = DigitalInOut(board.D10) # esp32_reset = DigitalInOut(board.D5) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED # import adafruit_rgbled # from adafruit_esp32spi import PWMOut # RED_LED = PWMOut.PWMOut(esp, 26) # GREEN_LED = PWMOut.PWMOut(esp, 27) # BLUE_LED = PWMOut.PWMOut(esp, 25) # status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) ### Feeds ### # Setup a feed named 'photocell' for publishing to a feed photocell_feed = aio_username + "/feeds/photocell" # Setup a feed named 'onoff' for subscribing to changes onoff_feed = aio_username + "/feeds/onoff" ### Code ### # Define callback methods which are called when events occur def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) # Subscribe to all changes on the onoff_feed. client.subscribe(onoff_feed) def disconnected(client, userdata, rc): # This method is called when the client is disconnected print("Disconnected from Adafruit IO!") def message(client, topic, message): # This method is called when a topic the client is subscribed to # has a new message. print(f"New message on topic {topic}: {message}") # Connect to WiFi print("Connecting to WiFi...") esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) print("Connected!") pool = adafruit_connection_manager.get_radio_socketpool(esp) ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) # Set up a MiniMQTT Client mqtt_client = MQTT.MQTT( broker="io.adafruit.com", username=aio_username, password=aio_key, socket_pool=pool, ssl_context=ssl_context, ) # Setup the callback methods above mqtt_client.on_connect = connected mqtt_client.on_disconnect = disconnected mqtt_client.on_message = message # Connect the client to the MQTT broker. print("Connecting to Adafruit IO...") mqtt_client.connect() photocell_val = 0 while True: # Poll the message queue mqtt_client.loop() # Send a new message print("Sending photocell value: %d..." % photocell_val) mqtt_client.publish(photocell_feed, photocell_val) print("Sent!") photocell_val += 1 time.sleep(5)
(Optional) Change ESP32 AirLift Pinouts
If you are using a board with a built-in ESP32 (like the PyPortal), you do not need to make changes to the code. It's already setup for usage with those boards. However, if you are using an externally connected ESP32 (like the AirLift Breakout), you'll need to define the ESP32's pinouts.
Make sure to change the ESP32 pin definitions in the code to match your wiring. You can do this by uncommenting and editing the following lines in your code to match your wiring.
esp32_cs = DigitalInOut(board.D9) esp32_ready = DigitalInOut(board.D10) esp32_reset = DigitalInOut(board.D5)
Directly after saving the code.py file, open a serial monitor/REPL to see the output. It should look something like the following:
code.py output: Connecting to Adafruit IO... Connected to Adafruit IO! Listening for topic changes on brubell/feeds/onoff Sending photocell value: 0... Sent! Sending photocell value: 1... Sent! Sending photocell value: 2... Sent! Sending photocell value: 3... Sent!
Navigate to the dashboard you created earlier. You should see the photocell gauge increasing its value as your CircuitPython device publishes the increasing photocell value to Adafruit IO.
If you navigate to the page for the photocell feed, you'll see the values increasing there along with metadata about when the data was received by the Adafruit IO broker.
While we're publishing the increasing photocell value to Adafruit IO - our code also subscribes to changes on the onoff feed.
The example code.py subscribes to the onoff feed when the client successfully connects to Adafruit IO. You don't need to make any changes to your code!
With the code still running on your CircuitPython device - click the toggle switch to send a value to the onoff feed. You should see the value appear on your serial monitor/REPL.
If you really want to see the speed of MQTT - remove the one second delay in the while True
loop.
Change the following code (within while True
) from:
print('Sent!')
photocell_val += 1
time.sleep(1)
to
print('Sent!')
photocell_val += 1
time.sleep(0.5)
Be warned - if you do this you will not be able to run the code for very long. This is because Adafruit IO's MQTT server imposes a rate limit to prevent excessive load on the service.
The current Adafruit IO Data Rate is at most 1 request per second (or 60 requests within 60 seconds), without an Adafruit IO+ Boost applied to your account.
Going Further - the Adafruit IO CircuitPython Module
While you can use this code to communicate with Adafruit IO, the recommend method of using CircuitPython with Adafruit IO is with the Adafruit IO CircuitPython module.
This module has methods to simplify using the Adafruit IO MQTT API. It also includes helper features to make your experience using Adafruit IO better.
If you want to use Adafruit IO and CircuitPython, check out Adafruit IO CircuitPython and its code examples on GitHub!
Text editor powered by tinymce.