This project uses the Adafruit FunHouse with the new Adafruit CircuitPython Dash Display library to create a customizable Adafruit IO dashboard on your FunHouse. This guide, as well as the Dash Display library, is currently only for the FunHouse, but expect support to be added for other boards like the PyPortal and Feather boards with a screen and WiFi connectivity.

There are a few examples of peripheral devices that will work directly with this, but in theory, just about any device should work as long as it publishes to or is controllable via an Adafruit IO feed. The devices I've written examples for are:

I'll go over 3 of the examples in this guide, but if you want to see the rest, you can find them all here.

I've also tried to use STEMMA QT whenever possible so the peripheral devices for this project should be very easy to assemble and should look pretty clean and organized.

This project mostly uses MQTT with the exception of the PyPortals which are currently having some issues with MQTT.

Parts

Home is where the heart is...it's also where we keep all our electronic bits. So why not wire it up with sensors and actuators to turn our house into an electronic wonderland....
$34.95
In Stock
Got a glorious RGB Matrix project you want to mount and display in your workspace or home? If you have one of the matrix panels listed below, you'll need a pack of these...
$2.50
In Stock
As technology changes and adapts, so does Adafruit. This  USB Type A to Type C cable will help you with the transition to USB C, even if you're still...
$4.95
In Stock
Need a USB jack for charging or powering a project, but don't want to lug around a computer? This switching supply gives a clean regulated output at up to 1000mA! 110 or 240 input,...
$5.95
In Stock

CircuitPython is a derivative of MicroPython designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the CIRCUITPY drive to iterate.

Set Up CircuitPython

Follow the steps to get CircuitPython installed on your FunHouse.

Click the link above and download the latest .BIN and .UF2 file

(depending on how you program the ESP32S2 board you may need one or the other, might as well get both)

Download and save it to your desktop (or wherever is handy).

Plug your FunHouse into your computer using a known-good USB cable.

A lot of people end up using charge-only USB cables and it is very frustrating! So make sure you have a USB cable you know is good for data sync.

Option 1 - Load with UF2 Bootloader

This is by far the easiest way to load CircuitPython. However it requires your board has the UF2 bootloader installed. Some early boards do not (we hadn't written UF2 yet!) - in which case you can load using the built in ROM bootloader.

Still, try this first!

Try Launching UF2 Bootloader

Loading CircuitPython by drag-n-drop UF2 bootloader is the easier way and we recommend it.

Launch UF2 by double-clicking the Reset button (the one next to the USB C port). You may have to try a few times to get the timing right.

About a half second pause between clicks while the DotStars are purple seems to work well.

If the UF2 bootloader is installed, you will see a new disk drive appear called HOUSEBOOT

Copy the UF2 file you downloaded at the first step of this tutorial onto the HOUSEBOOT drive

If you're using Windows and you get an error at the end of the file copy that says Error from the file copy, Error 0x800701B1: A device which does not exist was specified. You can ignore this error, the bootloader sometimes disconnects without telling Windows, the install completed just fine and you can continue. If its really annoying, you can also upgrade the bootloader (the latest version of the UF2 bootloader fixes this warning)

Your board should auto-reset into CircuitPython, or you may need to press reset. A CIRCUITPY drive will appear. You're done! Go to the next pages.

Option 2 - Use Chrome Browser To Upload BIN file

You will need to do a full erase prior to uploading new firmware.

The next best option is to try using the Chrome-browser version of esptool we have written. This is handy if you don't have Python on your computer, or something is really weird with your setup that makes esptool not run (which happens sometimes and isn't worth debugging!) You can follow along on the Install UF2 Bootloader page and either load the UF2 bootloader and then come back to Option 1 on this page, or you can download the CircuitPython BIN file directly using the tool in the same manner as the bootloader.

Option 3 - Use esptool to load BIN file

For more advanced users, you can upload with esptool to the ROM (hardware) bootloader instead!

Follow the initial steps found in the Run esptool and check connection section of the Install UF2 Bootloader page to verify your environment is set up, your board is successfully connected, and which port it's using.

In the final command to write a binary file to the board, replace the port with your port, and replace "firmware.bin" with the the file you downloaded above.

The output should look something like the output in the image.

Press reset to exit the bootloader.

Your CIRCUITPY drive should appear!

You're all set! Go to the next pages.

To use the internet-connectivity built into your ESP32-S2 with CircuitPython, you must first install a number of libraries. This page covers that process.

Adafruit CircuitPython Library Bundle

Download the Adafruit CircuitPython Bundle. You can find the latest release here:

Download the adafruit-circuitpython-bundle-version-mpy-*.zip bundle zip file, and unzip a folder of the same name. Inside you'll find a lib folder. The entire collection of libraries is too large to fit on the CIRCUITPY drive. Instead, add each library as you need it, this will reduce the space usage but you'll need to put in a little more effort.

At a minimum we recommend the following libraries, in fact we more than recommend. They're basically required. So grab them and install them into CIRCUITPY/lib now!

  • adafruit_requests.mpy - A requests-like library for HTTP commands.
  • adafruit_dotstar.mpy - Helper library to use DotStar LEDs, often built into the boards so they're great for quick feedback

Once you have added those files, please continue to the next page to set up and test Internet connectivity

Once you have CircuitPython installed and the minimum libraries installed we can get your board connected to the Internet. 

To get connected, you will need to start by creating a secrets.py file.

Secrets File

We expect people to share tons of projects as they build CircuitPython WiFi widgets. What we want to avoid is people accidentally sharing their passwords or secret tokens and API keys. So, we designed all our examples to use a secrets.py file, that is in your CIRCUITPY drive, to hold secret/private/custom data. That way you can share your main project without worrying about accidentally sharing private stuff.

Your secrets.py file should look like this:

# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : 'home_wifi_network',
    'password' : 'wifi_password',
    'aio_username' : 'my_adafruit_io_username',
    'aio_key' : 'my_adafruit_io_key',
    'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
    }

Copy and paste that text/code into a file called secrets.py and save it to your CIRCUITPY folder like so:

Inside is a python dictionary named secrets with a line for each entry. Each entry has an entry name (say 'ssid') and then a colon to separate it from the entry key 'home ssid' and finally a comma ,

At a minimum you'll need to adjust the ssid and password for your local WiFi setup so do that now!

As you make projects you may need more tokens and keys, just add them one line at a time. See for example other tokens such as one for accessing github or the hackaday API. Other non-secret data like your timezone can also go here, just cause its called secrets doesn't mean you can't have general customization data in there!

For the correct time zone string, look at http://worldtimeapi.org/timezones and remember that if your city is not listed, look for a city in the same time zone, for example Boston, New York, Philadelphia, Washington DC, and Miami are all on the same time as New York.

Of course, don't share your secrets.py - keep that out of GitHub, Discord or other project-sharing sites.

Don't share your secrets.py file, it has your passwords and API keys in it!

Connect to WiFi

OK now you have your secrets setup - you can connect to the Internet using the Requests module.

First make sure you are running the latest version of Adafruit CircuitPython for your board.

Next you'll need to install the necessary libraries to use the hardware--carefully follow the steps to find and install these libraries from Adafruit's CircuitPython library bundle. Our introduction guide has a great page on how to install the library bundle.

  • adafruit_requests
  • neopixel

Before continuing make sure your board's CIRCUITPY/lib folder or root filesystem has the above files copied over.

Once that's done, load up the following example using Mu or your favorite editor:

import ipaddress
import ssl
import wifi
import socketpool
import adafruit_requests

# URLs to fetch from
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_QUOTES_URL = "https://www.adafruit.com/api/quotes.php"
JSON_STARS_URL = "https://api.github.com/repos/adafruit/circuitpython"

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

print("ESP32-S2 WebClient Test")

print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

print("Available WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
            network.rssi, network.channel))
wifi.radio.stop_scanning_networks()

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!"%secrets["ssid"])
print("My IP address is", wifi.radio.ipv4_address)

ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % (wifi.radio.ping(ipv4)*1000))

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

print("Fetching text from", TEXT_URL)
response = requests.get(TEXT_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

print("Fetching json from", JSON_QUOTES_URL)
response = requests.get(JSON_QUOTES_URL)
print("-" * 40)
print(response.json())
print("-" * 40)

print()

print("Fetching and parsing json from", JSON_STARS_URL)
response = requests.get(JSON_STARS_URL)
print("-" * 40)
print("CircuitPython GitHub Stars", response.json()["stargazers_count"])
print("-" * 40)

print("done")

And save it to your board. Make sure the file is named code.py.

Open up your REPL, you should see something like the following:

In order, the example code...

Checks the ESP32-S2's MAC address.

print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

Performs a scan of all access points and prints out the access point's name (SSID), signal strength (RSSI), and channel.

print("Avaliable WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
            network.rssi, network.channel))
wifi.radio.stop_scanning_networks()

Connects to the access point you defined in the secrets.py file, prints out its local IP address, and attempts to ping google.com to check its network connectivity. 

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print(print("Connected to %s!"%secrets["ssid"]))
print("My IP address is", wifi.radio.ipv4_address)

ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % wifi.radio.ping(ipv4))

The code creates a socketpool using the wifi radio's available sockets. This is performed so we don't need to re-use sockets. Then, it initializes a a new instance of the requests interface - which makes getting data from the internet really really easy.

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

To read in plain-text from a web URL, call requests.get - you may pass in either a http, or a https url for SSL connectivity. 

print("Fetching text from", TEXT_URL)
response = requests.get(TEXT_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

Requests can also display a JSON-formatted response from a web URL using a call to requests.get

print("Fetching json from", JSON_QUOTES_URL)
response = requests.get(JSON_QUOTES_URL)
print("-" * 40)
print(response.json())
print("-" * 40)

Finally, you can fetch and parse a JSON URL using requests.get. This code snippet obtains the stargazers_count field from a call to the GitHub API.

print("Fetching and parsing json from", JSON_STARS_URL)
response = requests.get(JSON_STARS_URL)
print("-" * 40)
print("CircuitPython GitHub Stars", response.json()["stargazers_count"])
print("-" * 40)

OK you now have your ESP32-S2 board set up with a proper secrets.py file and can connect over the Internet. If not, check that your secrets.py file has the right ssid and password and retrace your steps until you get the Internet connectivity working!

A very common need for projects is to know the current date and time. Especially when you want to deep sleep until an event, or you want to change your display based on what day, time, date, etc. it is

Determining the correct local time is really really hard. There are various time zones, Daylight Savings dates, leap seconds, etc. Trying to get NTP time and then back-calculating what the local time is, is extraordinarily hard on a microcontroller just isn't worth the effort and it will get out of sync as laws change anyways.

For that reason, we have the free adafruit.io time service. Free for anyone, with a free adafruit.io account. You do need an account because we have to keep accidentally mis-programmed-board from overwhelming adafruit.io and lock them out temporarily. Again, it's free!

There are other services like WorldTimeAPI, but we don't use those for our guides because they are nice people and we don't want to accidentally overload their site. Also, there's a chance it may eventually go down or also require an account.

Step 1) Make an Adafruit account

It's free! Visit https://accounts.adafruit.com/ to register and make an account if you do not already have one

Step 2) Sign into Adafruit IO

Head over to io.adafruit.com and click Sign In to log into IO using your Adafruit account. It's free and fast to join.

Step 3) Get your Adafruit IO Key

Click on My Key in the top bar

You will get a popup with your Username and Key (In this screenshot, we've covered it with red blocks)

Go to your secrets.py file on your CIRCUITPY drive and add three lines for aio_username, aio_key and timezone so you get something like the following:

# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : 'home_wifi_network',
    'password' : 'wifi_password',
    'aio_username' : 'my_adafruit_io_username',
    'aio_key' : 'my_adafruit_io_key',
    'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
    }

The timezone is optional, if you don't have that entry, adafruit.io will guess your timezone based on geographic IP address lookup. You can visit http://worldtimeapi.org/timezones to see all the time zones available (even though we do not use worldtimeapi for time-keeping we do use the same time zone table)

Step 4) Upload Test Python Code

This code is like the Internet Test code from before, but this time it will connect to adafruit.io and get the local time

import ipaddress
import ssl
import wifi
import socketpool
import adafruit_requests
import secrets


TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_QUOTES_URL = "https://www.adafruit.com/api/quotes.php"
JSON_STARS_URL = "https://api.github.com/repos/adafruit/circuitpython"

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# Get our username, key and desired timezone
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]
location = secrets.get("timezone", None)
TIME_URL = "https://io.adafruit.com/api/v2/%s/integrations/time/strftime?x-aio-key=%s" % (aio_username, aio_key)
TIME_URL += "&fmt=%25Y-%25m-%25d+%25H%3A%25M%3A%25S.%25L+%25j+%25u+%25z+%25Z"

print("ESP32-S2 Adafruit IO Time test")

print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

print("Available WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
            network.rssi, network.channel))
wifi.radio.stop_scanning_networks()

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!"%secrets["ssid"])
print("My IP address is", wifi.radio.ipv4_address)

ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % wifi.radio.ping(ipv4))

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

print("Fetching text from", TIME_URL)
response = requests.get(TIME_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

After running this, you will see something like the below text. We have blocked out the part with the secret username and key data!

Note at the end you will get the date, time, and your timezone! If so, you have correctly configured your secrets.py and can continue to the next steps!

To use all the amazing features of your FunHouse with CircuitPython, you must first install a number of libraries. This page covers that process.

Get Latest Adafruit CircuitPython Bundle

Download the Adafruit CircuitPython Library Bundle. You can find the latest release here:

Download the adafruit-circuitpython-bundle-version-mpy-*.zip bundle zip file, and unzip a folder of the same name. Inside you'll find a lib folder. The entire collection of libraries is too large to fit on the CIRCUITPY drive. Therefore, you'll need to copy the necessary libraries to your board individually.

At a minimum, the following libraries are required. Copy the following folders or .mpy files to the lib folder on your CIRCUITPY drive. If the library is a folder, copy the entire folder to the lib folder on your board.

At a minimum we recommend the following libraries, in fact we more than recommend. They're basically required. So grab them and install them into CIRCUITPY/lib now!

Library folders (copy the whole folder over to lib):

  • adafruit_funhouse - This is a helper library designed for using all of the features of the FunHouse, including networking, buttons, DotStars, etc.
  • adafruit_portalbase - This library is the base library that adafruit_funhouse is built on top of.
  • adafruit_bitmap_font - There is fancy font support, and it's easy to make new fonts. This library reads and parses font files.
  • adafruit_display_text - This library displays text on the screen.
  • adafruit_io - This library helps connect the FunHouse to our free data logging and viewing service
  • adafruit_minimqtt - MQTT library required for communicating with the MQTT Server

Library files:

  • adafruit_requests.mpy - This library allows us to perform HTTP requests and get responses back from servers. GET/POST/PUT/PATCH - they're all in here!
  • adafruit_fakerequests.mpy  - This library allows you to create fake HTTP requests by using local files.
  • adafruit_miniqr.mpy  - QR creation library lets us add easy-to-scan 2D barcodes to the E-Ink display
  • adafruit_dotstar.mpy - This library is used to control the onboard DotStars.
  • simpleio.mpy - This library is used for tone generation.
  • adafruit_ahtx0.mpy - This is used for the Humidity and Temperature Sensor
  • adafruit_dps310.mpy- This is used for the Barometric Pressure Sensor

Secrets

Even if you aren't planning to go online with your FunHouse, you'll need to have a secrets.py file in the root directory (top level) of your CIRCUITPY drive. If you do not intend to connect to wireless, it does not need to have valid data in it. Here's more info on the secrets.py file.

In this section, I'll guide you through replicating my Adafruit IO dashboard. You don't have to have all the feeds I do, but you will have to slightly update the project code for that.

First, go to the Adafruit IO feeds tab. Then, click the 'New Feed' button and create these 7 feeds:

  • battery
  • door
  • heatindex
  • humidity
  • lamp
  • neopixel
  • temperature

After you've created them, your Feeds page should look something like this, except the last values section should be blank for all of them.

Then, go to the Dashboards tab and click the 'New Dashboard' button. Name the dashboard whatever you want. I called mine 'IOT Hub'. Then, click on it and it should take you to a blank dashboard.

Next, click the gear icon and press the button labeled 'Create New Block'. You'll do this for every block you create.

The first block we'll be creating will be a Toggle block. You can find it in the upper left-hand corner.

The first block we'll be creating will be a Toggle block. You can find it in the upper left-hand corner.

We'll use this block to control a relay. In my setup, I have it hooked up to a lamp, so we'll use the lamp feed.

On the next step, set the on text to 'True' and the off text to 'False' (it is case sensitive). Set the title to whatever you want, in this case I'll use 'Lamp'.

Then, click 'Create Block' and it should show up on your dashboard.

 

Now, we'll make a block to display data from a temperature sensor. This one will be a Text block which is in the first column of the second row.

Set the feed to 'temperature'.

On the final screen, set the text size to medium, set the decimal places to 1, check 'show icon' and set the icon to 'thermometer'.

This block should appear right under the last block we made.

Now, we'll make the humidity block. This one is also a text block. 

Using the humidity feed, we'll set the text size to medium, decimal places to one, enable 'show icon' and set the icon to 'w:humidity' and click 'create block'.

Now, click the gear icon, then 'edit layout' and click and drag it so it's next to the temperature block.

After that, we'll make our fourth block, which displays the heat index. The heat index is what the temperature and humidity feels like. We'll also use a text block for this one. 

Set feed to 'heatindex', the text size to medium, decimal places to 1, and the icon to 'w:thermometer-exterior'.

Once you've created the block, click 'edit layout' and resize it so it's the same width as the lamp block.

Next, make a color picker block. This will be used so we can set the color of a neopixel strip remotely. Use the neopixel feed for this one. You don't need to do any more configuration for this block.

For our penultimate block, we'll make a LiPo charger indicator. This will use the gauge block and the battery feed.

Set the title to Battery, the gauge label to Percent, the low warning value to 20, the decimal places to zero, and set the icon to battery.

The last block will use the indicator block and the door feed. 

Set the block title to Door and set conditions to equals 1.

If you decided to add all the blocks, your dashboard should look something like the third picture.

If you'd like to laser cut a mount to easily put your FunHouse on the wall, the file below should work great. Also, if you want to 3d print it, you should be able to import it into your CAD software and extrude it.

Dash Display is not yet in the CircuitPython bundle but will be soon. If you download the bundle and it isn't in there, you can download it by clicking the button below this.

Installing the Project Code

Download a zip of the project by clicking 'Download: Project Bundle' in the code window below.

After unzipping the file, copy code.py to the CIRCUITPY drive which appears when the FunHouse is connected to your computer via a USB cable and turned on via a small on/off switch on the front of the board.

In addition to the libraries you installed in the 'FunHouse-Specific CircuitPython Libraries' section, you'll have to copy adafruit_dash_display and adafruit_display_shapes over to the board from the Bundle Zip file.

Your secrets.py file should at the very least have values for the fields ssidpasswordtimezoneaio_username, and aio_key. Make sure to copy it over to CIRCUITPY as well.

After you've copied everything over, this is what the CIRCUITPY drive should look like.

Be sure you have the libraries and secrets.py file complete and loaded onto the CIRCUITPY drive also or the code will not run properly.
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import ssl
import displayio
import board
from digitalio import DigitalInOut, Direction, Pull
from adafruit_display_text.label import Label
import terminalio
import touchio
import socketpool
import wifi
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from adafruit_dash_display import Hub

# Set up navigation buttons
up = DigitalInOut(board.BUTTON_UP)
up.direction = Direction.INPUT
up.pull = Pull.DOWN

select = DigitalInOut(board.BUTTON_SELECT)
select.direction = Direction.INPUT
select.pull = Pull.DOWN

down = DigitalInOut(board.BUTTON_DOWN)
down.direction = Direction.INPUT
down.pull = Pull.DOWN

back = touchio.TouchIn(board.CAP7)
submit = touchio.TouchIn(board.CAP8)

# Check for secrets.py. Note: for this project, your secrets.py needs an adafruit io api key as
# well as the wifi information
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# Make the rgb group for setting rgb hex values for NeoPixels
rgb_group = displayio.Group()
R_label = Label(
    terminalio.FONT,
    text="   +\nR:\n   -",
    color=0xFFFFFF,
    anchor_point=(0, 0.5),
    anchored_position=(5, 120),
    scale=2,
)
G_label = Label(
    terminalio.FONT,
    text="   +\nG:\n   -",
    color=0xFFFFFF,
    anchor_point=(0, 0.5),
    anchored_position=(90, 120),
    scale=2,
)
B_label = Label(
    terminalio.FONT,
    text="   +\nB:\n   -",
    color=0xFFFFFF,
    anchor_point=(0, 0.5),
    anchored_position=(175, 120),
    scale=2,
)
rgb_group.append(R_label)
rgb_group.append(G_label)
rgb_group.append(B_label)
R = Label(
    terminalio.FONT,
    text="00",
    color=0xFFFFFF,
    anchor_point=(0, 0.5),
    anchored_position=(35, 120),
    scale=2,
)
G = Label(
    terminalio.FONT,
    text="00",
    color=0xFFFFFF,
    anchor_point=(0, 0.5),
    anchored_position=(120, 120),
    scale=2,
)
B = Label(
    terminalio.FONT,
    text="00",
    color=0xFFFFFF,
    anchor_point=(0, 0.5),
    anchored_position=(205, 120),
    scale=2,
)
rgb_group.append(R)
rgb_group.append(G)
rgb_group.append(B)

# Set up callbacks

# pylint: disable=unused-argument
def rgb(last):
    """ Function for when the rgb screen is active """
    display.show(None)
    rgb_group[3].text = "00"
    rgb_group[4].text = "00"
    rgb_group[5].text = "00"
    display.show(rgb_group)
    time.sleep(0.2)
    index = 0
    colors = [00, 00, 00]

    while True:
        if select.value:
            index += 1
            if index == 3:
                index = 0
            time.sleep(0.3)
            continue

        if up.value:
            colors[index] += 1
            if colors[index] == 256:
                colors[index] = 0
            rgb_group[index + 3].text = hex(colors[index])[2:]
            time.sleep(0.01)
            continue

        if down.value:
            colors[index] -= 1
            if colors[index] == -1:
                colors[index] = 255
            rgb_group[index + 3].text = hex(colors[index])[2:]
            time.sleep(0.01)
            continue

        if submit.value:
            color = ["{:02x}".format(colors[i]) for i in range(len(colors))]
            color = "#" + "".join(color)
            iot.publish("neopixel", color)
            break

        if back.value:
            break
        time.sleep(0.1)

    display.show(None)
    time.sleep(0.1)

def rgb_set_color(message):
    """ Sets the color of the rgb label based on the value of the feed """
    return int(message[1:], 16)

def door_color(message):
    """ Sets the color of the door label based on the value of the feed """
    door = bool(int(message))
    if door:
        return int(0x00FF00)
    return int(0xFF0000)

def on_door(client, feed_id, message):
    """ Sets the door text based on the value of the feed """
    door = bool(int(message))
    if door:
        return "Door: Closed"
    return "Door: Open"

def pub_lamp(lamp):
    if isinstance(lamp, str):
        lamp = eval(lamp)  # pylint: disable=eval-used
    iot.publish("lamp", str(not lamp))
    # funhouse.set_text(f"Lamp: {not lamp}", 0)
    time.sleep(0.3)

display = board.DISPLAY

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

print("Connecting to %s" % secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!" % secrets["ssid"])

# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
    socket_pool=pool,
    ssl_context=ssl.create_default_context(),
)

# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

iot = Hub(display=display, io=io, nav=(up, select, down, back, submit))

iot.add_device(
    feed_key="lamp",
    default_text="Lamp: ",
    formatted_text="Lamp: {}",
    pub_method=pub_lamp,
)
iot.add_device(
    feed_key="temperature",
    default_text="Temperature: ",
    formatted_text="Temperature: {:.1f} C",
)
iot.add_device(
    feed_key="humidity", default_text="Humidity: ", formatted_text="Humidity: {:.2f}%"
)
iot.add_device(
    feed_key="neopixel",
    default_text="LED: ",
    formatted_text="LED: {}",
    color_callback=rgb_set_color,
    pub_method=rgb,
)
iot.add_device(
    feed_key="battery",
    default_text="Battery: ",
    formatted_text="Battery: {}%",
)
iot.add_device(
    feed_key="door",
    default_text="Door: ",
    formatted_text="Door: {}",
    color_callback=door_color,
    callback=on_door,
    )

iot.get()

while True:
    iot.loop()
    time.sleep(0.01)

Customizing the Devices

Lines 204-236 in code.py are where I add all the devices. It's good to note that while I do call them devices, they're just Adafruit IO feeds with a few functions that make it easier to handle the data how we want to.

If you'd like to add your own device, it's good to know what the parameters are:

  • feed_key - The key of the Adafruit IO feed you want to use. This can't be left blank.
  • default_text - The text to set to the display before a value has been gotten. You can leave this blank and it should be fine.
  • formatted_text - The text in a way that can be formatted using curly braces (ex. "Lamp: {}". If you want a specific number of decimal points to be displayed put :.1f in the curly braces, replacing 1 with the precision you want. If you leave this blank it won't display any text unless you have a custom callback function that returns the formatted text you want.
  • color_callback - The function you want to be called whenever the device gets a new value to set the color of the text for that device. You can see two examples of this on line 150 and 154 of code.py. You can leave this blank.
  • callback - The callback you want to run after the device gets a new message. This can do a number of things like turn on the FunHouse's built in dotstars or play a sound. There's a function on line 161 that shows how you could use a callback to set the text in a slightly more complicated way. If left blank, this defaults to a built-in callback that just uses formatted_text to set the text.
  • pub_method - The function you want to call when the select button is pressed. Only 2 devices in code.py have one of these. If you look at line 168 you can see an example of a simple one that just toggles the lamp, but if you look at line 102 you can see a much more complicated one that displays a whole new screen and ui.

Code Behavior

The code should show 6 lines with the various feeds. To navigate use the three buttons left of the display. The upper button moves the cursor up, the middle button will let you publish a new value to the feed if that is enabled (in my example it's only enabled for the lamp and neopixel feed).

If you wanted to turn the lamp on, you'd press the middle button and it will turn on pretty quickly.

If you want to change the color of the NeoPixels, navigate down to it with the third button then select it with the middle button. From there it will take you to a screen where you can edit the hex values for the red, green, and blue components of the NeoPixels. Use the up and down button to increase or decrease them and use the select button to switch between the colors. When you're done, you can submit it with the Capacitive Touch 8 button on the upper right of the screen. If you decide that you don't want to submit it, press the Capacitive Touch 7 button on the upper left of the screen and it will take you back to the home screen without submitting the value you set.

First, the code makes all of the required imports, this may seem like a lot, but most of them are just for making the connection to Adafruit IO.

import time
import ssl
import displayio
import board
from digitalio import DigitalInOut, Direction, Pull
from adafruit_display_text.label import Label
import terminalio
import touchio
import socketpool
import wifi
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from adafruit_dash_display import Hub

Next, the navigation buttons are defined so they can be passed to the Dash Display library later.

up = DigitalInOut(board.BUTTON_UP)
up.direction = Direction.INPUT
up.pull = Pull.DOWN

select = DigitalInOut(board.BUTTON_SELECT)
select.direction = Direction.INPUT
select.pull = Pull.DOWN

down = DigitalInOut(board.BUTTON_DOWN)
down.direction = Direction.INPUT
down.pull = Pull.DOWN

back = touchio.TouchIn(board.CAP7)
submit = touchio.TouchIn(board.CAP8)

After that, the code makes sure that there is a secrets.py file present on the board.

# Check for secrets.py. Note: for this project, your secrets.py needs an adafruit io api key as
# well as the wifi information
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

Now, the DisplayIO group that the NeoPixel setter will use is defined. It consists of 6 labels, 3 that are static and 3 that are changed by user input.

rgb_group = displayio.Group()
R_label = Label(
    terminalio.FONT,
    text="   +\nR:\n   -",
    color=0xFFFFFF,
    anchor_point=((0, 0.5)),
    anchored_position=((5, 120)),
    scale=2,
)
G_label = Label(
    terminalio.FONT,
    text="   +\nG:\n   -",
    color=0xFFFFFF,
    anchor_point=((0, 0.5)),
    anchored_position=((90, 120)),
    scale=2,
)
B_label = Label(
    terminalio.FONT,
    text="   +\nB:\n   -",
    color=0xFFFFFF,
    anchor_point=((0, 0.5)),
    anchored_position=((175, 120)),
    scale=2,
)
rgb_group.append(R_label)
rgb_group.append(G_label)
rgb_group.append(B_label)
R = Label(
    terminalio.FONT,
    text="00",
    color=0xFFFFFF,
    anchor_point=((0, 0.5)),
    anchored_position=((35, 120)),
    scale=2,
)
G = Label(
    terminalio.FONT,
    text="00",
    color=0xFFFFFF,
    anchor_point=((0, 0.5)),
    anchored_position=((120, 120)),
    scale=2,
)
B = Label(
    terminalio.FONT,
    text="00",
    color=0xFFFFFF,
    anchor_point=((0, 0.5)),
    anchored_position=((205, 120)),
    scale=2,
)
rgb_group.append(R)
rgb_group.append(G)
rgb_group.append(B)

Continuing what the code just did, the function that will use the DisplayIO group is defined. This function lets you input a hex value using the navigation buttons and then sends it to Adafruit IO.

# pylint: disable=unused-argument
def rgb(last):
    """ Function for when the rgb screen is active """
    display.show(None)
    rgb_group[3].text = "00"
    rgb_group[4].text = "00"
    rgb_group[5].text = "00"
    display.show(rgb_group)
    time.sleep(0.2)
    index = 0
    colors = [00, 00, 00]

    while True:
        if select.value:
            index += 1
            if index == 3:
                index = 0
            time.sleep(0.3)
            continue

        if up.value:
            colors[index] += 1
            if colors[index] == 256:
                colors[index] = 0
            rgb_group[index + 3].text = hex(colors[index])[2:]
            time.sleep(0.01)
            continue

        if down.value:
            colors[index] -= 1
            if colors[index] == -1:
                colors[index] = 255
            rgb_group[index + 3].text = hex(colors[index])[2:]
            time.sleep(0.01)
            continue

        if submit.value:
            color = ["{:02x}".format(colors[i]) for i in range(len(colors))]
            color = "#" + "".join(color)
            iot.publish("neopixel", color)
            break

        if back.value:
            break
        time.sleep(0.1)

    display.show(None)
    time.sleep(0.1)

The next two color callbacks are defined here. The first one just sets the text color to the value of the NeoPixel feed, which should always be an RGB hex string.

The second color callback sets the text color to red if the door is open and green if it is closed.

def rgb_set_color(message):
    """ Sets the color of the rgb label based on the value of the feed """
    return int(message[1:], 16)

def door_color(message):
    """ Sets the color of the door label based on the value of the feed """
    door = bool(int(message))
    if door:
        return int(0x00FF00)
    return int(0xFF0000)

Then, a callback for the door feed is defined. This callback sets the text to "Door: Open" if the value of the door feed is 'False' and thus open and "Door: Closed" if it is 'True' and thus closed.

def on_door(client, feed_id, message):
    """ Sets the door text based on the value of the feed """
    door = bool(int(message))
    if door:
        return "Door: Closed"
    return "Door: Open"

Next, the publish method for the lamp is defined. Basically it just publishes the opposite of whatever value was last sent from the lamp feed.

def pub_lamp(lamp):
    if isinstance(lamp, str):
        lamp = eval(lamp)  # pylint: disable=eval-used
    iot.publish("lamp", str(not lamp))
    # funhouse.set_text(f"Lamp: {not lamp}", 0)
    time.sleep(0.3)

After that, the code does all the Adafruit IO setup.

display = board.DISPLAY

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

print("Connecting to %s" % secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!" % secrets["ssid"])

# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
    socket_pool=pool,
    ssl_context=ssl.create_default_context(),
)

# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

The code now defines the Dash Display Hub object and passes it the display, the Adafruit IO object, and the navigation buttons.

iot = Hub(display=display, io=io, nav=(up, select, down, back, submit))

The code then adds all the devices to the Hub object so they will be displayed.

iot.add_device(
    feed_key="lamp",
    default_text="Lamp: ",
    formatted_text="Lamp: {}",
    pub_method=pub_lamp,
)
iot.add_device(
    feed_key="temperature",
    default_text="Temperature: ",
    formatted_text="Temperature: {:.1f} C",
)
iot.add_device(
    feed_key="humidity", default_text="Humidity: ", formatted_text="Humidity: {:.2f}%"
)
iot.add_device(
    feed_key="neopixel",
    default_text="LED: ",
    formatted_text="LED: {}",
    color_callback=rgb_set_color,
    pub_method=rgb,
)
iot.add_device(
    feed_key="battery",
    default_text="Battery: ",
    formatted_text="Battery: {}%",
)
iot.add_device(
    feed_key="door",
    default_text="Door: ",
    formatted_text="Door: {}",
    color_callback=door_color,
    callback=on_door,
    )

iot.get()

Finally, the code calls the Hub object's loop function which checks all the nav buttons and does things accordingly.

while True:
    iot.loop()
    time.sleep(0.01)
This example is not designed to run on the FunHouse. It is an example of a device you could connect to Adafruit IO and then display the connected feed on your FunHouse IoT hub.

This example uses a PyPortal Titano as a remote control for NeoPixels. It uses HTTP which is pretty slow, but MQTT on PyPortals is a bit unreliable at the moment.

For this project, you need:

The PyPortal Titano is the big sister to our popular PyPortal now with twice as many pixels! The PyPortal...
$59.95
In Stock
It's what you've been waiting for, the Feather M4 Express featuring ATSAMD51. This Feather is fast like a swift, smart like an owl, strong like a ox-bird (it's half ox,...
$22.95
In Stock
Give your Feather project a lift with the Adafruit AirLift FeatherWing - a FeatherWing that lets you use the powerful ESP32 as a WiFi co-processor. You probably have your...
$12.95
In Stock
This is the FeatherWing Tripler - a prototyping add-on and more for all Feather boards. This is similar to our
$8.50
In Stock

If the FeatherWing tripler is out of stock, you can also use a FeatherWing Doubler and put Stacking Headers on either the Feather M4 or the AirLift FeatherWing.

You can't bake a cake without flour, sugar, and baking soda? Cream cheese? Muscadet? Ok - to be honest we don't do much cake baking.  But we do light up a TON of...
$24.95
In Stock

PyPortal Setup

First click Download Project Bundle below. This zip file will contain everything you need for this example. However, the files are also in the zip file you downloaded for the FunHouse, so you can get them from either one, just make sure you take the files from the neopixel_remote directory.

# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""
NeoPixel remote control using PyPortal Titano.

Colors used are taken from Adafruit_CircuitPython_LED_Animation library
"""

import time
import math
import board
import busio
from digitalio import DigitalInOut
import displayio
from adafruit_display_shapes.rect import Rect
import adafruit_imageload
import adafruit_touchscreen

# ESP32 SPI
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager

# Import NeoPixel Library
import neopixel

# Import Adafruit IO HTTP Client
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError

ts = adafruit_touchscreen.Touchscreen(
    board.TOUCH_XL,
    board.TOUCH_XR,
    board.TOUCH_YD,
    board.TOUCH_YU,
    calibration=((5200, 59000), (5800, 57000)),
    size=(480, 320),
)
RED = 0xFF0000
YELLOW = 0xFF9600
ORANGE = 0xFF2800
GREEN = 0x00FF00
TEAL = 0x00FF78
CYAN = 0x00FFFF
BLUE = 0x0000FF
PURPLE = 0xB400FF
MAGENTA = 0xFF0014
WHITE = 0xFFFFFF
BLACK = 0x000000

GOLD = 0xFFDE1E
PINK = 0xF15AFF
AQUA = 0x32FFFF
JADE = 0x00FF28
AMBER = 0xFF6400

colors = [
    None,
    None,
    GREEN,
    PURPLE,
    GOLD,
    AMBER,
    None,
    None,
    ORANGE,
    BLUE,
    BLACK,
    JADE,
    None,
    None,
    YELLOW,
    CYAN,
    WHITE,
    AQUA,
    None,
    None,
    RED,
    TEAL,
    MAGENTA,
    PINK,
]

print(colors)
group = displayio.Group()
# pyportal_setter.xcf has been included so you can edit the colors used in GIMP, just make sure to
# change them here as well
background, palette = adafruit_imageload.load(
    "bmps/pyportal_setter.bmp", bitmap=displayio.Bitmap, palette=displayio.Palette
)
tile_grid = displayio.TileGrid(background, pixel_shader=palette)
group.append(tile_grid)
rect = Rect(0, 0, 160, 320, fill=0x000000)
group.append(rect)
print(len(group))

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# PyPortal ESP32 Setup
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
ADAFRUIT_IO_USER = secrets["aio_username"]
ADAFRUIT_IO_KEY = secrets["aio_key"]

# Create an instance of the Adafruit IO HTTP client
io = IO_HTTP(ADAFRUIT_IO_USER, ADAFRUIT_IO_KEY, wifi)

try:
    # Get the 'temperature' feed from Adafruit IO
    neopixel_feed = io.get_feed("neopixel")
except AdafruitIO_RequestError:
    neopixel_feed = io.create_new_feed("neopixel")

board.DISPLAY.show(group)
print("ready")
last_color = 257
last_index = 0
while True:
    p = ts.touch_point
    if p:
        x = math.floor(p[0] / 80)
        y = math.floor(p[1] / 80)
        index = 6 * y + x
        # Used to prevent the touchscreen sending incorrect results
        if last_index == index:
            color = colors[index]
            if colors[index]:
                group[1].fill = color
                if last_color != color:
                    color_str = "#{:06x}".format(color)
                    print(color_str)
                    io.send_data(neopixel_feed["key"], color_str)
                    last_color = color
        last_index = index
    time.sleep(0.1)

First, you'll need to copy over the following libraries to your PyPortal Titano:

  • adafruit_display_shapes/
  • adafruit_imageload/
  • adafruit_io/
  • adafruit_esp32spi/
  • adafruit_requests.mpy
  • adafruit_touchscreen.mpy
  • neopixel.mpy

After you've done that, rename neopixel_remote.py to code.py and put it on the PyPortal.

Next, make a new folder on your PyPortal named bmps and put pyportal_setter.bmp inside it.

Finally, copy over your secrets.py file.

After you've done all that, this is what your CIRCUITPY drive should look like:

When you've done all this, your PyPortal should look like this and you should be able to tap a square and have the top of the display turn that color as well as see the Adafruit IO color indicator turn that color.

Feather Setup

# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""
Sets NeoPixel color based on an Adafruit IO feed.
Uses:
    * https://www.adafruit.com/product/3811
    * Feather board
    * https://www.adafruit.com/product/4264
    * https://www.adafruit.com/product/2890

If your Feather board has STEMMA QT, you'll need one of these:
    * https://www.adafruit.com/product/4209

But if it doesn't, use stacking headers on either the Feather or the AirLift FeatherWing
"""

import board
import busio
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from digitalio import DigitalInOut

### WiFi ###

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# Change the first number to the pin the data line is plugged in to and the second number
# to the number of pixels
pixels = neopixel.NeoPixel(board.D5, 300)

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)

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
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Define callback functions which will be called when certain events happen.
# pylint: disable=unused-argument
def connected(client):
    client.subscribe("neopixel")


def subscribe(client, userdata, topic, granted_qos):
    # This method is called when the client subscribes to a new feed.
    print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))


def on_neopixel(client, topic, message):
    print(message)
    colors = [
        int(message.split("#")[1][i : i + 2], 16) for i in range(0, len(message) - 1, 2)
    ]
    print(colors)
    pixels.fill(colors)


# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
)


# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

io.add_feed_callback("neopixel", on_neopixel)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

io.get("neopixel")

while True:
    io.loop()

First, copy over the required libraries:

  • adafruit_esp32spi/
  • adafruit_io/
  • adafruit_minimqtt/
  • adafruit_requests.mpy
  • neopixel.mpy

The code above should already be downloaded. Rename it to code.py and copy it over to your Feather.

After you've copied all that over, copy your secrets.py over and you should be set as far as the files are concerned.

Assembly

Solder the headers that came with each device. Then put the Feather and the AirLift FeatherWing in the FeatherWing Tripler and attach the data wire from the NeoPixel strip (often green. I used one of these to make it a bit easier) to pin D5 (third pin from the end furthest from the USB port of the header with less pins) on the Tripler and then connect the ground wire (usually white or black) to a GND pin on the Tripler.

Afer you've done all this it should look something like this:

Now, connect the NeoPixel strip to a power source. If you have a lot of pixels, use a power supply but if you only have a few, you can get away with connecting it to the USB pin (note: this only works if you're powering the board through USB. If you're powering it with a LiPo this won't work).

Usage

To use the remote, just press one of the colored squares and it will send that to Adafruit IO. Then, the Feather will update the NeoPixels accordingly.

This example is not designed to run on the FunHouse. It is an example of a device you could connect to Adafruit IO and then display the connected feed on your FunHouse IoT hub.

This example uses a Feather RP2040 (although any Feather board with stemma works) and an LC709203 to track the charging of a LiPo battery with Adafruit IO.

For this project, you will need:

A new chip means a new Feather, and the Raspberry Pi RP2040 is no exception. When we saw this chip we thought "this chip is going to be awesome when we give it the Feather...
$11.95
In Stock
Give your Feather project a lift with the Adafruit AirLift FeatherWing - a FeatherWing that lets you use the powerful ESP32 as a WiFi co-processor. You probably have your...
$12.95
In Stock
A Feather board without ambition is a Feather board without FeatherWings! This is the FeatherWing OLED: it adds a 128x32 monochrome OLED plus 3 user buttons to...
$14.95
In Stock
Low cost Lithium Polymer batteries have revolutionized electronics - they're thin, they're light, they can be regulated down to 3.3V and they're easy to charge. On your...
$6.95
In Stock
These two Female Stacking Headers alone are, well, lonely. But pair them with any of our Feather boards and...
$1.25
In Stock
This is the FeatherWing Doubler - a prototyping add-on and more for all Feather boards. This is similar to our
$7.50
In Stock
This 4-wire cable is 50mm / 1.9" long and fitted with JST SH female 4-pin connectors on both ends. Compared with the chunkier JST PH these are 1mm pitch instead of 2mm, but...
$0.95
In Stock
Lithium-ion polymer (also known as 'lipo' or 'lipoly') batteries are thin, light, and powerful. The output ranges from 4.2V when completely charged to 3.7V. This...
$12.50
In Stock

If the cable or battery is out of stock, you can buy any other size, although for the STEMMA QT cable, shorter is better.

Feather Setup

First, click Download Project Bundle below. This zip file will contain everything you need for this example. However, the files are also in the zip file you downloaded for the FunHouse, so you can get them from either one, just make sure you take the files from the battery_peripheral directory.

# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""
Adafruit IO connected LiPo charger.
Uses:
    * https://www.adafruit.com/product/4712
    * Feather board (M4 or RP2040 reccomended)
    * https://www.adafruit.com/product/4264
    * https://www.adafruit.com/product/2890
    * https://www.adafruit.com/product/2900
Either the Feather or the Airlift Featherwing should have stacking headers for the display.
"""

import time
import board
from adafruit_lc709203f import LC709203F
import busio
from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT

import displayio
import terminalio
from adafruit_display_text import label
import adafruit_displayio_ssd1306

displayio.release_displays()

### WiFi ###

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise


# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)

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
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Define callback functions which will be called when certain events happen.
# pylint: disable=unused-argument
def connected(client):
    client.subscribe("battery")


def subscribe(client, userdata, topic, granted_qos):
    # This method is called when the client subscribes to a new feed.
    print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))


def message(client, feed_id, payload):
    print("Feed {0} received new value: {1}".format(feed_id, payload))


# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
)


# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe
io.on_message = message

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

display_bus = displayio.I2CDisplay(board.I2C(), device_address=0x3C)

WIDTH = 128
HEIGHT = 32
BORDER = 2

display = adafruit_displayio_ssd1306.SSD1306(display_bus, width=WIDTH, height=HEIGHT)

splash = displayio.Group()
display.show(splash)

digital_label = label.Label(
    terminalio.FONT, text="Battery Percent: ", color=0xFFFFFF, x=4, y=4
)
splash.append(digital_label)
alarm_label = label.Label(terminalio.FONT, text="Voltage: ", color=0xFFFFFF, x=4, y=14)
splash.append(alarm_label)


sensor = LC709203F(board.I2C())

start = 0
while True:
    io.loop()
    percent = sensor.cell_percent
    if time.time() - start > 60:
        io.publish("battery", int(percent))
        start = time.time()
    splash[0].text = f"Percent: {str(int(percent))}%"
    splash[1].text = f"Voltage: {str(sensor.cell_voltage)}"
    time.sleep(1)

The first thing you'll need to do is copy all the required libraries over. The libraries needed are:

  • adafruit_esp32spi/
  • adafruit_minimqtt/
  • adafruit_io/
  • adafruit_display_text/
  • adafruit_lc709203f.mpy
  • adafruit_requests.mpy
  • neopixel.mpy
  • adafruit_displayio_ssd1306.mpy

After you've copied over those libraries, copy code.py over to the CIRCUITPY drive.

Finally, copy secrets.py to the CIRCUITPY drive.

After you've done all that, this is what your CIRCUITPY drive should look like:

Assembly

Solder the stacking headers to either the RP2040 or the AirLift Featherwing, solder the normal headers to whichever one you didn't solder the stacking headers to and the OLED. Then, solder the headers that came with the FeatherWing Doubler to it (it's a bit easier to do if you put 2 Feather boards in to hold them in place before you get 2 pins on each header soldered).

Then, put the Feather RP2040 and AirLift FeatherWing on the doubler and put the OLED on top of the Feather.

Hook up the LiPo charger to the STEMMA QT connector on the Feather using either of the STEMMA QT connectors on the charger. Then, use the JST 2-PH cable that came with it to connect the charger to the Feather. You can use either jack on the charger.

Now that you've set everything up, plug a battery in and press the RESET button and it should look something like this:

Having issues removing the battery cables? Try putting a pair of tweezers through the hole on the top of the jack and use them to push the connector part out.
This example is not designed to run on the FunHouse. It is an example of a device you could connect to Adafruit IO and then display the connected feed on your FunHouse IoT hub.

This project uses a Feather and either the Relay FeatherWing or the 4 Outlet Power Relay to control devices that turn on and off through Adafruit IO.

For this project, you will need:

It's what you've been waiting for, the Feather M4 Express featuring ATSAMD51. This Feather is fast like a swift, smart like an owl, strong like a ox-bird (it's half ox,...
$22.95
In Stock
Give your Feather project a lift with the Adafruit AirLift FeatherWing - a FeatherWing that lets you use the powerful ESP32 as a WiFi co-processor. You probably have your...
$12.95
In Stock
This is the FeatherWing Tripler - a prototyping add-on and more for all Feather boards. This is similar to our
$8.50
In Stock
A Feather board without ambition is a Feather board without FeatherWings! This is the Power Relay FeatherWing. It gives you power to control, and control over power....
$9.95
In Stock

OR

Say goodbye to hazardous high voltage wiring and create the Internet of Things with safe, reliable power control....
Out of Stock

Feather Setup

First, click Download Project Bundle below. This zip file will contain everything you need for this example. However, the files are also in the zip file you downloaded for the FunHouse, so you can get them from either one, just make sure you take the files from the relay_peripheral directory.

# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""
Controlling a relay with Adafruit IO
Uses:
    * Feather board
    * https://www.adafruit.com/product/2890
    * https://www.adafruit.com/product/4264

    * https://www.adafruit.com/product/3191
    OR
    * https://www.adafruit.com/product/2935
"""
import board
import busio
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from digitalio import DigitalInOut, Direction

### WiFi ###

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# If you are using a Relay FeatherWing, make sure this pin corresponds to the pin shorted on the
# bottom of the Relay FeatherWing
RELAY = DigitalInOut(board.D10)
RELAY.direction = Direction.OUTPUT

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)

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
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Define callback functions which will be called when certain events happen.
# pylint: disable=unused-argument
def connected(client):
    client.subscribe("lamp")


def subscribe(client, userdata, topic, granted_qos):
    # This method is called when the client subscribes to a new feed.
    print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))


def on_lamp(client, topic, message):
    RELAY.value = eval(message)  # pylint: disable=eval-used


# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
)


# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

io.add_feed_callback("lamp", on_lamp)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

io.get("lamp")

while True:
    io.loop()

The first thing you'll need to do is copy all the required libraries over. The required libraries are:

  • adafruit_esp32spi/
  • adafruit_minimqtt/
  • adafruit_io/
  • neopixel.mpy
  • adafruit_requests.mpy

After you've copied all that over, rename relay_daughter.py to code.py and copy it over to the CIRCUITPY drive.

Finally, copy secrets.py to the CIRCUITPY drive.

After you've done all that, this is what your CIRCUITPY drive should look like:

Assembly

Solder all the headers to the devices they came with. Then, put everything on the FeatherWing Tripler.

If you're using the Four Outlet Power Relay, then plug a breadboard wire into pin D10 on the FeatherWing Tripler and another wire into the GND pin. Then pull out the green part that the pins go into in the Relay itself and plug the wire from D10 into the receptacle marked with a + (the one on the left) and the wire from GND into the receptacle with a - (the one on the right). Then, screw in the two screws that hold the wires in place and plug the green part back into the Power Relay.

Now that you've set everything up, this is what yours should look like if you're using the Relay FeatherWing:

And, if you're using the 4-Outlet Power Relay, this is what it should look like:

This guide was first published on May 26, 2021. It was last updated on 2021-05-26 10:50:53 -0400.