Have you always wanted to upgrade your ensemble with a creepy-cool creature PCB silkscreen and an eye-blistering arrangement of LEDs? We love to put NeoPixels on our face, as evidenced by our many glowy LED glasses projects. Each of these requires quite a bit of soldering, and the cost of each NeoPixel adds up quickly. So we wanted to make a PCB assembly that can be used by any microcontroller to make glamorous face-tronics.

Please note: You get one EyeLights LED Glasses panel per order. The silkscreen selection is random per order; we can't change or control which one you get!

The Adafruit EyeLights LED Glasses have 116 artfully arranged 2x2mm RGB LEDs, all controlled with an IS31FL3741 I2C Driver that handles all the PWMing, so it's plug-and-play with almost any microcontroller.

On each side are STEMMA QT / JST-SH plugs - use these with one of our cables to attach it to your driver board of choice. Of course, you can pick left or right, then if you want to add on more hardware, like an accelerometer or light sensor, you can chain onto the other side. There's also six mounting holes for attaching to a glasses frame of your choosing - we recommend getting some 'fashion frames' from the mall or a street vendor, they're all the style and will provide great mechanical support.

We have four different silkscreen designs: Bug, Wolf, Cat, and Dragon (peep those fearsome fangs!) Each design is exactly the same mechanically and electrically, the only difference is what is silkscreened on top of the PCB.

Please note: You get one EyeLights LED Glasses panel per order. The silkscreen selection is random per order; we can't change or control which one you get!

Gaze upon these features:

  • IS31Fl3741 LED driver chip uses I2C to control the LEDs with 8-bit PWM per color (24-bit per RGB LED), write pixel data and it will handle the matrix driving automatically.
  • Power and communicate over STEMMA QT for easy wiring
  • The LEDs are arranged as 2 x 24-LED rings around each eye and an overlapping 16x5 matrix. The matrix has two bottom pixels 'missing' over the nose. Some LEDs are shared between both matrix and rings!
  • Arduino and CircuitPython/Python library support

If you're looking for the perfect companion to your Adafruit EyeLights LED Glasses, check out the Adafruit EyeLights LED Glasses Driver! This board is designed to be a thin, bluetooth-enabled driver board for our Adafruit EyeLights LED Glasses RGB LED matrix. That said, it's a perfectly good stand-alone development board for the Nordic nRF52840 chipset, with a very slim design, optional LiPo battery support, a few sensors, and a Stemma QT port for adding other devices or sensors with I2C plug-and-play.

The driver looks a little like a Feather but it does not have any breakout pins to keep it very compact. If you need access to GPIO pins, we recommend an nRF52840 ItsyBitsy, nRF52840 Feather or Feather Sense.

In exchange for GPIO outputs, we added some sensors instead: each board comes with a LIS3DH triple-axis accelerometer that can be used for motion and orientation sensing, and a PDM digital microphone for audio sensing. To add more sensors or connect to the EyeLights LED Glasses front panel, there's a  STEMMA QT connector for plug-and-play I2C support.

Unlike our Itsy/Feather boards, this driver also comes with a proper on/off switch which will cut power to the microcontroller and external sensors. There's optional LiPo charge support because we think that many folks will want to power this board with AAA or coin cell batteries. If you'd like to enable LiPo charging, solder across the jumper pads on the back and then make sure to only use 4.2V/3.7V rechargeable batteries in the battery port.

The nRF52840 is a lovely Bluetooth LE microcontroller, with good support in both Arduino and CircuitPython. It feathers a Cortex M4 processor with 1 MB of FLASH and 256KB of SRAM. Best of all, it's got that native USB! Finally, no need for a separate USB serial chip like CP2104 or FT232. Serial is handled as a USB CDC descriptor, and the chip can act like a keyboard, mouse, MIDI device or even disk drive. This chip has TinyUSB support - that means you can use it with Arduino as a native USB device and act as UART (CDC), HID, Mass Storage, MIDI and more!

Board Features:

  • ARM Cortex M4F (with HW floating point acceleration) running at 64MHz
  • 1MB flash and 256KB SRAM
  • Bluetooth Low Energy compatible 2.4GHz radio (Details available in the nRF52840 product specification)
  • FCC / IC / TELEC certified module with up to +8dBm output power
  • 2MB external QSPI flash for CircuitPython file storage
  • Built in LIS3DH accelerometer and PDM microphone
  • Red LED for general purpose blinking, plus a tiny NeoPixel for colorful feedback
  • STEMMA QT connector for plug-and-play I2C support.
  • JST PH 2-pin battery port with optional LiPoly charger
  • 4 mounting holes/slots
  • Reset button and User button
  • Native USB supported by every OS - can be used in Arduino or CircuitPython as USB serial console, Keyboard/Mouse HID, even a little disk drive for storing Python scripts.
  • Can be used with Arduino IDE or CircuitPython
  • Comes pre-loaded with the UF2 bootloader, which looks like a USB storage key. Simply drag firmware on to program, no special tools or drivers needed! It can be used to load up CircuitPython or pre-compiled Arduino sketches.

For developers, we pre-programed the chip with our UF2 bootloader, which can use either command line UART programming with nrfutil (we use this for Arduino) or drag-n-drop mass storage, for CircuitPython installation and also because mass-storage-drive bootloaders make updating firmware so easy. Want to program the chip directly? You can use our command line tools with your favorite editor and toolchain. If you want to use an SWD programmer/debugger (for even more advanced usage), we have broken out the SWD pads for easy soldering.

The EyeLights LED Glasses Driver and EyeLights LED Glasses are packed full of features! Here are the details.

The PDF of the diagram above is available here.

EyeLights LED Glasses Driver Details

First up, a detailed look at the EyeLights Driver board.

nRF52840 and QSPI Flash

  • The blue and silver module located on the end of the board, opposite the USB connector, is the nRF52840. It is an ARM Cortex M4F (with HW floating point acceleration) running at 64MHz, with 1MB flash and 256KB SRAM. It has a Bluetooth Low Energy compatible 2.4GHz radio, and is an FCC / IC / TELEC certified module with up to +8dBm output power.
  • The grey rectangle on the bottom of the board to the left of the nRF module is the 2MB external QSPI flash for CircuitPython file storage.

QSPI is neat because it allows you to have 4 data in/out lines instead of just SPI's single line in and single line out. This means that QSPI is at least 4 times faster. But in reality is at least 10x faster because you can clock the QSPI peripheral much faster than a plain SPI peripheral.

USB and Power

  • Along the bottom edge of the board towards the left end is the USB Type C connector. It is used for power and sending data to the board.
  • To the right of the USB connector is a battery JST connector labeled BAT on the board. It is recommended to use the batteries Adafruit sells because the proper polarity is verified. Polarity cannot be guaranteed with other batteries.
  • On the top of the board, in the middle is an On / Off switch, labeled On and Off on the board. This controls power to the board. 
  • On the back of the board is a jumper labeled Optional Lipo Charge. Some folks will prefer to use AAA  battery packs. If you'd like to enable LiPo charging, short the jumper on the back and then make sure to only use 4.2V/3.7V rechargeable batteries in the battery port.
If you plug your driver board into your computer and nothing happens, make sure the switch is in the "On" position, which is closer to the top of the board.

STEMMA QT Connector

  • On the left side of the board is a STEMMA QT connector, labeled I2C on the board, which enables plug-and-play I2C support. It allows for a solderless connection to the EyeLights Glasses panel, as well as a variety of other sensors and breakouts.
  • In CircuitPython, you can use the STEMMA connector with board.SCL and board.SDA, or board.STEMMA_I2C().

User Button Switch

  • On the top edge of the board, towards the left end, is a user button switch. It is labeled SW on the board, and can be used as in input. It is available in CircuitPython as board.SWITCH, and in Arduino as PIN_BUTTON1.

LED and NeoPixel

  • Along the top edge of the board, towards the right end of the board is a red LED labeled LED on the board. This is controllable in CircuitPython as board.LED, and in Arduino as LED_RED.
  • To the right of the red LED is an RGB NeoPixel LED labeled Neo on the board. It is addressable in CircuitPython as board.NEOPIXEL, and in Arduino as PIN_NEOPIXEL.

Accelerometer and Microphone

  • Towards the center of the board is an LIS3DH accelerometer, labeled Accel on the board. Interface with it using I2C. In CircuitPython, you would use board.I2C(). The interrupt pin is available in CircuitPython as board.ACCELEROMETER_INTERRUPT.
  • Above the accelerometer, is a PDM microphone, labeled Mic on the board. You can interface with it in CircuitPython with board.MICROPHONE_CLOCK and board.MICROPHONE_DATA. In Arduino, it's PIN_PDM_CLK and PIN_PDM_DIN.

Reset Button

  • To the left of the user switch, is the Reset button, labeled Reset on the board. It is used to reset the board, or if double-pressed, to enter the bootloader for loading CircuitPython.

Debug Pins

  • On the bottom of the board, on the right side, are three debug pins, labeled left-to-right Rt, IO, and CL on the board. These are reset, data and clock. Use for SWD debugging / programming.

EyeLights LED Glasses Panel

Now, a detailed look at the EyeLights Glasses panel features.

IS31FL3741 I2C LED Driver

  • In the center of the panel, is the IS31FL3741 I2C LED driver chip. It uses I2C to control the LEDs with 8-bit PWM per color (24-bit per RGB LED), write pixel data, and it will handle the matrix driving automatically.

LEDs

  • Arranged as 2 x 24-LED rings around each eye and an overlapping 16x5 matrix, are 116 RGB LEDs. These are NOT NeoPixel or DotStar LEDs! That's why this board comes with the IS31FL3741 to talk to them.

STEMMA QT Connectors

  • On each side of the panel is a STEMMA QT connector.  It allows for a quick and solderless connection to the EyeLights Glasses Driver board, as well as other STEMMA QT microcontrollers, using a variety of STEMMA QT cables.

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.

CircuitPython Quickstart

Follow this step-by-step to quickly get CircuitPython running on your board.

Click the link above to download the latest CircuitPython UF2 file.

Save it wherever is convenient for you.

Plug your board into your computer, using a known-good data-sync cable, directly, or via an adapter if needed.

Double-click the reset button (highlighted in red above), and you will see the RGB status LED(s) turn green (highlighted in green above). If you see red, try another port, or if you're using an adapter or hub, try without the hub, or different adapter or hub.

If double-clicking doesn't work the first time, try again. Sometimes it can take a few tries to get the rhythm right!

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

You will see a new disk drive appear called GLASSESBOOT.

 

Drag the adafruit_circuitpython_etc.uf2 file to GLASSESBOOT.

The BOOT drive will disappear and a new disk drive called CIRCUITPY will appear.

That's it!

Mu is a simple code editor that works with the Adafruit CircuitPython boards. It's written in Python and works on Windows, MacOS, Linux and Raspberry Pi. The serial console is built right in so you get immediate feedback from your board's serial output!

Mu is our recommended editor - please use it (unless you are an experienced coder with a favorite editor already!).

Download and Install Mu

Download Mu from https://codewith.mu.

Click the Download link for downloads and installation instructions.

Click Start Here to find a wealth of other information, including extensive tutorials and and how-to's.

 

Windows users: due to the nature of MSI installers, please remove old versions of Mu before installing the latest version.

Starting Up Mu

The first time you start Mu, you will be prompted to select your 'mode' - you can always change your mind later. For now please select CircuitPython!

The current mode is displayed in the lower right corner of the window, next to the "gear" icon. If the mode says "Microbit" or something else, click the Mode button in the upper left, and then choose "CircuitPython" in the dialog box that appears.

Mu attempts to auto-detect your board on startup, so if you do not have a CircuitPython board plugged in with a CIRCUITPY drive available, Mu will inform you where it will store any code you save until you plug in a board.

To avoid this warning, plug in a board and ensure that the CIRCUITPY drive is mounted before starting Mu.

Using Mu

You can now explore Mu! The three main sections of the window are labeled below; the button bar, the text editor, and the serial console / REPL.

Now you're ready to code! Let's keep going...

One of the best things about CircuitPython is how simple it is to get code up and running. This section covers how to create and edit your first CircuitPython program.

To create and edit code, all you'll need is an editor. There are many options. Adafruit strongly recommends using Mu! It's designed for CircuitPython, and it's really simple and easy to use, with a built in serial console!

If you don't or can't use Mu, there are a number of other editors that work quite well. The Recommended Editors page has more details. Otherwise, make sure you do "Eject" or "Safe Remove" on Windows or "sync" on Linux after writing a file if you aren't using Mu. (This was formerly not a problem on macOS, but see the warning below.)

macOS Sonoma (14.x) introduced a bug that delays writes to small drives such as CIRCUITPY drives. This causes errors when saving files to CIRCUITPY. For a workaround, see https://learn.adafruit.com/welcome-to-circuitpython/troubleshooting#macos-sonoma-14-dot-x-disk-errors-writing-to-circuitpy-3160304

Creating Code

Installing CircuitPython generates a code.py file on your CIRCUITPY drive. To begin your own program, open your editor, and load the code.py file from the CIRCUITPY drive.

If you are using Mu, click the Load button in the button bar, navigate to the CIRCUITPY drive, and choose code.py.

Copy and paste the following code into your editor:

import board
import digitalio
import time

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

while True:
    led.value = True
    time.sleep(0.5)
    led.value = False
    time.sleep(0.5)
The KB2040, QT Py and the Trinkeys do not have a built-in little red LED! There is an addressable RGB NeoPixel LED. The above example will NOT work on the KB2040, QT Py or the Trinkeys!

If you're using a KB2040, QT Py or a Trinkey, please download the NeoPixel blink example.

The NeoPixel blink example uses the onboard NeoPixel, but the time code is the same. You can use the linked NeoPixel Blink example to follow along with this guide page.

It will look like this. Note that under the while True: line, the next four lines begin with four spaces to indent them, and they're indented exactly the same amount. All the lines before that have no spaces before the text.

Save the code.py file on your CIRCUITPY drive.

The little LED should now be blinking. Once per half-second.

Congratulations, you've just run your first CircuitPython program!

On most boards you'll find a tiny red LED. On the ItsyBitsy nRF52840, you'll find a tiny blue LED. On QT Py M0, QT Py RP2040, and the Trinkey series, you will find only an RGB NeoPixel LED.

Editing Code

To edit code, open the code.py file on your CIRCUITPY drive into your editor.

 

Make the desired changes to your code. Save the file. That's it!

Your code changes are run as soon as the file is done saving.

There's one warning before you continue...

Don't click reset or unplug your board!

The CircuitPython code on your board detects when the files are changed or written and will automatically re-start your code. This makes coding very fast because you save, and it re-runs. If you unplug or reset the board before your computer finishes writing the file to your board, you can corrupt the drive. If this happens, you may lose the code you've written, so it's important to backup your code to your computer regularly.

There are a couple of ways to avoid filesystem corruption.

1. Use an editor that writes out the file completely when you save it.

Check out the Recommended Editors page for details on different editing options.

If you are dragging a file from your host computer onto the CIRCUITPY drive, you still need to do step 2. Eject or Sync (below) to make sure the file is completely written.

2. Eject or Sync the Drive After Writing

If you are using one of our not-recommended-editors, not all is lost! You can still make it work.

On Windows, you can Eject or Safe Remove the CIRCUITPY drive. It won't actually eject, but it will force the operating system to save your file to disk. On Linux, use the sync command in a terminal to force the write to disk.

You also need to do this if you use Windows Explorer or a Linux graphical file manager to drag a file onto CIRCUITPY.

Oh No I Did Something Wrong and Now The CIRCUITPY Drive Doesn't Show Up!!!

Don't worry! Corrupting the drive isn't the end of the world (or your board!). If this happens, follow the steps found on the Troubleshooting page of every board guide to get your board up and running again.

Back to Editing Code...

Now! Let's try editing the program you added to your board. Open your code.py file into your editor. You'll make a simple change. Change the first 0.5 to 0.1. The code should look like this:

import board
import digitalio
import time

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

while True:
    led.value = True
    time.sleep(0.1)
    led.value = False
    time.sleep(0.5)

Leave the rest of the code as-is. Save your file. See what happens to the LED on your board? Something changed! Do you know why?

You don't have to stop there! Let's keep going. Change the second 0.5 to 0.1 so it looks like this:

while True:
    led.value = True
    time.sleep(0.1)
    led.value = False
    time.sleep(0.1)

Now it blinks really fast! You decreased the both time that the code leaves the LED on and off!

Now try increasing both of the 0.1 to 1. Your LED will blink much more slowly because you've increased the amount of time that the LED is turned on and off.

Well done! You're doing great! You're ready to start into new examples and edit them to see what happens! These were simple changes, but major changes are done using the same process. Make your desired change, save it, and get the results. That's really all there is to it!

Naming Your Program File

CircuitPython looks for a code file on the board to run. There are four options: code.txt, code.py, main.txt and main.py. CircuitPython looks for those files, in that order, and then runs the first one it finds. While code.py is the recommended name for your code file, it is important to know that the other options exist. If your program doesn't seem to be updating as you work, make sure you haven't created another code file that's being read instead of the one you're working on.

One of the staples of CircuitPython (and programming in general!) is something called a "print statement". This is a line you include in your code that causes your code to output text. A print statement in CircuitPython (and Python) looks like this:

print("Hello, world!")

This line in your code.py would result in:

Hello, world!

However, these print statements need somewhere to display. That's where the serial console comes in!

The serial console receives output from your CircuitPython board sent over USB and displays it so you can see it. This is necessary when you've included a print statement in your code and you'd like to see what you printed. It is also helpful for troubleshooting errors, because your board will send errors and the serial console will display those too.

The serial console requires an editor that has a built in terminal, or a separate terminal program. A terminal is a program that gives you a text-based interface to perform various tasks.

Are you using Mu?

If so, good news! The serial console is built into Mu and will autodetect your board making using the serial console really really easy.

First, make sure your CircuitPython board is plugged in.

If you open Mu without a board plugged in, you may encounter the error seen here, letting you know no CircuitPython board was found and indicating where your code will be stored until you plug in a board.

If you are using Windows 7, make sure you installed the drivers.

Once you've opened Mu with your board plugged in, look for the Serial button in the button bar and click it.

The Mu window will split in two, horizontally, and display the serial console at the bottom.

If nothing appears in the serial console, it may mean your code is done running or has no print statements in it. Click into the serial console part of Mu, and press CTRL+D to reload.

Serial Console Issues or Delays on Linux

If you're on Linux, and are seeing multi-second delays connecting to the serial console, or are seeing "AT" and other gibberish when you connect, then the modemmanager service might be interfering. Just remove it; it doesn't have much use unless you're still using dial-up modems.

To remove modemmanager, type the following command at a shell:

sudo apt purge modemmanager

Setting Permissions on Linux

On Linux, if you see an error box something like the one below when you press the Serial button, you need to add yourself to a user group to have permission to connect to the serial console.

On Ubuntu and Debian, add yourself to the dialout group by doing:

sudo adduser $USER dialout

After running the command above, reboot your machine to gain access to the group. On other Linux distributions, the group you need may be different. See the Advanced Serial Console on Linux for details on how to add yourself to the right group.

Using Something Else?

If you're not using Mu to edit, are using or if for some reason you are not a fan of its built in serial console, you can run the serial console from a separate program.

Windows requires you to download a terminal program. Check out the Advanced Serial Console on Windows page for more details.

MacOS has Terminal built in, though there are other options available for download. Check the Advanced Serial Console on Mac page for more details.

Linux has a terminal program built in, though other options are available for download. Check the Advanced Serial Console on Linux page for more details.

Once connected, you'll see something like the following.

Once you've successfully connected to the serial console, it's time to start using it.

The code you wrote earlier has no output to the serial console. So, you're going to edit it to create some output.

Open your code.py file into your editor, and include a print statement. You can print anything you like! Just include your phrase between the quotation marks inside the parentheses. For example:

import board
import digitalio
import time

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

while True:
    print("Hello, CircuitPython!")
    led.value = True
    time.sleep(1)
    led.value = False
    time.sleep(1)

Save your file.

Now, let's go take a look at the window with our connection to the serial console.

Excellent! Our print statement is showing up in our console! Try changing the printed text to something else.

import board
import digitalio
import time

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

while True:
    print("Hello back to you!")
    led.value = True
    time.sleep(1)
    led.value = False
    time.sleep(1)

Keep your serial console window where you can see it. Save your file. You'll see what the serial console displays when the board reboots. Then you'll see your new change!

The Traceback (most recent call last): is telling you the last thing your board was doing before you saved your file. This is normal behavior and will happen every time the board resets. This is really handy for troubleshooting. Let's introduce an error so you can see how it is used.

Delete the e at the end of True from the line led.value = True so that it says led.value = Tru

import board
import digitalio
import time

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

while True:
    print("Hello back to you!")
    led.value = Tru
    time.sleep(1)
    led.value = False
    time.sleep(1)

Save your file. You will notice that your red LED will stop blinking, and you may have a colored status LED blinking at you. This is because the code is no longer correct and can no longer run properly. You need to fix it!

Usually when you run into errors, it's not because you introduced them on purpose. You may have 200 lines of code, and have no idea where your error could be hiding. This is where the serial console can help. Let's take a look!

The Traceback (most recent call last): is telling you that the last thing it was able to run was line 10 in your code. The next line is your error: NameError: name 'Tru' is not defined. This error might not mean a lot to you, but combined with knowing the issue is on line 10, it gives you a great place to start!

Go back to your code, and take a look at line 10. Obviously, you know what the problem is already. But if you didn't, you'd want to look at line 10 and see if you could figure it out. If you're still unsure, try googling the error to get some help. In this case, you know what to look for. You spelled True wrong. Fix the typo and save your file.

Nice job fixing the error! Your serial console is streaming and your red LED Is blinking again.

The serial console will display any output generated by your code. Some sensors, such as a humidity sensor or a thermistor, receive data and you can use print statements to display that information. You can also use print statements for troubleshooting, which is called "print debugging". Essentially, if your code isn't working, and you want to know where it's failing, you can put print statements in various places to see where it stops printing.

The serial console has many uses, and is an amazing tool overall for learning and programming!

The other feature of the serial connection is the Read-Evaluate-Print-Loop, or REPL. The REPL allows you to enter individual lines of code and have them run immediately. It's really handy if you're running into trouble with a particular program and can't figure out why. It's interactive so it's great for testing new ideas.

Entering the REPL

To use the REPL, you first need to be connected to the serial console. Once that connection has been established, you'll want to press CTRL+C.

If there is code running, in this case code measuring distance, it will stop and you'll see Press any key to enter the REPL. Use CTRL-D to reload. Follow those instructions, and press any key on your keyboard.

The Traceback (most recent call last): is telling you the last thing your board was doing before you pressed Ctrl + C and interrupted it. The KeyboardInterrupt is you pressing CTRL+C. This information can be handy when troubleshooting, but for now, don't worry about it. Just note that it is expected behavior.

If your code.py file is empty or does not contain a loop, it will show an empty output and Code done running.. There is no information about what your board was doing before you interrupted it because there is no code running.

If you have no code.py on your CIRCUITPY drive, you will enter the REPL immediately after pressing CTRL+C. Again, there is no information about what your board was doing before you interrupted it because there is no code running.

Regardless, once you press a key you'll see a >>> prompt welcoming you to the REPL!

If you have trouble getting to the >>> prompt, try pressing Ctrl + C a few more times.

The first thing you get from the REPL is information about your board.

This line tells you the version of CircuitPython you're using and when it was released. Next, it gives you the type of board you're using and the type of microcontroller the board uses. Each part of this may be different for your board depending on the versions you're working with.

This is followed by the CircuitPython prompt.

Interacting with the REPL

From this prompt you can run all sorts of commands and code. The first thing you'll do is run help(). This will tell you where to start exploring the REPL. To run code in the REPL, type it in next to the REPL prompt.

Type help() next to the prompt in the REPL.

Then press enter. You should then see a message.

First part of the message is another reference to the version of CircuitPython you're using. Second, a URL for the CircuitPython related project guides. Then... wait. What's this? To list built-in modules type `help("modules")`. Remember the modules you learned about while going through creating code? That's exactly what this is talking about! This is a perfect place to start. Let's take a look!

Type help("modules") into the REPL next to the prompt, and press enter.

This is a list of all the core modules built into CircuitPython, including board. Remember, board contains all of the pins on the board that you can use in your code. From the REPL, you are able to see that list!

Type import board into the REPL and press enter. It'll go to a new prompt. It might look like nothing happened, but that's not the case! If you recall, the import statement simply tells the code to expect to do something with that module. In this case, it's telling the REPL that you plan to do something with that module.

Next, type dir(board) into the REPL and press enter.

This is a list of all of the pins on your board that are available for you to use in your code. Each board's list will differ slightly depending on the number of pins available. Do you see LED? That's the pin you used to blink the red LED!

The REPL can also be used to run code. Be aware that any code you enter into the REPL isn't saved anywhere. If you're testing something new that you'd like to keep, make sure you have it saved somewhere on your computer as well!

Every programmer in every programming language starts with a piece of code that says, "Hello, World." You're going to say hello to something else. Type into the REPL:

print("Hello, CircuitPython!")

Then press enter.

That's all there is to running code in the REPL! Nice job!

You can write single lines of code that run stand-alone. You can also write entire programs into the REPL to test them. Remember that nothing typed into the REPL is saved.

There's a lot the REPL can do for you. It's great for testing new ideas if you want to see if a few new lines of code will work. It's fantastic for troubleshooting code by entering it one line at a time and finding out where it fails. It lets you see what modules are available and explore those modules.

Try typing more into the REPL to see what happens!

Everything typed into the REPL is ephemeral. Once you reload the REPL or return to the serial console, nothing you typed will be retained in any memory space. So be sure to save any desired code you wrote somewhere else, or you'll lose it when you leave the current REPL instance!

Returning to the Serial Console

When you're ready to leave the REPL and return to the serial console, simply press CTRL+D. This will reload your board and reenter the serial console. You will restart the program you had running before entering the REPL. In the console window, you'll see any output from the program you had running. And if your program was affecting anything visual on the board, you'll see that start up again as well.

You can return to the REPL at any time!

As CircuitPython development continues and there are new releases, Adafruit will stop supporting older releases. Visit https://circuitpython.org/downloads to download the latest version of CircuitPython for your board. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update CircuitPython and then visit https://circuitpython.org/libraries to download the latest Library Bundle.

Each CircuitPython program you run needs to have a lot of information to work. The reason CircuitPython is so simple to use is that most of that information is stored in other files and works in the background. These files are called libraries. Some of them are built into CircuitPython. Others are stored on your CIRCUITPY drive in a folder called lib. Part of what makes CircuitPython so great is its ability to store code separately from the firmware itself. Storing code separately from the firmware makes it easier to update both the code you write and the libraries you depend.

Your board may ship with a lib folder already, it's in the base directory of the drive. If not, simply create the folder yourself. When you first install CircuitPython, an empty lib directory will be created for you.

CircuitPython libraries work in the same way as regular Python modules so the Python docs are an excellent reference for how it all should work. In Python terms, you can place our library files in the lib directory because it's part of the Python path by default.

One downside of this approach of separate libraries is that they are not built in. To use them, one needs to copy them to the CIRCUITPY drive before they can be used. Fortunately, there is a library bundle.

The bundle and the library releases on GitHub also feature optimized versions of the libraries with the .mpy file extension. These files take less space on the drive and have a smaller memory footprint as they are loaded.

Due to the regular updates and space constraints, Adafruit does not ship boards with the entire bundle. Therefore, you will need to load the libraries you need when you begin working with your board. You can find example code in the guides for your board that depends on external libraries.

Either way, as you start to explore CircuitPython, you'll want to know how to get libraries on board.

The Adafruit Learn Guide Project Bundle

The quickest and easiest way to get going with a project from the Adafruit Learn System is by utilising the Project Bundle. Most guides now have a Download Project Bundle button available at the top of the full code example embed. This button downloads all the necessary files, including images, etc., to get the guide project up and running. Simply click, open the resulting zip, copy over the right files, and you're good to go!

The first step is to find the Download Project Bundle button in the guide you're working on.

The Download Project Bundle button is only available on full demo code embedded from GitHub in a Learn guide. Code snippets will NOT have the button available.
When you copy the contents of the Project Bundle to your CIRCUITPY drive, it will replace all the existing content! If you don't want to lose anything, ensure you copy your current code to your computer before you copy over the new Project Bundle content!

The Download Project Bundle button downloads a zip file. This zip contains a series of directories, nested within which is the code.py, any applicable assets like images or audio, and the lib/ folder containing all the necessary libraries. The following zip was downloaded from the Piano in the Key of Lime guide.

The Piano in the Key of Lime guide was chosen as an example. That guide is specific to Circuit Playground Express, and cannot be used on all boards. Do not expect to download that exact bundle and have it work on your non-CPX microcontroller.

When you open the zip, you'll find some nested directories. Navigate through them until you find what you need. You'll eventually find a directory for your CircuitPython version (in this case, 7.x). In the version directory, you'll find the file and directory you need: code.py and lib/. Once you find the content you need, you can copy it all over to your CIRCUITPY drive, replacing any files already on the drive with the files from the freshly downloaded zip.

In some cases, there will be other files such as audio or images in the same directory as code.py and lib/. Make sure you include all the files when you copy things over!

Once you copy over all the relevant files, the project should begin running! If you find that the project is not running as expected, make sure you've copied ALL of the project files onto your microcontroller board.

That's all there is to using the Project Bundle!

The Adafruit CircuitPython Library Bundle

Adafruit provides CircuitPython libraries for much of the hardware they provide, including sensors, breakouts and more. To eliminate the need for searching for each library individually, the libraries are available together in the Adafruit CircuitPython Library Bundle. The bundle contains all the files needed to use each library.

Downloading the Adafruit CircuitPython Library Bundle

You can download the latest Adafruit CircuitPython Library Bundle release by clicking the button below. The libraries are being constantly updated and improved, so you'll always want to download the latest bundle. 

Match up the bundle version with the version of CircuitPython you are running. For example, you would download the 6.x library bundle if you're running any version of CircuitPython 6, or the 7.x library bundle if you're running any version of CircuitPython 7, etc. If you mix libraries with major CircuitPython versions, you will get incompatible mpy errors due to changes in library interfaces possible during major version changes.

Download the bundle version that matches your CircuitPython firmware version. If you don't know the version, check the version info in boot_out.txt file on the CIRCUITPY drive, or the initial prompt in the CircuitPython REPL. For example, if you're running v7.0.0, download the 7.x library bundle.

There's also a py bundle which contains the uncompressed python files, you probably don't want that unless you are doing advanced work on libraries.

The CircuitPython Community Library Bundle

The CircuitPython Community Library Bundle is made up of libraries written and provided by members of the CircuitPython community. These libraries are often written when community members encountered hardware not supported in the Adafruit Bundle, or to support a personal project. The authors all chose to submit these libraries to the Community Bundle make them available to the community.

These libraries are maintained by their authors and are not supported by Adafruit. As you would with any library, if you run into problems, feel free to file an issue on the GitHub repo for the library. Bear in mind, though, that most of these libraries are supported by a single person and you should be patient about receiving a response. Remember, these folks are not paid by Adafruit, and are volunteering their personal time when possible to provide support.

Downloading the CircuitPython Community Library Bundle

You can download the latest CircuitPython Community Library Bundle release by clicking the button below. The libraries are being constantly updated and improved, so you'll always want to download the latest bundle.

The link takes you to the latest release of the CircuitPython Community Library Bundle on GitHub. There are multiple versions of the bundle available. Download the bundle version that matches your CircuitPython firmware version. If you don't know the version, check the version info in boot_out.txt file on the CIRCUITPY drive, or the initial prompt in the CircuitPython REPL. For example, if you're running v7.0.0, download the 7.x library bundle.

Understanding the Bundle

After downloading the zip, extract its contents. This is usually done by double clicking on the zip. On Mac OSX, it places the file in the same directory as the zip.

Open the bundle folder. Inside you'll find two information files, and two folders. One folder is the lib bundle, and the other folder is the examples bundle.

Now open the lib folder. When you open the folder, you'll see a large number of .mpy files, and folders.

Example Files

All example files from each library are now included in the bundles in an examples directory (as seen above), as well as an examples-only bundle. These are included for two main reasons:

  • Allow for quick testing of devices.
  • Provide an example base of code, that is easily built upon for individualized purposes.

Copying Libraries to Your Board

First open the lib folder on your CIRCUITPY drive. Then, open the lib folder you extracted from the downloaded zip. Inside you'll find a number of folders and .mpy files. Find the library you'd like to use, and copy it to the lib folder on CIRCUITPY.

If the library is a directory with multiple .mpy files in it, be sure to copy the entire folder to CIRCUITPY/lib.

This also applies to example files. Open the examples folder you extracted from the downloaded zip, and copy the applicable file to your CIRCUITPY drive. Then, rename it to code.py to run it.

If a library has multiple .mpy files contained in a folder, be sure to copy the entire folder to CIRCUITPY/lib.

Understanding Which Libraries to Install

You now know how to load libraries on to your CircuitPython-compatible microcontroller board. You may now be wondering, how do you know which libraries you need to install? Unfortunately, it's not always straightforward. Fortunately, there is an obvious place to start, and a relatively simple way to figure out the rest. First up: the best place to start.

When you look at most CircuitPython examples, you'll see they begin with one or more import statements. These typically look like the following:

  • import library_or_module

However, import statements can also sometimes look like the following:

  • from library_or_module import name
  • from library_or_module.subpackage import name
  • from library_or_module import name as local_name

They can also have more complicated formats, such as including a try / except block, etc.

The important thing to know is that an import statement will always include the name of the module or library that you're importing.

Therefore, the best place to start is by reading through the import statements.

Here is an example import list for you to work with in this section. There is no setup or other code shown here, as the purpose of this section involves only the import list.

import time
import board
import neopixel
import adafruit_lis3dh
import usb_hid
from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode

Keep in mind, not all imported items are libraries. Some of them are almost always built-in CircuitPython modules. How do you know the difference? Time to visit the REPL.

In the Interacting with the REPL section on The REPL page in this guide, the help("modules") command is discussed. This command provides a list of all of the built-in modules available in CircuitPython for your board. So, if you connect to the serial console on your board, and enter the REPL, you can run help("modules") to see what modules are available for your board. Then, as you read through the import statements, you can, for the purposes of figuring out which libraries to load, ignore the statement that import modules.

The following is the list of modules built into CircuitPython for the Feather RP2040. Your list may look similar or be anything down to a significant subset of this list for smaller boards.

Now that you know what you're looking for, it's time to read through the import statements. The first two, time and board, are on the modules list above, so they're built-in.

The next one, neopixel, is not on the module list. That means it's your first library! So, you would head over to the bundle zip you downloaded, and search for neopixel. There is a neopixel.mpy file in the bundle zip. Copy it over to the lib folder on your CIRCUITPY drive. The following one, adafruit_lis3dh, is also not on the module list. Follow the same process for adafruit_lis3dh, where you'll find adafruit_lis3dh.mpy, and copy that over.

The fifth one is usb_hid, and it is in the modules list, so it is built in. Often all of the built-in modules come first in the import list, but sometimes they don't! Don't assume that everything after the first library is also a library, and verify each import with the modules list to be sure. Otherwise, you'll search the bundle and come up empty!

The final two imports are not as clear. Remember, when import statements are formatted like this, the first thing after the from is the library name. In this case, the library name is adafruit_hid. A search of the bundle will find an adafruit_hid folder. When a library is a folder, you must copy the entire folder and its contents as it is in the bundle to the lib folder on your CIRCUITPY drive. In this case, you would copy the entire adafruit_hid folder to your CIRCUITPY/lib folder.

Notice that there are two imports that begin with adafruit_hid. Sometimes you will need to import more than one thing from the same library. Regardless of how many times you import the same library, you only need to load the library by copying over the adafruit_hid folder once.

That is how you can use your example code to figure out what libraries to load on your CircuitPython-compatible board!

There are cases, however, where libraries require other libraries internally. The internally required library is called a dependency. In the event of library dependencies, the easiest way to figure out what other libraries are required is to connect to the serial console and follow along with the ImportError printed there. The following is a very simple example of an ImportError, but the concept is the same for any missing library.

Example: ImportError Due to Missing Library

If you choose to load libraries as you need them, or you're starting fresh with an existing example, you may end up with code that tries to use a library you haven't yet loaded.  This section will demonstrate what happens when you try to utilise a library that you don't have loaded on your board, and cover the steps required to resolve the issue.

This demonstration will only return an error if you do not have the required library loaded into the lib folder on your CIRCUITPY drive.

Let's use a modified version of the Blink example.

import board
import time
import simpleio

led = simpleio.DigitalOut(board.LED)

while True:
    led.value = True
    time.sleep(0.5)
    led.value = False
    time.sleep(0.5)

Save this file. Nothing happens to your board. Let's check the serial console to see what's going on.

You have an ImportError. It says there is no module named 'simpleio'. That's the one you just included in your code!

Click the link above to download the correct bundle. Extract the lib folder from the downloaded bundle file. Scroll down to find simpleio.mpy. This is the library file you're looking for! Follow the steps above to load an individual library file.

The LED starts blinking again! Let's check the serial console.

No errors! Excellent. You've successfully resolved an ImportError!

If you run into this error in the future, follow along with the steps above and choose the library that matches the one you're missing.

Library Install on Non-Express Boards

If you have an M0 non-Express board such as Trinket M0, Gemma M0, QT Py M0, or one of the M0 Trinkeys, you'll want to follow the same steps in the example above to install libraries as you need them. Remember, you don't need to wait for an ImportError if you know what library you added to your code. Open the library bundle you downloaded, find the library you need, and drag it to the lib folder on your CIRCUITPY drive.

You can still end up running out of space on your M0 non-Express board even if you only load libraries as you need them. There are a number of steps you can use to try to resolve this issue. You'll find suggestions on the Troubleshooting page.

Updating CircuitPython Libraries and Examples

Libraries and examples are updated from time to time, and it's important to update the files you have on your CIRCUITPY drive.

To update a single library or example, follow the same steps above. When you drag the library file to your lib folder, it will ask if you want to replace it. Say yes. That's it!

A new library bundle is released every time there's an update to a library. Updates include things like bug fixes and new features. It's important to check in every so often to see if the libraries you're using have been updated.

CircUp CLI Tool

There is a command line interface (CLI) utility called CircUp that can be used to easily install and update libraries on your device. Follow the directions on the install page within the CircUp learn guide. Once you've got it installed you run the command circup update in a terminal to interactively update all libraries on the connected CircuitPython device. See the usage page in the CircUp guide for a full list of functionality

These are some of the common questions regarding CircuitPython and CircuitPython microcontrollers.

What are some common acronyms to know?

Using Older Versions

As CircuitPython development continues and there are new releases, Adafruit will stop supporting older releases. Visit https://circuitpython.org/downloads to download the latest version of CircuitPython for your board. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update CircuitPython and then visit https://circuitpython.org/libraries to download the latest Library Bundle.
I have to continue using CircuitPython 7.x or earlier. Where can I find compatible libraries?

We are no longer building or supporting the CircuitPython 7.x or earlier library bundles. We highly encourage you to update CircuitPython to the latest version and use the current version of the libraries. However, if for some reason you cannot update, here are the last available library bundles for older versions:

Python Arithmetic

Does CircuitPython support floating-point numbers?

All CircuitPython boards support floating point arithmetic, even if the microcontroller chip does not support floating point in hardware. Floating point numbers are stored in 30 bits, with an 8-bit exponent and a 22-bit mantissa. Note that this is two bits less than standard 32-bit single-precision floats. You will get about 5-1/2 digits of decimal precision. 

(The broadcom port may provide 64-bit floats in some cases.)

Does CircuitPython support long integers, like regular Python?

Python long integers (integers of arbitrary size) are available on most builds, except those on boards with the smallest available firmware size. On these boards, integers are stored in 31 bits.

Boards without long integer support are mostly SAMD21 ("M0") boards without an external flash chip, such as the Adafruit Gemma M0, Trinket M0, QT Py M0, and the Trinkey series. There are also a number of third-party boards in this category. There are also a few small STM third-party boards without long integer support.

time.localtime(), time.mktime(), time.time(), and time.monotonic_ns() are available only on builds with long integers.

Wireless Connectivity

How do I connect to the Internet with CircuitPython?

If you'd like to include WiFi in  your project, your best bet is to use a board that is running natively on ESP32 chipsets - those have WiFi built in!

If your development board has an SPI port and at least 4 additional pins, you can check out this guide on using AirLift with CircuitPython - extra wiring is required and some boards like the MacroPad or NeoTrellis do not have enough available pins to add the hardware support.

For further project examples, and guides about using AirLift with specific hardware, check out the Adafruit Learn System.

How do I do BLE (Bluetooth Low Energy) with CircuitPython?

The nRF52840 and nRF52833 boards have the most complete BLE implementation. Your program can act as both a BLE central and peripheral. As a central, you can scan for advertisements, and connect to an advertising board. As a peripheral, you can advertise, and you can create services available to a central. Pairing and bonding are supported.

ESP32-C3 and ESP32-S3 boards currently provide an incomplete BLE implementation. Your program can act as a central, and connect to a peripheral. You can advertise, but you cannot create services. You cannot advertise anonymously. Pairing and bonding are not supported.

The ESP32 could provide a similar implementation, but it is not yet available. Note that the ESP32-S2 does not have Bluetooth capability.

On most other boards with adequate firmware space, BLE is available for use with AirLift or other NINA-FW-based co-processors. Some boards have this coprocessor on board, such as the PyPortal. Currently, this implementation only supports acting as a BLE peripheral. Scanning and connecting as a central are not yet implemented. Bonding and pairing are not supported.

Are there other ways to communicate by radio with CircuitPython?

Check out Adafruit's RFM boards for simple radio communication supported by CircuitPython, which can be used over distances of 100m to over a km, depending on the version. The RFM SAMD21 M0 boards can be used, but they were not designed for CircuitPython, and have limited RAM and flash space; using the RFM breakouts or FeatherWings with more capable boards will be easier.

Asyncio and Interrupts

Is there asyncio support in CircuitPython?

There is support for asyncio starting with CircuitPython 7.1.0, on all boards except the smallest SAMD21 builds. Read about using it in the Cooperative Multitasking in CircuitPython Guide.

Does CircuitPython support interrupts?

No. CircuitPython does not currently support interrupts - please use asyncio for multitasking / 'threaded' control of your code

Status RGB LED

My RGB NeoPixel/DotStar LED is blinking funny colors - what does it mean?

The status LED can tell you what's going on with your CircuitPython board. Read more here for what the colors mean!

Memory Issues

What is a MemoryError?

Memory allocation errors happen when you're trying to store too much on the board. The CircuitPython microcontroller boards have a limited amount of memory available. You can have about 250 lines of code on the M0 Express boards. If you try to import too many libraries, a combination of large libraries, or run a program with too many lines of code, your code will fail to run and you will receive a MemoryError in the serial console.

What do I do when I encounter a MemoryError?

Try resetting your board. Each time you reset the board, it reallocates the memory. While this is unlikely to resolve your issue, it's a simple step and is worth trying.

Make sure you are using .mpy versions of libraries. All of the CircuitPython libraries are available in the bundle in a .mpy format which takes up less memory than .py format. Be sure that you're using the latest library bundle for your version of CircuitPython.

If that does not resolve your issue, try shortening your code. Shorten comments, remove extraneous or unneeded code, or any other clean up you can do to shorten your code. If you're using a lot of functions, you could try moving those into a separate library, creating a .mpy of that library, and importing it into your code.

You can turn your entire file into a .mpy and import that into code.py. This means you will be unable to edit your code live on the board, but it can save you space.

Can the order of my import statements affect memory?

It can because the memory gets fragmented differently depending on allocation order and the size of objects. Loading .mpy files uses less memory so its recommended to do that for files you aren't editing.

How can I create my own .mpy files?

You can make your own .mpy versions of files with mpy-cross.

You can download mpy-cross for your operating system from here. Builds are available for Windows, macOS, x64 Linux, and Raspberry Pi Linux. Choose the latest mpy-cross whose version matches the version of CircuitPython you are using.

To make a .mpy file, run ./mpy-cross path/to/yourfile.py to create a yourfile.mpy in the same directory as the original file.

How do I check how much memory I have free?

Run the following to see the number of bytes available for use:

import gc
gc.mem_free()

Unsupported Hardware

Is ESP8266 or ESP32 supported in CircuitPython? Why not?

We dropped ESP8266 support as of 4.x - For more information please read about it here!

As of CircuitPython 8.x we have started to support ESP32 and ESP32-C3 and have added a WiFi workflow for wireless coding!

We also support ESP32-S2 & ESP32-S3, which have native USB.

Does Feather M0 support WINC1500?

No, WINC1500 will not fit into the M0 flash space.

Can AVRs such as ATmega328 or ATmega2560 run CircuitPython?

No.

From time to time, you will run into issues when working with CircuitPython. Here are a few things you may encounter and how to resolve them.

As CircuitPython development continues and there are new releases, Adafruit will stop supporting older releases. Visit https://circuitpython.org/downloads to download the latest version of CircuitPython for your board. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update CircuitPython and then visit https://circuitpython.org/libraries to download the latest Library Bundle.

Always Run the Latest Version of CircuitPython and Libraries

As CircuitPython development continues and there are new releases, Adafruit will stop supporting older releases. You need to update to the latest CircuitPython..

You need to download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update CircuitPython and then download the latest bundle.

As new versions of CircuitPython are released, Adafruit will stop providing the previous bundles as automatically created downloads on the Adafruit CircuitPython Library Bundle repo. If you must continue to use an earlier version, you can still download the appropriate version of mpy-cross from the particular release of CircuitPython on the CircuitPython repo and create your own compatible .mpy library files. However, it is best to update to the latest for both CircuitPython and the library bundle.

I have to continue using CircuitPython 7.x or earlier. Where can I find compatible libraries?

Adafruit is no longer building or supporting the CircuitPython 7.x or earlier library bundles. You are highly encourged to update CircuitPython to the latest version and use the current version of the libraries. However, if for some reason you cannot update, links to the previous bundles are available in the FAQ.

macOS Sonoma 14.x: Disk Errors Writing to CIRCUITPY

macOS Sonoma takes many seconds to complete writes to small FAT drives, 8MB or smaller. This causes errors when writing to CIRCUITPY. The best solution is to remount the CIRCUITPY drive after it is automatically mounted. Or consider downgrading back to Ventura if that works for you.

Here is a shell script to do this remount conveniently (courtesy @czei in GitHub). Copy the code here into a file named, say, remount-CIRCUITPY.sh. Place the file in a directory on your PATH, or in some other convenient place.

#!/bin/csh
#
# This works around bug where, by default, macOS 14.x writes part of a file 
# immediately, and then doesn't update the directory for 20-60 seconds, causing
# the file system to be corrupted.
#

set disky=`df | grep CIRCUITPY | cut -d" " -f1`
sudo umount /Volumes/CIRCUITPY
sudo mkdir /Volumes/CIRCUITPY
sleep 2
sudo mount -v -o noasync -t msdos $disky /Volumes/CIRCUITPY

Then in a Terminal window, do this to make this script executable:

chmod +x remount-CIRCUITPY.sh

Place the file in a directory on your PATH, or in some other convenient place.

Now, each time you plug in or reset your CIRCUITPY board, run the file remount-CIRCUITPY.sh. You can run it in a Terminal window or you may be able to place it on the desktop or in your dock to run it just by double-clicking.

This will be something of a nuisance but it is the safest solution.

This problem is being tracked in this CircuitPython issue.

Bootloader (boardnameBOOT) Drive Not Present

You may have a different board.

Only Adafruit Express boards and the SAMD21 non-Express boards ship with the UF2 bootloader installed. The Feather M0 Basic, Feather M0 Adalogger, and similar boards use a regular Arduino-compatible bootloader, which does not show a boardnameBOOT drive.

MakeCode

If you are running a MakeCode program on Circuit Playground Express, press the reset button just once to get the CPLAYBOOT drive to show up. Pressing it twice will not work.

macOS

DriveDx and its accompanything SAT SMART Driver can interfere with seeing the BOOT drive. See this forum post for how to fix the problem.

Windows 10

Did you install the Adafruit Windows Drivers package by mistake, or did you upgrade to Windows 10 with the driver package installed? You don't need to install this package on Windows 10 for most Adafruit boards. The old version (v1.5) can interfere with recognizing your device. Go to Settings -> Apps and uninstall all the "Adafruit" driver programs.

Windows 7 or 8.1

To use a CircuitPython-compatible board with Windows 7 or 8.1, you must install a driver. Installation instructions are available here.

Windows 7 and 8.1 have reached end of life. It is recommended that you upgrade to Windows 10 if possible; an upgrade is probably still free for you. Check here.

The Windows Drivers installer was last updated in November 2020 (v2.5.0.0) . Windows 7 drivers for CircuitPython boards released since then, including RP2040 boards, are not available. There are no plans to release drivers for new boards. The boards work fine on Windows 10.

You should now be done! Test by unplugging and replugging the board. You should see the CIRCUITPY drive, and when you double-click the reset button (single click on Circuit Playground Express running MakeCode), you should see the appropriate boardnameBOOT drive.

Let us know in the Adafruit support forums or on the Adafruit Discord if this does not work for you!

Windows Explorer Locks Up When Accessing boardnameBOOT Drive

On Windows, several third-party programs that can cause issues. The symptom is that you try to access the boardnameBOOT drive, and Windows or Windows Explorer seems to lock up. These programs are known to cause trouble:

  • AIDA64: to fix, stop the program. This problem has been reported to AIDA64. They acquired hardware to test, and released a beta version that fixes the problem. This may have been incorporated into the latest release. Please let us know in the forums if you test this.
  • Hard Disk Sentinel
  • Kaspersky anti-virus: To fix, you may need to disable Kaspersky completely. Disabling some aspects of Kaspersky does not always solve the problem. This problem has been reported to Kaspersky.
  • ESET NOD32 anti-virus: There have been problems with at least version 9.0.386.0, solved by uninstallation.

Copying UF2 to boardnameBOOT Drive Hangs at 0% Copied

On Windows, a Western DIgital (WD) utility that comes with their external USB drives can interfere with copying UF2 files to the boardnameBOOT drive. Uninstall that utility to fix the problem.

CIRCUITPY Drive Does Not Appear or Disappears Quickly

Kaspersky anti-virus can block the appearance of the CIRCUITPY drive. There has not yet been settings change discovered that prevents this. Complete uninstallation of Kaspersky fixes the problem.

Norton anti-virus can interfere with CIRCUITPY. A user has reported this problem on Windows 7. The user turned off both Smart Firewall and Auto Protect, and CIRCUITPY then appeared.

Sophos Endpoint security software can cause CIRCUITPY to disappear and the BOOT drive to reappear. It is not clear what causes this behavior.

Samsung Magician can cause CIRCUITPY to disappear (reported here and here).

Device Errors or Problems on Windows

Windows can become confused about USB device installations. This is particularly true of Windows 7 and 8.1. It is recommended that you upgrade to Windows 10 if possible; an upgrade is probably still free for you: see this link.

If not, try cleaning up your USB devices. Use Uwe Sieber's Device Cleanup Tool (on that page, scroll down to "Device Cleanup Tool"). Download and unzip the tool. Unplug all the boards and other USB devices you want to clean up. Run the tool as Administrator. You will see a listing like this, probably with many more devices. It is listing all the USB devices that are not currently attached.

Select all the devices you want to remove, and then press Delete. It is usually safe just to select everything. Any device that is removed will get a fresh install when you plug it in. Using the Device Cleanup Tool also discards all the COM port assignments for the unplugged boards. If you have used many Arduino and CircuitPython boards, you have probably seen higher and higher COM port numbers used, seemingly without end. This will fix that problem.

Serial Console in Mu Not Displaying Anything

There are times when the serial console will accurately not display anything, such as, when no code is currently running, or when code with no serial output is already running before you open the console. However, if you find yourself in a situation where you feel it should be displaying something like an error, consider the following.

Depending on the size of your screen or Mu window, when you open the serial console, the serial console panel may be very small. This can be a problem. A basic CircuitPython error takes 10 lines to display!

Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
Traceback (most recent call last):
  File "code.py", line 7
SyntaxError: invalid syntax



Press any key to enter the REPL. Use CTRL-D to reload.
 

More complex errors take even more lines!

Therefore, if your serial console panel is five lines tall or less, you may only see blank lines or blank lines followed by Press any key to enter the REPL. Use CTRL-D to reload.. If this is the case, you need to either mouse over the top of the panel to utilise the option to resize the serial panel, or use the scrollbar on the right side to scroll up and find your message.

This applies to any kind of serial output whether it be error messages or print statements. So before you start trying to debug your problem on the hardware side, be sure to check that you haven't simply missed the serial messages due to serial output panel height.

code.py Restarts Constantly

CircuitPython will restart code.py if you or your computer writes to something on the CIRCUITPY drive. This feature is called auto-reload, and lets you test a change to your program immediately.

Some utility programs, such as backup, anti-virus, or disk-checking apps, will write to the CIRCUITPY as part of their operation. Sometimes they do this very frequently, causing constant restarts.

Acronis True Image and related Acronis programs on Windows are known to cause this problem. It is possible to prevent this by disabling the "Acronis Managed Machine Service Mini".

If you cannot stop whatever is causing the writes, you can disable auto-reload by putting this code in boot.py or code.py:

import supervisor

supervisor.runtime.autoreload = False

CircuitPython RGB Status Light

Nearly all CircuitPython-capable boards have a single NeoPixel or DotStar RGB LED on the board that indicates the status of CircuitPython. A few boards designed before CircuitPython existed, such as the Feather M0 Basic, do not.

Circuit Playground Express and Circuit Playground Bluefruit have multiple RGB LEDs, but do NOT have a status LED. The LEDs are all green when in the bootloader. In versions before 7.0.0, they do NOT indicate any status while running CircuitPython.

CircuitPython 7.0.0 and Later

The status LED blinks were changed in CircuitPython 7.0.0 in order to save battery power and simplify the blinks. These blink patterns will occur on single color LEDs when the board does not have any RGB LEDs. Speed and blink count also vary for this reason.

On start up, the LED will blink YELLOW multiple times for 1 second. Pressing the RESET button (or on Espressif, the BOOT button) during this time will restart the board and then enter safe mode. On Bluetooth capable boards, after the yellow blinks, there will be a set of faster blue blinks. Pressing reset during the BLUE blinks will clear Bluetooth information and start the device in discoverable mode, so it can be used with a BLE code editor.

Once started, CircuitPython will blink a pattern every 5 seconds when no user code is running to indicate why the code stopped:

  • 1 GREEN blink: Code finished without error.
  • 2 RED blinks: Code ended due to an exception. Check the serial console for details.
  • 3 YELLOW blinks: CircuitPython is in safe mode. No user code was run. Check the serial console for safe mode reason.

When in the REPL, CircuitPython will set the status LED to WHITE. You can change the LED color from the REPL. The status indicator will not persist on non-NeoPixel or DotStar LEDs.

CircuitPython 6.3.0 and earlier

Here's what the colors and blinking mean:

  • steady GREEN: code.py (or code.txt, main.py, or main.txt) is running
  • pulsing GREEN: code.py (etc.) has finished or does not exist
  • steady YELLOW at start up: (4.0.0-alpha.5 and newer) CircuitPython is waiting for a reset to indicate that it should start in safe mode
  • pulsing YELLOW: Circuit Python is in safe mode: it crashed and restarted
  • steady WHITE: REPL is running
  • steady BLUE: boot.py is running

Colors with multiple flashes following indicate a Python exception and then indicate the line number of the error. The color of the first flash indicates the type of error:

  • GREEN: IndentationError
  • CYAN: SyntaxError
  • WHITE: NameError
  • ORANGE: OSError
  • PURPLE: ValueError
  • YELLOW: other error

These are followed by flashes indicating the line number, including place value. WHITE flashes are thousands' place, BLUE are hundreds' place, YELLOW are tens' place, and CYAN are one's place. So for example, an error on line 32 would flash YELLOW three times and then CYAN two times. Zeroes are indicated by an extra-long dark gap.

Serial console showing ValueError: Incompatible .mpy file

This error occurs when importing a module that is stored as a .mpy binary file that was generated by a different version of CircuitPython than the one its being loaded into. In particular, the mpy binary format changed between CircuitPython versions 6.x and 7.x, 2.x and 3.x, and 1.x and 2.x.

So, for instance, if you upgraded to CircuitPython 7.x from 6.x you’ll need to download a newer version of the library that triggered the error on import. All libraries are available in the Adafruit bundle.

CIRCUITPY Drive Issues

You may find that you can no longer save files to your CIRCUITPY drive. You may find that your CIRCUITPY stops showing up in your file explorer, or shows up as NO_NAME. These are indicators that your filesystem has issues. When the CIRCUITPY disk is not safely ejected before being reset by the button or being disconnected from USB, it may corrupt the flash drive. It can happen on Windows, Mac or Linux, though it is more common on Windows.

Be aware, if you have used Arduino to program your board, CircuitPython is no longer able to provide the USB services. You will need to reload CircuitPython to resolve this situation.

The easiest first step is to reload CircuitPython. Double-tap reset on the board so you get a boardnameBOOT drive rather than a CIRCUITPY drive, and copy the latest version of CircuitPython (.uf2) back to the board. This may restore CIRCUITPY functionality.

If reloading CircuitPython does not resolve your issue, the next step is to try putting the board into safe mode.

Safe Mode

Whether you've run into a situation where you can no longer edit your code.py on your CIRCUITPY drive, your board has gotten into a state where CIRCUITPY is read-only, or you have turned off the CIRCUITPY drive altogether, safe mode can help.

Safe mode in CircuitPython does not run any user code on startup, and disables auto-reload. This means a few things. First, safe mode bypasses any code in boot.py (where you can set CIRCUITPY read-only or turn it off completely). Second, it does not run the code in code.py. And finally, it does not automatically soft-reload when data is written to the CIRCUITPY drive.

Therefore, whatever you may have done to put your board in a non-interactive state, safe mode gives you the opportunity to correct it without losing all of the data on the CIRCUITPY drive.

Entering Safe Mode in CircuitPython 7.x and Later

To enter safe mode when using CircuitPython 7.x, plug in your board or hit reset (highlighted in red above). Immediately after the board starts up or resets, it waits 1000ms. On some boards, the onboard status LED will blink yellow during that time. If you press reset during that 1000ms, the board will start up in safe mode. It can be difficult to react to the yellow LED, so you may want to think of it simply as a "slow" double click of the reset button. (Remember, a fast double click of reset enters the bootloader.)

Entering Safe Mode in CircuitPython 6.x

To enter safe mode when using CircuitPython 6.x, plug in your board or hit reset (highlighted in red above). Immediately after the board starts up or resets, it waits 700ms. On some boards, the onboard status LED (highlighted in green above) will turn solid yellow during this time. If you press reset during that 700ms, the board will start up in safe mode. It can be difficult to react to the yellow LED, so you may want to think of it simply as a slow double click of the reset button. (Remember, a fast double click of reset enters the bootloader.)

In Safe Mode

Once you've entered safe mode successfully in CircuitPython 6.x, the LED will pulse yellow.

If you successfully enter safe mode on CircuitPython 7.x, the LED will intermittently blink yellow three times.

If you connect to the serial console, you'll find the following message.

Auto-reload is off.
Running in safe mode! Not running saved code.

CircuitPython is in safe mode because you pressed the reset button during boot. Press again to exit safe mode.

Press any key to enter the REPL. Use CTRL-D to reload.

You can now edit the contents of the CIRCUITPY drive. Remember, your code will not run until you press the reset button, or unplug and plug in your board, to get out of safe mode.

At this point, you'll want to remove any user code in code.py and, if present, the boot.py file from CIRCUITPY. Once removed, tap the reset button, or unplug and plug in your board, to restart CircuitPython. This will restart the board and may resolve your drive issues. If resolved, you can begin coding again as usual.

If safe mode does not resolve your issue, the board must be completely erased and CircuitPython must be reloaded onto the board.

You WILL lose everything on the board when you complete the following steps. If possible, make a copy of your code before continuing.

To erase CIRCUITPY: storage.erase_filesystem()

CircuitPython includes a built-in function to erase and reformat the filesystem. If you have a version of CircuitPython older than 2.3.0 on your board, you can update to the newest version to do this.

  1. Connect to the CircuitPython REPL using Mu or a terminal program.
  2. Type the following into the REPL:
>>> import storage
>>> storage.erase_filesystem()

CIRCUITPY will be erased and reformatted, and your board will restart. That's it!

Erase CIRCUITPY Without Access to the REPL

If you can't access the REPL, or you're running a version of CircuitPython previous to 2.3.0 and you don't want to upgrade, there are options available for some specific boards.

The options listed below are considered to be the "old way" of erasing your board. The method shown above using the REPL is highly recommended as the best method for erasing your board.

If at all possible, it is recommended to use the REPL to erase your CIRCUITPY drive. The REPL method is explained above.

For the specific boards listed below:

If the board you are trying to erase is listed below, follow the steps to use the file to erase your board.

       1.  Download the correct erase file:

       2.  Double-click the reset button on the board to bring up the boardnameBOOT drive.
       3.  Drag the erase .uf2 file to the boardnameBOOT drive.
       4.  The status LED will turn yellow or blue, indicating the erase has started.
       5.  After approximately 15 seconds, the status LED will light up green. On the NeoTrellis M4 this is the first NeoPixel on the grid
       6.  Double-click the reset button on the board to bring up the boardnameBOOT drive.
       7.  Drag the appropriate latest release of CircuitPython .uf2 file to the boardnameBOOT drive.

It should reboot automatically and you should see CIRCUITPY in your file explorer again.

If the LED flashes red during step 5, it means the erase has failed. Repeat the steps starting with 2.

If you haven't already downloaded the latest release of CircuitPython for your board, check out the installation page. You'll also need to load your code and reinstall your libraries!

For SAMD21 non-Express boards that have a UF2 bootloader:

Any SAMD21-based microcontroller that does not have external flash available is considered a SAMD21 non-Express board. Non-Express boards that have a UF2 bootloader include Trinket M0, GEMMA M0, QT Py M0, and the SAMD21-based Trinkey boards.

If you are trying to erase a SAMD21 non-Express board, follow these steps to erase your board.

       1.  Download the erase file:

       2.  Double-click the reset button on the board to bring up the boardnameBOOT drive.
       3.  Drag the erase .uf2 file to the boardnameBOOT drive.
       4.  The boot LED will start flashing again, and the boardnameBOOT drive will reappear.
       5.  Drag the appropriate latest release CircuitPython .uf2 file to the boardnameBOOT drive.

It should reboot automatically and you should see CIRCUITPY in your file explorer again.

If you haven't already downloaded the latest release of CircuitPython for your board, check out the installation page YYou'll also need to load your code and reinstall your libraries!

For SAMD21 non-Express boards that do not have a UF2 bootloader:

Any SAMD21-based microcontroller that does not have external flash available is considered a SAMD21 non-Express board. Non-Express boards that do not have a UF2 bootloader include the Feather M0 Basic Proto, Feather Adalogger, or the Arduino Zero.

If you are trying to erase a non-Express board that does not have a UF2 bootloader, follow these directions to reload CircuitPython using bossac, which will erase and re-create CIRCUITPY.

Running Out of File Space on SAMD21 Non-Express Boards

Any SAMD21-based microcontroller that does not have external flash available is considered a SAMD21 non-Express board. This includes boards like the Trinket M0, GEMMA M0, QT Py M0, and the SAMD21-based Trinkey boards.

The file system on the board is very tiny. (Smaller than an ancient floppy disk.) So, its likely you'll run out of space but don't panic! There are a number of ways to free up space.

Delete something!

The simplest way of freeing up space is to delete files from the drive. Perhaps there are libraries in the lib folder that you aren't using anymore or test code that isn't in use. Don't delete the lib folder completely, though, just remove what you don't need.

The board ships with the Windows 7 serial driver too! Feel free to delete that if you don't need it or have already installed it. It's ~12KiB or so.

Use tabs

One unique feature of Python is that the indentation of code matters. Usually the recommendation is to indent code with four spaces for every indent. In general, that is recommended too. However, one trick to storing more human-readable code is to use a single tab character for indentation. This approach uses 1/4 of the space for indentation and can be significant when you're counting bytes.

On MacOS?

MacOS loves to generate hidden files. Luckily you can disable some of the extra hidden files that macOS adds by running a few commands to disable search indexing and create zero byte placeholders. Follow the steps below to maximize the amount of space available on macOS.

Prevent & Remove MacOS Hidden Files

First find the volume name for your board.  With the board plugged in run this command in a terminal to list all the volumes:

ls -l /Volumes

Look for a volume with a name like CIRCUITPY (the default for CircuitPython).  The full path to the volume is the /Volumes/CIRCUITPY path.

Now follow the steps from this question to run these terminal commands that stop hidden files from being created on the board:

mdutil -i off /Volumes/CIRCUITPY
cd /Volumes/CIRCUITPY
rm -rf .{,_.}{fseventsd,Spotlight-V*,Trashes}
mkdir .fseventsd
touch .fseventsd/no_log .metadata_never_index .Trashes
cd -

Replace /Volumes/CIRCUITPY in the commands above with the full path to your board's volume if it's different.  At this point all the hidden files should be cleared from the board and some hidden files will be prevented from being created.

Alternatively, with CircuitPython 4.x and above, the special files and folders mentioned above will be created automatically if you erase and reformat the filesystem. WARNING: Save your files first! Do this in the REPL:

>>> import storage
>>> storage.erase_filesystem()

However there are still some cases where hidden files will be created by MacOS.  In particular if you copy a file that was downloaded from the internet it will have special metadata that MacOS stores as a hidden file.  Luckily you can run a copy command from the terminal to copy files without this hidden metadata file.  See the steps below.

Copy Files on MacOS Without Creating Hidden Files

Once you've disabled and removed hidden files with the above commands on macOS you need to be careful to copy files to the board with a special command that prevents future hidden files from being created.  Unfortunately you cannot use drag and drop copy in Finder because it will still create these hidden extended attribute files in some cases (for files downloaded from the internet, like Adafruit's modules).

To copy a file or folder use the -X option for the cp command in a terminal.  For example to copy a file_name.mpy file to the board use a command like:

cp -X file_name.mpy /Volumes/CIRCUITPY

(Replace file_name.mpy with the name of the file you want to copy.)

Or to copy a folder and all of the files and folders contained within, use a command like:

cp -rX folder_to_copy /Volumes/CIRCUITPY

If you are copying to the lib folder, or another folder, make sure it exists before copying.

# if lib does not exist, you'll create a file named lib !
cp -X file_name.mpy /Volumes/CIRCUITPY/lib
# This is safer, and will complain if a lib folder does not exist.
cp -X file_name.mpy /Volumes/CIRCUITPY/lib/

Other MacOS Space-Saving Tips

If you'd like to see the amount of space used on the drive and manually delete hidden files here's how to do so. First, move into the Volumes/ directory with cd /Volumes/, and then list the amount of space used on the CIRCUITPY drive with the df command.

That's not very much space left! The next step is to show a list of the files currently on the CIRCUITPY drive, including the hidden files, using the ls command. You cannot use Finder to do this, you must do it via command line!

There are a few of the hidden files that MacOS loves to generate, all of which begin with a ._ before the file name. Remove the ._ files using the rm command. You can remove them all once by running rm CIRCUITPY/._*. The * acts as a wildcard to apply the command to everything that begins with ._ at the same time.

Finally, you can run df again to see the current space used.

Nice! You have 12Ki more than before! This space can now be used for libraries and code!

Device Locked Up or Boot Looping

In rare cases, it may happen that something in your code.py or boot.py files causes the device to get locked up, or even go into a boot loop. A boot loop occurs when the board reboots repeatedly and never fully loads. These are not caused by your everyday Python exceptions, typically it's the result of a deeper problem within CircuitPython. In this situation, it can be difficult to recover your device if CIRCUITPY is not allowing you to modify the code.py or boot.py files. Safe mode is one recovery option. When the device boots up in safe mode it will not run the code.py or boot.py scripts, but will still connect the CIRCUITPY drive so that you can remove or modify those files as needed.

The method used to manually enter safe mode can be different for different devices. It is also very similar to the method used for getting into bootloader mode, which is a different thing. So it can take a few tries to get the timing right. If you end up in bootloader mode, no problem, you can try again without needing to do anything else.

For most devices:
Press the reset button, and then when the RGB status LED blinks yellow, press the reset button again. Since your reaction time may not be that fast, try a "slow" double click, to catch the yellow LED on the second click.

For ESP32-S2 based devices:
Press and release the reset button, then press and release the boot button about 3/4 of a second later.

Refer to the diagrams above for boot sequence details.

A lot of our boards can be used with multiple programming languages. For example, the Circuit Playground Express can be used with MakeCode, Code.org CS Discoveries, CircuitPython and Arduino.

Maybe you tried CircuitPython and want to go back to MakeCode or Arduino? Not a problem. You can always remove or reinstall CircuitPython whenever you want! Heck, you can change your mind every day!

There is nothing to uninstall. CircuitPython is "just another program" that is loaded onto your board. You simply load another program (Arduino or MakeCode) and it will overwrite CircuitPython.

Backup Your Code

Before replacing CircuitPython, don't forget to make a backup of the code you have on the CIRCUITPY drive. That means your code.py any other files, the lib folder etc. You may lose these files when you remove CircuitPython, so backups are key! Just drag the files to a folder on your laptop or desktop computer like you would with any USB drive.

Moving Circuit Playground Express to MakeCode

On the Circuit Playground Express (this currently does NOT apply to Circuit Playground Bluefruit), if you want to go back to using MakeCode, it's really easy. Visit makecode.adafruit.com and find the program you want to upload. Click Download to download the .uf2 file that is generated by MakeCode.

Now double-click your CircuitPython board until you see the onboard LED(s) turn green and the ...BOOT directory shows up.

Then find the downloaded MakeCode .uf2 file and drag it to the CPLAYBOOT drive.

Your MakeCode is now running and CircuitPython has been removed. Going forward you only have to single click the reset button to get to CPLAYBOOT. This is an idiosyncrasy of MakeCode.

Moving to Arduino

If you want to use Arduino instead, you just use the Arduino IDE to load an Arduino program. Here's an example of uploading a simple "Blink" Arduino program, but you don't have to use this particular program.

Start by plugging in your board, and double-clicking reset until you get the green onboard LED(s).

Within Arduino IDE, select the matching board, say Circuit Playground Express.

Select the correct matching Port:

Create a new simple Blink sketch example:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

Make sure the LED(s) are still green, then click Upload to upload Blink. Once it has uploaded successfully, the serial Port will change so re-select the new Port!

Once Blink is uploaded you should no longer need to double-click to enter bootloader mode. Arduino will automatically reset when you upload.

CircuitPython is a programming language that's super simple to get started with and great for learning. It runs on microcontrollers and works out of the box. You can plug it in and get started with any text editor. The best part? CircuitPython comes with an amazing, supportive community.

Everyone is welcome! CircuitPython is Open Source. This means it's available for anyone to use, edit, copy and improve upon. This also means CircuitPython becomes better because of you being a part of it. Whether this is your first microcontroller board or you're a seasoned software engineer, you have something important to offer the Adafruit CircuitPython community. This page highlights some of the many ways you can be a part of it!

Adafruit Discord

The Adafruit Discord server is the best place to start. Discord is where the community comes together to volunteer and provide live support of all kinds. From general discussion to detailed problem solving, and everything in between, Discord is a digital maker space with makers from around the world.

There are many different channels so you can choose the one best suited to your needs. Each channel is shown on Discord as "#channelname". There's the #help-with-projects channel for assistance with your current project or help coming up with ideas for your next one. There's the #show-and-tell channel for showing off your newest creation. Don't be afraid to ask a question in any channel! If you're unsure, #general is a great place to start. If another channel is more likely to provide you with a better answer, someone will guide you.

The help with CircuitPython channel is where to go with your CircuitPython questions. #help-with-circuitpython is there for new users and developers alike so feel free to ask a question or post a comment! Everyone of any experience level is welcome to join in on the conversation. Your contributions are important! The #circuitpython-dev channel is available for development discussions as well.

The easiest way to contribute to the community is to assist others on Discord. Supporting others doesn't always mean answering questions. Join in celebrating successes! Celebrate your mistakes! Sometimes just hearing that someone else has gone through a similar struggle can be enough to keep a maker moving forward.

The Adafruit Discord is the 24x7x365 hackerspace that you can bring your granddaughter to.

Visit https://adafru.it/discord to sign up for Discord. Everyone is looking forward to meeting you!

CircuitPython.org

Beyond the Adafruit Learn System, which you are viewing right now, the best place to find information about CircuitPython is circuitpython.org. Everything you need to get started with your new microcontroller and beyond is available. You can do things like download CircuitPython for your microcontroller or download the latest CircuitPython Library bundle, or check out which single board computers support Blinka. You can also get to various other CircuitPython related things like Awesome CircuitPython or the Python for Microcontrollers newsletter. This is all incredibly useful, but it isn't necessarily community related. So why is it included here? The Contributing page.

CircuitPython itself is written in C. However, all of the Adafruit CircuitPython libraries are written in Python. If you're interested in contributing to CircuitPython on the Python side of things, check out circuitpython.org/contributing. You'll find information pertaining to every Adafruit CircuitPython library GitHub repository, giving you the opportunity to join the community by finding a contributing option that works for you.

Note the date on the page next to Current Status for:

If you submit any contributions to the libraries, and do not see them reflected on the Contributing page, it could be that the job that checks for new updates hasn't yet run for today. Simply check back tomorrow!

Now, a look at the different options.

Pull Requests

The first tab you'll find is a list of open pull requests.

GitHub pull requests, or PRs, are opened when folks have added something to an Adafruit CircuitPython library GitHub repo, and are asking for Adafruit to add, or merge, their changes into the main library code. For PRs to be merged, they must first be reviewed. Reviewing is a great way to contribute! Take a look at the list of open pull requests, and pick one that interests you. If you have the hardware, you can test code changes. If you don't, you can still check the code updates for syntax. In the case of documentation updates, you can verify the information, or check it for spelling and grammar. Once you've checked out the update, you can leave a comment letting us know that you took a look. Once you've done that for a while, and you're more comfortable with it, you can consider joining the CircuitPythonLibrarians review team. The more reviewers we have, the more authors we can support. Reviewing is a crucial part of an open source ecosystem, CircuitPython included.

Open Issues

The second tab you'll find is a list of open issues.

GitHub issues are filed for a number of reasons, including when there is a bug in the library or example code, or when someone wants to make a feature request. Issues are a great way to find an opportunity to contribute directly to the libraries by updating code or documentation. If you're interested in contributing code or documentation, take a look at the open issues and find one that interests you.

If you're not sure where to start, you can search the issues by label. Labels are applied to issues to make the goal easier to identify at a first glance, or to indicate the difficulty level of the issue. Click on the dropdown next to "Sort by issue labels" to see the list of available labels, and click on one to choose it.

If you're new to everything, new to contributing to open source, or new to contributing to the CircuitPython project, you can choose "Good first issue". Issues with that label are well defined, with a finite scope, and are intended to be easy for someone new to figure out.

If you're looking for something a little more complicated, consider "Bug" or "Enhancement". The Bug label is applied to issues that pertain to problems or failures found in the library. The Enhancement label is applied to feature requests.

Don't let the process intimidate you. If you're new to Git and GitHub, there is a guide to walk you through the entire process. As well, there are always folks available on Discord to answer questions.

Library Infrastructure Issues

The third tab you'll find is a list of library infrastructure issues.

This section is generated by a script that runs checks on the libraries, and then reports back where there may be issues. It is made up of a list of subsections each containing links to the repositories that are experiencing that particular issue. This page is available mostly for internal use, but you may find some opportunities to contribute on this page. If there's an issue listed that sounds like something you could help with, mention it on Discord, or file an issue on GitHub indicating you're working to resolve that issue. Others can reply either way to let you know what the scope of it might be, and help you resolve it if necessary.

CircuitPython Localization

The fourth tab you'll find is the CircuitPython Localization tab.

If you speak another language, you can help translate CircuitPython! The translations apply to informational and error messages that are within the CircuitPython core. It means that folks who do not speak English have the opportunity to have these messages shown to them in their own language when using CircuitPython. This is incredibly important to provide the best experience possible for all users. CircuitPython uses Weblate to translate, which makes it much simpler to contribute translations. You will still need to know some CircuitPython-specific practices and a few basics about coding strings, but as with any CircuitPython contributions, folks are there to help.

Regardless of your skill level, or how you want to contribute to the CircuitPython project, there is an opportunity available. The Contributing page is an excellent place to start!

Adafruit GitHub

Whether you're just beginning or are life-long programmer who would like to contribute, there are ways for everyone to be a part of the CircuitPython project. The CircuitPython core is written in C. The libraries are written in Python. GitHub is the best source of ways to contribute to the CircuitPython core, and the CircuitPython libraries. If you need an account, visit https://github.com/ and sign up.

If you're new to GitHub or programming in general, there are great opportunities for you. For the CircuitPython core, head over to the CircuitPython repository on GitHub, click on "Issues", and you'll find a list that includes issues labeled "good first issue". For the libraries, head over to the Contributing page Issues list, and use the drop down menu to search for "good first issue". These issues are things that have been identified as something that someone with any level of experience can help with. These issues include options like updating documentation, providing feedback, and fixing simple bugs. If you need help getting started with GitHub, there is an excellent guide on Contributing to CircuitPython with Git and GitHub.

Already experienced and looking for a challenge? Checkout the rest of either issues list and you'll find plenty of ways to contribute. You'll find all sorts of things, from new driver requests, to library bugs, to core module updates. There's plenty of opportunities for everyone at any level!

When working with or using CircuitPython or the CircuitPython libraries, you may find problems. If you find a bug, that's great! The team loves bugs! Posting a detailed issue to GitHub is an invaluable way to contribute to improving CircuitPython. For CircuitPython itself, file an issue here. For the libraries, file an issue on the specific library repository on GitHub. Be sure to include the steps to replicate the issue as well as any other information you think is relevant. The more detail, the better!

Testing new software is easy and incredibly helpful. Simply load the newest version of CircuitPython or a library onto your CircuitPython hardware, and use it. Let us know about any problems you find by posting a new issue to GitHub. Software testing on both stable and unstable releases is a very important part of contributing CircuitPython. The developers can't possibly find all the problems themselves! They need your help to make CircuitPython even better.

On GitHub, you can submit feature requests, provide feedback, report problems and much more. If you have questions, remember that Discord and the Forums are both there for help!

Adafruit Forums

The Adafruit Forums are the perfect place for support. Adafruit has wonderful paid support folks to answer any questions you may have. Whether your hardware is giving you issues or your code doesn't seem to be working, the forums are always there for you to ask. You need an Adafruit account to post to the forums. You can use the same account you use to order from Adafruit.

While Discord may provide you with quicker responses than the forums, the forums are a more reliable source of information. If you want to be certain you're getting an Adafruit-supported answer, the forums are the best place to be.

There are forum categories that cover all kinds of topics, including everything Adafruit. The Adafruit CircuitPython category under "Supported Products & Projects" is the best place to post your CircuitPython questions.

Be sure to include the steps you took to get to where you are. If it involves wiring, post a picture! If your code is giving you trouble, include your code in your post! These are great ways to make sure that there's enough information to help you with your issue.

You might think you're just getting started, but you definitely know something that someone else doesn't. The great thing about the forums is that you can help others too! Everyone is welcome and encouraged to provide constructive feedback to any of the posted questions. This is an excellent way to contribute to the community and share your knowledge!

Read the Docs

Read the Docs is a an excellent resource for a more detailed look at the CircuitPython core and the CircuitPython libraries. This is where you'll find things like API documentation and example code. For an in depth look at viewing and understanding Read the Docs, check out the CircuitPython Documentation page!

You've been introduced to CircuitPython, and worked through getting everything set up. What's next? CircuitPython Essentials!

There are a number of core modules built into CircuitPython, which can be used along side the many CircuitPython libraries available. The following pages demonstrate some of these modules. Each page presents a different concept including a code example with an explanation. All of the examples are designed to work with your microcontroller board.

Time to get started learning the CircuitPython essentials!

Many of the demos in this guide require the EyeLights LED Glasses Driver and the EyeLights LED Glasses Panel. The I2C Essentials example requires an I2C sensor breakout.

The following components are needed to complete all of the examples.

Angled shot of Adafruit LED Glasses Driver.
This board is designed to be a thin, bluetooth-enabled driver board for our Adafruit LED Glasses RGB LED matrix. That said, it's...
$24.95
In Stock
Top view of dragon eyeglass PCB. ADAFRUIT in rainbow LEDs scrolls across the mask.
Have you always wanted to upgrade your ensemble with a creepy-cool creature PCB silkscreen and an eye-blistering arrangement of LEDs?
$24.95
In Stock
Top view of temperature sensor breakout above an OLED display FeatherWing. The OLED display reads "MCP9808 Temp: 24.19ºC"
The MCP9808 digital temperature sensor is one of the more accurate/precise we've ever seen, with a typical accuracy of ±0.25°C over the sensor's -40°C to...
$4.95
In Stock

In learning any programming language, you often begin with some sort of Hello, World! program. In CircuitPython, Hello, World! is blinking an LED. Blink is one of the simplest programs in CircuitPython. It involves three built-in modules, two lines of set up, and a short loop. Despite its simplicity, it shows you many of the basic concepts needed for most CircuitPython programs, and provides a solid basis for more complex projects. Time to get blinky!

LED Location

  • Along the top edge, towards the right end of the board, is a red LED (highlighted in red in the image), labeled LED on the board.

Blinking an LED

In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory CircuitPython_Templates/blink/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT
"""CircuitPython Blink Example - the CircuitPython 'Hello, World!'"""
import time
import board
import digitalio

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

while True:
    led.value = True
    time.sleep(0.5)
    led.value = False
    time.sleep(0.5)

The built-in LED begins blinking!

Note that the code is a little less "Pythonic" than it could be. It could also be written as led.value = not led.value with a single time.sleep(0.5). That way is more difficult to understand if you're new to programming, so the example is a bit longer than it needed to be to make it easier to read.

It's important to understand what is going on in this program.

First you import three modules: time, board and digitalio. This makes these modules available for use in your code. All three are built-in to CircuitPython, so you don't need to download anything to get started.

Next, you set up the LED. To interact with hardware in CircuitPython, your code must let the board know where to look for the hardware and what to do with it. So, you create a digitalio.DigitalInOut() object, provide it the LED pin using the board module, and save it to the variable led. Then, you tell the pin to act as an OUTPUT.

Finally, you create a while True: loop. This means all the code inside the loop will repeat indefinitely. Inside the loop, you set led.value = True which powers on the LED. Then, you use time.sleep(0.5) to tell the code to wait half a second before moving on to the next line. The next line sets led.value = False which turns the LED off. Then you use another time.sleep(0.5) to wait half a second before starting the loop over again.

With only a small update, you can control the blink speed. The blink speed is controlled by the amount of time you tell the code to wait before moving on using time.sleep(). The example uses 0.5, which is one half of one second. Try increasing or decreasing these values to see how the blinking changes.

That's all there is to blinking an LED using CircuitPython!

The CircuitPython digitalio module has many applications. The basic Blink program sets up the LED as a digital output. You can just as easily set up a digital input such as a button to control the LED. This example builds on the basic Blink example, but now includes setup for a button switch. Instead of using the time module to blink the LED, it uses the status of the button switch to control whether the LED is turned on or off.

LED and Button

  • Along the top edge, towards the right end of the board, is a red LED (highlighted in red in the image), labeled LED on the board.
  • Along the top edge, towards the left end of the board, is a user button switch (highlighted in green in the image), labeled SW on the board.

Controlling the LED with a Button

In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory EyeLights_LED_Glasses_and_Driver/Digital_Input/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
CircuitPython Digital Input Example - Blinking an LED using a button switch.
"""
import board
import digitalio

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

button = digitalio.DigitalInOut(board.SWITCH)
button.switch_to_input(pull=digitalio.Pull.UP)

while True:
    if not button.value:
        led.value = True
    else:
        led.value = False

Now, press the button. The LED lights up! Let go of the button and the LED turns off.

Note that the code is a little less "Pythonic" than it could be. It could also be written as led.value = not button.value. That way is more difficult to understand if you're new to programming, so the example is a bit longer than it needed to be to make it easier to read.

First you import two modules: board and digitalio. This makes these modules available for use in your code. Both are built-in to CircuitPython, so you don't need to download anything to get started.

Next, you set up the LED. To interact with hardware in CircuitPython, your code must let the board know where to look for the hardware and what to do with it. So, you create a digitalio.DigitalInOut() object, provide it the LED pin using the board module, and save it to the variable led. Then, you tell the pin to act as an OUTPUT.

You include setup for the button as well. It is similar to the LED setup, except the button is an INPUT, and requires a pull up.

Inside the loop, you check to see if the button is pressed, and if so, turn on the LED. Otherwise the LED is off.

That's all there is to controlling an LED with a button switch!

i2c_I2C_controller_target.jpg
A QT Py ESP32-S2 connected to an MCP9808 Temperature Sensor for I2C via STEMMA QT.

The I2C, or inter-integrated circuit, is a 2-wire protocol for communicating with simple sensors and devices, which means it uses two connections, or wires, for transmitting and receiving data. One connection is a clock, called SCL. The other is the data line, called SDA. Each pair of clock and data pins are referred to as a bus.

Typically, there is a device that acts as a controller and sends requests to the target devices on each bus. In this case, your microcontroller board acts as the controller, and the sensor breakout acts as the target. Historically, the controller is referred to as the master, and the target is referred to as the slave, so you may run into that terminology elsewhere. The official terminology is controller and target.

Multiple I2C devices can be connected to the same clock and data lines. Each I2C device has an address, and as long as the addresses are different, you can connect them at the same time. This means you can have many different sensors and devices all connected to the same two pins.

Both I2C connections require pull-up resistors, and most Adafruit I2C sensors and breakouts have pull-up resistors built in. If you're using one that does not, you'll need to add your own 2.2-10kΩ pull-up resistors from SCL and SDA to 3.3V.

I2C and CircuitPython

CircuitPython supports many I2C devices, and makes it super simple to interact with them. There are libraries available for many I2C devices in the CircuitPython Library Bundle. (If you don't see the sensor you're looking for, keep checking back, more are being written all the time!)

In this section, you'll learn how to scan the I2C bus for all connected devices. Then you'll learn how to interact with an I2C device.

Necessary Hardware

You'll need the following additional hardware to complete the examples on this page.

Top view of temperature sensor breakout above an OLED display FeatherWing. The OLED display reads "MCP9808 Temp: 24.19ºC"
The MCP9808 digital temperature sensor is one of the more accurate/precise we've ever seen, with a typical accuracy of ±0.25°C over the sensor's -40°C to...
$4.95
In Stock
Angled of of JST SH 4-Pin Cable.
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

While the examples here will be using the Adafruit MCP9808, a high accuracy temperature sensor, the overall process is the same for just about any I2C sensor or device.

The first thing you'll want to do is get the sensor connected so your board has I2C to talk to.

Wiring the MCP9808

The MCP9808 comes with a STEMMA QT connector, which makes wiring it up quite simple and solder-free.

 

 

Simply connect the STEMMA QT cable from the STEMMA QT port on your board to the STEMMA QT port on the MCP9808.

Find Your Sensor

The first thing you'll want to do after getting the sensor wired up, is make sure it's wired correctly. You're going to do an I2C scan to see if the board is detected, and if it is, print out its I2C address.

Save the following to your CIRCUITPY drive as code.py.

Click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, find your CircuitPython version, and copy the matching code.py file to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT
"""CircuitPython I2C Device Address Scan"""
import time
import board

i2c = board.I2C()  # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller

# To create I2C bus on specific pins
# import busio
# i2c = busio.I2C(board.GP1, board.GP0)    # Pi Pico RP2040

while not i2c.try_lock():
    pass

try:
    while True:
        print(
            "I2C addresses found:",
            [hex(device_address) for device_address in i2c.scan()],
        )
        time.sleep(2)

finally:  # unlock the i2c bus when ctrl-c'ing out of the loop
    i2c.unlock()

If you run this and it seems to hang, try manually unlocking your I2C bus by running the following two commands from the REPL.

import board
board.I2C().unlock()

First you create the i2c object, using board.I2C(). This convenience routine creates and saves a busio.I2C object using the default pins board.SCL and board.SDA. If the object has already been created, then the existing object is returned. No matter how many times you call board.I2C(), it will return the same object. This is called a singleton.

To be able to scan it, you need to lock the I2C down so the only thing accessing it is the code. So next you include a loop that waits until I2C is locked and then continues on to the scan function.

Last, you have the loop that runs the actual scan, i2c_scan(). Because I2C typically refers to addresses in hex form, the example includes this bit of code that formats the results into hex format: [hex(device_address) for device_address in i2c.scan()].

Open the serial console to see the results! The code prints out an array of addresses. You've connected the MCP9808 which has a 7-bit I2C address of 0x18. The result for this sensor is I2C addresses found: ['0x18']. If no addresses are returned, refer back to the wiring diagrams to make sure you've wired up your sensor correctly.

I2C Sensor Data

Now you know for certain that your sensor is connected and ready to go. Time to find out how to get the data from the sensor!

Save the following to your CIRCUITPY drive as code.py.

Click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, find your CircuitPython version, and copy the matching entire lib folder and code.py file to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT
"""CircuitPython I2C MCP9808 Temperature Sensor Example"""
import time
import board
import adafruit_mcp9808

i2c = board.I2C()  # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
# import busio
# i2c = busio.I2C(board.SCL1, board.SDA1) # For QT Py RP2040, QT Py ESP32-S2
mcp9808 = adafruit_mcp9808.MCP9808(i2c)

while True:
    temperature_celsius = mcp9808.temperature
    temperature_fahrenheit = temperature_celsius * 9 / 5 + 32
    print("Temperature: {:.2f} C {:.2f} F ".format(temperature_celsius, temperature_fahrenheit))
    time.sleep(2)
For the EyeLights, you'll need to change the I2C setup to the commented out setup included in the code above.

The EyeLights STEMMA QT connector is available on board.STEMMA_I2C(). Comment out the current i2c setup line, and uncomment the the i2c = board.STEMMA_I2C() line to use with your board's STEMMA QT connector.

This code begins the same way as the scan code, except this time, you create your sensor object using the sensor library. You call it mcp9808 and provide it the i2c object.

Then you have a simple loop that prints out the temperature reading using the sensor object you created. Finally, there's a time.sleep(2), so it only prints once every two seconds. Connect to the serial console to see the results. Try touching the MCP9808 with your finger to see the values change!

Where's my I2C?

On many microcontrollers, you have the flexibility of using a wide range of pins for I2C. On some types of microcontrollers, any pin can be used for I2C! Other chips require using bitbangio, but can also use any pins for I2C. There are further microcontrollers that may have fixed I2C pins.  

Given the many different types of microcontroller boards available, it's impossible to guarantee anything other than the labeled 'SDA' and 'SCL' pins. So, if you want some other setup, or multiple I2C interfaces, how will you find those pins? Easy! Below is a handy script.

Save the following to your CIRCUITPY drive as code.py.

Click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, find your CircuitPython version, and copy the matching code.py file to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021-2023 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT
"""CircuitPython I2C possible pin-pair identifying script"""
import board
import busio
from microcontroller import Pin


def is_hardware_i2c(scl, sda):
    try:
        p = busio.I2C(scl, sda)
        p.deinit()
        return True
    except ValueError:
        return False
    except RuntimeError:
        return True


def get_unique_pins():
    exclude = [
        getattr(board, p)
        for p in [
            # This is not an exhaustive list of unexposed pins. Your results
            # may include other pins that you cannot easily connect to.
            "NEOPIXEL",
            "DOTSTAR_CLOCK",
            "DOTSTAR_DATA",
            "APA102_SCK",
            "APA102_MOSI",
            "LED",
            "SWITCH",
            "BUTTON",
            "ACCELEROMETER_INTERRUPT",
            "VOLTAGE_MONITOR",
            "MICROPHONE_CLOCK",
            "MICROPHONE_DATA",
            "RFM_RST",
            "RFM_CS",
            "RFM_IO0",
            "RFM_IO1",
            "RFM_IO2",
            "RFM_IO3",
            "RFM_IO4",
            "RFM_IO5",
            "TFT_I2C_POWER",
            "NEOPIXEL_POWER",
        ]
        if p in dir(board)
    ]
    pins = [
        pin
        for pin in [getattr(board, p) for p in dir(board)]
        if isinstance(pin, Pin) and pin not in exclude
    ]
    unique = []
    for p in pins:
        if p not in unique:
            unique.append(p)
    return unique


for scl_pin in get_unique_pins():
    for sda_pin in get_unique_pins():
        if scl_pin is sda_pin:
            continue
        if is_hardware_i2c(scl_pin, sda_pin):
            print("SCL pin:", scl_pin, "\t SDA pin:", sda_pin)

Now, connect to the serial console and check out the output! The results print out a nice handy list of SCL and SDA pin pairs that support I2C.

This example only runs once, so if you do not see any output when you connect to the serial console, try CTRL+D to reload.

There is a temperature sensor built into the CPU on your microcontroller board. It reads the internal CPU temperature, which varies depending on how long the board has been running or how intense your code is.

CircuitPython makes it really simple to read this data from the temperature sensor built into the microcontroller. Using the built-in microcontroller module, you can easily read the temperature.

Microcontroller Location

The blue and silver module located on the right end of the board, opposite the USB connector, is the nRF52840.

Reading the Microcontroller Temperature

The data is read using two lines of code. All necessary modules are built into CircuitPython, so you don't need to download any extra files to get started.

Connect to the serial console, and then update your code.py to the following.

In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory CircuitPython_Templates/cpu_temperature/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT
"""CircuitPython CPU temperature example in Celsius"""
import time
import microcontroller

while True:
    print(microcontroller.cpu.temperature)
    time.sleep(0.15)

The CPU temperature in Celsius is printed out to the serial console!

Try putting your finger on the microcontroller to see the temperature change.

The code is simple. First you import two modules: time and microcontroller. Then, inside the loop, you print the microcontroller CPU temperature, and the time.sleep() slows down the print enough to be readable. That's it!

You can easily print out the temperature in Fahrenheit by adding a little math to your code, using this simple formula: Celsius * (9/5) + 32.

In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory CircuitPython_Templates/cpu_temperature_f/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT
"""CircuitPython CPU temperature example in Fahrenheit"""
import time
import microcontroller

while True:
    print(microcontroller.cpu.temperature * (9 / 5) + 32)
    time.sleep(0.15)

The CPU temperature in Fahrenheit is printed out to the serial console!

That's all there is to reading the CPU temperature using CircuitPython!

Note that the temperature sensor built into the nRF52840 has a resolution of 0.25 degrees Celsius, so any temperature you print out will be in 0.25 degree increments.

We made a few starter projects to demonstrate features of the EyeLights LED Glasses and Driver such as the accelerometer or microphone input. They’re not highly polished demos, but show how to set up the basics. Consider them starting points and fuel for your own creative ideas.

The next few pages showcase CircuitPython examples. If Arduino is more your style, we have a separate starter projects section for that later in this guide.

The examples rely on the adafruit_is31fl3741 library for CircuitPython, and each may then require one or two other libraries. Using the “Download Project Bundle” button for each project will gather up all the files you need!

Don’t be alarmed by the size of the code below…it’s actually more comments than code, to walk you through what it’s doing.

This example demonstrates some basics of using the LED rings and the driver board’s accelerometer.

Although the driver board has a clicky button that can be used for input (board.SWITCH in CircuitPython), this is one of those “make you think” projects: what if, instead explicitly interacting with devices, they anticipated our needs and did what we want? This is normally a pair of festive Halloween glasses…but when you look down (as when navigating steps or looking in your candy bag) it transitions into bright headlights. Look up again and it’s back to Halloween mode.

This also demonstrates the accelerometer’s tap-detect function (just tap the glasses to select among different color schemes) and smooth “easing” interpolation between colors that gives things a touch of luxury.

The driver board is normally mounted on an eyeglass frame’s temple, with the STEMMA QT connector toward the front. If the code’s look-down behavior seems wrong, it may be that the glasses are folded or the board isn’t mounted the right way.

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory EyeLights_Accelerometer_Tap/EyeLights_Accelerometer_Tap_Circuitpython and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
ACCELEROMETER INPUT DEMO: while the LED Glasses Driver has a perfectly
good clicky button for input, this code shows how one might instead use
the onboard accelerometer for interactions*.

Worn normally, the LED rings are simply lit a solid color.
TAP the eyeglass frames to cycle among a list of available colors.
LOOK DOWN to light the LED rings bright white -- for navigating steps
or finding the right key. LOOK BACK UP to return to solid color.
This uses only the rings, not the matrix portion.

* Like, if you have big ol' monster hands, that little button can be
  hard to click, y'know?
"""

import time
import board
import digitalio
import supervisor
import adafruit_lis3dh
import adafruit_is31fl3741
from adafruit_is31fl3741.adafruit_ledglasses import LED_Glasses

# Shared by both the accelerometer and LED controller
i2c = board.I2C()  # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller

# Initialize the accelerometer and enable single-tap detection
int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1)
lis3dh.set_tap(1, 100)
last_tap_time = 0

# Initialize the IS31 LED driver, buffered for smoother animation
glasses = LED_Glasses(i2c, allocate=adafruit_is31fl3741.MUST_BUFFER)

# Here's a list of colors that we cycle through when tapped, specified
# as (R,G,B) tuples from 0-255. These are intentionally a bit dim --
# both to save battery and to make the "ground light" mode more dramatic.
# Rather than primary color red/green/blue sequence which is just so
# over-done at this point, let's use some HALLOWEEN colors!
colors = ((27, 9, 0), (12, 0, 24), (5, 31, 0))  # Orange, purple, green
color_index = 0  # Begin at first color in list

# Check accelerometer to see if we've started in the looking-down state,
# set the target color (what we're aiming for) appropriately. Only the
# Y axis is needed for this.
_, filtered_y, _ = lis3dh.acceleration
looking_down = filtered_y > 5
target_color = (255, 255, 255) if looking_down else colors[color_index]

interpolated_color = (0, 0, 0)  # LEDs off at startup, they'll ramp up


while True:  # Loop forever...

    # The try/except here is because VERY INFREQUENTLY the I2C bus will
    # encounter an error when accessing either the accelerometer or the
    # LED driver, whether from bumping around the wires or sometimes an
    # I2C device just gets wedged. To more robustly handle the latter,
    # the code will restart if that happens.
    try:

        # interpolated_color blends from the prior to the next ("target")
        # LED ring colors, with a pleasant ease-out effect.
        interpolated_color = (
            interpolated_color[0] * 0.85 + target_color[0] * 0.15,
            interpolated_color[1] * 0.85 + target_color[1] * 0.15,
            interpolated_color[2] * 0.85 + target_color[2] * 0.15,
        )
        # Fill both rings with interpolated_color, then refresh the LEDs.
        # fill_color(interpolated_color)
        packed = (
            (int(interpolated_color[0]) << 16)
            | (int(interpolated_color[1]) << 8)
            | int(interpolated_color[2])
        )
        glasses.left_ring.fill(packed)
        glasses.right_ring.fill(packed)
        glasses.show()

        # The look-down detection only needs the accelerometer's Y axis.
        # This works with the Glasses Driver mounted on either temple and
        # with the glasses arms "open" (as when worn).
        _, y, _ = lis3dh.acceleration
        # Smooth the accelerometer reading the same way RGB colors are
        # interpolated. This avoids false triggers from jostling around.
        filtered_y = filtered_y * 0.85 + y * 0.15
        # The threshold between "looking down" and "looking up" depends
        # on which of those states we're currently in. This is an example
        # of hysteresis in software...a change of direction requires a
        # little extra push before it takes, which avoids oscillating if
        # there was just a single threshold both ways.
        if looking_down:  #             Currently in the looking-down state
            _ = lis3dh.tapped  #        Discard any taps while looking down
            if filtered_y < 3.5:  #     Have we crossed the look-up threshold?
                target_color = colors[color_index]
                looking_down = False  # We're looking up now!
        else:  #                        Currently in looking-up state
            if filtered_y > 5:  #       Crossed the look-down threshold?
                target_color = (255, 255, 255)
                looking_down = True  #  We're looking down now!
            elif lis3dh.tapped:
                # No look up/down change, but the accelerometer registered
                # a tap. Compare this against the last time we sensed one,
                # and only do things if it's been more than half a second.
                # This avoids spurious double-taps that can occur no matter
                # how carefully the tap threshold was set.
                now = time.monotonic()
                elapsed = now - last_tap_time
                if elapsed > 0.5:
                    # A good tap was detected. Cycle to the next color in
                    # the list and note the time of this tap.
                    color_index = (color_index + 1) % len(colors)
                    target_color = colors[color_index]
                    last_tap_time = now

    # See "try" notes above regarding rare I2C errors.
    except OSError:
        supervisor.reload()

This is another example demonstrating the LED rings and accelerometer, not the matrix portion of the glasses yet. The rings swivel and spin in response to movement, as if filled with liquid, or like jiggling plastic “googly eyes.” The idea and math are adapted from an earlier project, Bill Earl's STEAM-Punk Goggles.

The driver board is normally mounted on an eyeglass frame’s temple, with the STEMMA QT connector toward the front. If gravity’s behavior seems wrong, it may be that the glasses are folded or the board isn’t mounted right.

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory EyeLights_Googly_Rings/EyeLights_Googly_Rings_CircuitPython/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
GOOGLY EYES for Adafruit EyeLight LED glasses + driver. Pendulum physics
simulation using accelerometer and math. This uses only the rings, not the
matrix portion. Adapted from Bill Earl's STEAM-Punk Goggles project:
https://learn.adafruit.com/steam-punk-goggles
"""

import math
import random
import board
import supervisor
import adafruit_lis3dh
import adafruit_is31fl3741
from adafruit_is31fl3741.adafruit_ledglasses import LED_Glasses


# HARDWARE SETUP ----

# Shared by both the accelerometer and LED controller
i2c = board.I2C()  # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller

# Initialize the accelerometer
lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c)

# Initialize the IS31 LED driver, buffered for smoother animation
glasses = LED_Glasses(i2c, allocate=adafruit_is31fl3741.MUST_BUFFER)


# PHYSICS SETUP -----


class Pendulum:
    """A small class for our pendulum simulation."""

    def __init__(self, ring, color):
        """Initial pendulum position, plus axle friction, are randomized
        so the two rings don't spin in perfect lockstep."""
        self.ring = ring  # Save reference to corresponding LED ring
        self.color = color  # (R,G,B) tuple for color
        self.angle = random.random()  # Position around ring, in radians
        self.momentum = 0
        self.friction = random.uniform(0.85, 0.9)  # Inverse friction, really

    def interp(self, pixel, scale):
        """Given a pixel index (0-23) and a scaling factor (0.0-1.0),
        interpolate between LED "off" color (at 0.0) and this item's fully-
        lit color (at 1.0) and set pixel to the result."""
        self.ring[pixel] = (
            (int(self.color[0] * scale) << 16)
            | (int(self.color[1] * scale) << 8)
            | int(self.color[2] * scale)
        )

    def iterate(self, xyz):
        """Given an accelerometer reading, run one cycle of the pendulum
        physics simulation and render the corresponding LED ring."""
        # Minus here is because LED pixel indices run clockwise vs. trigwise.
        # 0.05 is just an empirically-derived scaling fudge factor that looks
        # good; smaller values for more sluggish rings, higher = more twitch.
        self.momentum = (
            self.momentum * self.friction
            - (math.cos(self.angle) * xyz[2] + math.sin(self.angle) * xyz[0]) * 0.05
        )
        self.angle += self.momentum

        # Scale pendulum angle into pixel space
        midpoint = self.angle * 12 / math.pi % 24
        # Go around the whole ring, setting each pixel based on proximity
        # (this is also to erase the prior position)...
        for i in range(24):
            dist = abs(midpoint - i)  # Pixel to pendulum distance...
            if dist > 12:  #            If it crosses the "seam" at top,
                dist = 24 - dist  #      take the shorter path.
            if dist > 5:  #             Not close to pendulum,
                self.ring[i] = 0  #      erase pixel.
            elif dist < 2:  #           Close to pendulum,
                self.interp(i, 1.0)  #   solid color
            else:  #                    Anything in-between,
                self.interp(i, (5 - dist) / 3)  # interpolate


# List of pendulum objects, of which there are two: one per glasses ring
pendulums = [
    Pendulum(glasses.left_ring, (0, 20, 50)),  # Cerulean blue,
    Pendulum(glasses.right_ring, (0, 20, 50)),  # 50 is plenty bright!
]


# MAIN LOOP ---------

while True:

    # The try/except here is because VERY INFREQUENTLY the I2C bus will
    # encounter an error when accessing either the accelerometer or the
    # LED driver, whether from bumping around the wires or sometimes an
    # I2C device just gets wedged. To more robustly handle the latter,
    # the code will restart if that happens.
    try:

        accel = lis3dh.acceleration
        for p in pendulums:
            p.iterate(accel)

        glasses.show()

    # See "try" notes above regarding rare I2C errors.
    except OSError:
        supervisor.reload()

OK, now let’s put that microphone and 18x5 RGB LED matrix to good use…this project reacts to sound and music as a flashy audio spectrum visualizer.

While this looks like a lot of code, again it’s about 50% comments. With all that’s going on, it’s a bit surprising how little code this required, thanks to CircuitPython’s native ulab module for number-crunching.

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory EyeLights_Audio_Spectrum/EyeLights_Audio_Spectrum_CircuitPython/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
AUDIO SPECTRUM LIGHT SHOW for Adafruit EyeLights (LED Glasses + Driver).
Uses onboard microphone and a lot of math to react to music.
"""

from array import array
from math import log
from time import monotonic
from supervisor import reload
import board
from audiobusio import PDMIn
from busio import I2C
import adafruit_is31fl3741
from adafruit_is31fl3741.adafruit_ledglasses import LED_Glasses
from rainbowio import colorwheel
from ulab import numpy as np
from ulab.scipy.signal import spectrogram


# FFT/SPECTRUM CONFIG ----

fft_size = 256  # Sample size for Fourier transform, MUST be power of two
spectrum_size = fft_size // 2  # Output spectrum is 1/2 of FFT result
# Bottom of spectrum tends to be noisy, while top often exceeds musical
# range and is just harmonics, so clip both ends off:
low_bin = 10  # Lowest bin of spectrum that contributes to graph
high_bin = 75  # Highest bin "


# HARDWARE SETUP ---------

# Manually declare I2C (not board.I2C() directly) to access 1 MHz speed...
i2c = I2C(board.SCL, board.SDA, frequency=1000000)

# Initialize the IS31 LED driver, buffered for smoother animation
glasses = LED_Glasses(i2c, allocate=adafruit_is31fl3741.MUST_BUFFER)
glasses.show()  # Clear any residue on startup
glasses.global_current = 5  # Not too bright please

# Initialize mic and allocate recording buffer (default rate is 16 MHz)
mic = PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, bit_depth=16)
rec_buf = array("H", [0] * fft_size)  # 16-bit audio samples


# FFT/SPECTRUM SETUP -----

# To keep the display lively, tables are precomputed where each column of
# the matrix (of which there are few) is the sum value and weighting of
# several bins from the FFT spectrum output (of which there are many).
# The tables also help visually linearize the output so octaves are evenly
# spaced, as on a piano keyboard, whereas the source spectrum data is
# spaced by frequency in Hz.
column_table = []

spectrum_bits = log(spectrum_size, 2)  # e.g. 7 for 128-bin spectrum
# Scale low_bin and high_bin to 0.0 to 1.0 equivalent range in spectrum
low_frac = log(low_bin, 2) / spectrum_bits
frac_range = log(high_bin, 2) / spectrum_bits - low_frac

for column in range(glasses.width):
    # Determine the lower and upper frequency range for this column, as
    # fractions within the scaled 0.0 to 1.0 spectrum range. 0.95 below
    # creates slight frequency overlap between columns, looks nicer.
    lower = low_frac + frac_range * (column / glasses.width * 0.95)
    upper = low_frac + frac_range * ((column + 1) / glasses.width)
    mid = (lower + upper) * 0.5  # Center of lower-to-upper range
    half_width = (upper - lower) * 0.5  # 1/2 of lower-to-upper range
    # Map fractions back to spectrum bin indices that contribute to column
    first_bin = int(2 ** (spectrum_bits * lower) + 1e-4)
    last_bin = int(2 ** (spectrum_bits * upper) + 1e-4)
    bin_weights = []  # Each spectrum bin's weighting will be added here
    for bin_index in range(first_bin, last_bin + 1):
        # Find distance from column's overall center to individual bin's
        # center, expressed as 0.0 (bin at center) to 1.0 (bin at limit of
        # lower-to-upper range).
        bin_center = log(bin_index + 0.5, 2) / spectrum_bits
        dist = abs(bin_center - mid) / half_width
        if dist < 1.0:  # Filter out a few math stragglers at either end
            # Bin weights have a cubic falloff curve within range:
            dist = 1.0 - dist  # Invert dist so 1.0 is at center
            bin_weights.append(((3.0 - (dist * 2.0)) * dist) * dist)
    # Scale bin weights so total is 1.0 for each column, but then mute
    # lower columns slightly and boost higher columns. It graphs better.
    total = sum(bin_weights)
    bin_weights = [
        (weight / total) * (0.8 + idx / glasses.width * 1.4)
        for idx, weight in enumerate(bin_weights)
    ]
    # List w/five elements is stored for each column:
    # 0: Index of the first spectrum bin that impacts this column.
    # 1: A list of bin weights, starting from index above, length varies.
    # 2: Color for drawing this column on the LED matrix. The 225 is on
    #    purpose, providing hues from red to purple, leaving out magenta.
    # 3: Current height of the 'falling dot', updated each frame
    # 4: Current velocity of the 'falling dot', updated each frame
    column_table.append(
        [
            first_bin - low_bin,
            bin_weights,
            colorwheel(225 * column / glasses.width),
            glasses.height,
            0.0,
        ]
    )
# print(column_table)


# MAIN LOOP -------------

dynamic_level = 10  # For responding to changing volume levels
frames, start_time = 0, monotonic()  # For frames-per-second calc

while True:
    # The try/except here is because VERY INFREQUENTLY the I2C bus will
    # encounter an error when accessing the LED driver, whether from bumping
    # around the wires or sometimes an I2C device just gets wedged. To more
    # robustly handle the latter, the code will restart if that happens.
    try:
        mic.record(rec_buf, fft_size)  # Record batch of 16-bit samples
        samples = np.array(rec_buf)  # Convert to ndarray
        # Compute spectrogram and trim results. Only the left half is
        # normally needed (right half is mirrored), but we trim further as
        # only the low_bin to high_bin elements are interesting to graph.
        spectrum = spectrogram(samples)[low_bin : high_bin + 1]
        # Linearize spectrum output. spectrogram() is always nonnegative,
        # but add a tiny value to change any zeros to nonzero numbers
        # (avoids rare 'inf' error)
        spectrum = np.log(spectrum + 1e-7)
        # Determine minimum & maximum across all spectrum bins, with limits
        lower = max(np.min(spectrum), 4)
        upper = min(max(np.max(spectrum), lower + 6), 20)

        # Adjust dynamic level to current spectrum output, keeps the graph
        # 'lively' as ambient volume changes. Sparkle but don't saturate.
        if upper > dynamic_level:
            # Got louder. Move level up quickly but allow initial "bump."
            dynamic_level = upper * 0.7 + dynamic_level * 0.3
        else:
            # Got quieter. Ease level down, else too many bumps.
            dynamic_level = dynamic_level * 0.5 + lower * 0.5

        # Apply vertical scale to spectrum data. Results may exceed
        # matrix height...that's OK, adds impact!
        data = (spectrum - lower) * (7 / (dynamic_level - lower))

        for column, element in enumerate(column_table):
            # Start BELOW matrix and accumulate bin weights UP, saves math
            first_bin = element[0]
            column_top = glasses.height + 1
            for bin_offset, weight in enumerate(element[1]):
                column_top -= data[first_bin + bin_offset] * weight

            if column_top < element[3]:  #       Above current falling dot?
                element[3] = column_top - 0.5  # Move dot up
                element[4] = 0  #                and clear out velocity
            else:
                element[3] += element[4]  #      Move dot down
                element[4] += 0.2  #             and accelerate

            column_top = int(column_top)  #      Quantize to pixel space
            for row in range(column_top):  #     Erase area above column
                glasses.pixel(column, row, 0)
            for row in range(column_top, 5):  #  Draw column
                glasses.pixel(column, row, element[2])
            glasses.pixel(column, int(element[3]), 0xE08080)  # Draw peak dot

        glasses.show()  # Buffered mode MUST use show() to refresh matrix

        frames += 1
        # print(frames / (monotonic() - start_time), "FPS")

    except OSError:  # See "try" notes above regarding rare I2C errors.
        print("Restarting")
        reload()

This example is based on a staple of the 8-bit demoscene days, where the goal was to create impressive animation when RAM and CPU cycles were scarce. The fire effect translates well to the bright colors and limited pixels of the LED matrix. It’s not based on real flame physics — mathematically it’s fairly crude and comments in the code below explain each step — but like those animated flame lights in stores, it does a reasonable job fooling the eye!

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory EyeLights_Fire/EyeLights_Fire_CircuitPython/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
FIRE EFFECT for Adafruit EyeLights (LED Glasses + Driver).
A demoscene classic that produces a cool analog-esque look with
modest means, iteratively scrolling and blurring raster data.
"""

import random
from supervisor import reload
import board
from busio import I2C
import adafruit_is31fl3741
from adafruit_is31fl3741.adafruit_ledglasses import LED_Glasses


# HARDWARE SETUP ---------

# Manually declare I2C (not board.I2C() directly) to access 1 MHz speed...
i2c = I2C(board.SCL, board.SDA, frequency=1000000)

# Initialize the IS31 LED driver, buffered for smoother animation
glasses = LED_Glasses(i2c, allocate=adafruit_is31fl3741.MUST_BUFFER)
glasses.show()  # Clear any residue on startup
glasses.global_current = 20  # Just middlin' bright, please


# INITIALIZE TABLES ------

# The raster data is intentionally one row taller than the LED matrix.
# Each frame, random noise is put in the bottom (off matrix) row. There's
# also an extra column on either side, to avoid needing edge clipping when
# neighboring pixels (left, center, right) are averaged later.
data = [[0] * (glasses.width + 2) for _ in range(glasses.height + 1)]
# (2D array where elements are accessed as data[y][x], initialized to 0)

# Each element in the raster is a single value representing brightness.
# A pre-computed lookup table maps these to RGB colors. This one happens
# to have 32 elements, but as we're not on an actual paletted hardware
# framebuffer it could be any size really (with suitable changes throughout).
gamma = 2.6
colormap = []
for n in range(32):
    n *= 3 / 31  #  0.0 <= n <= 3.0 from start to end of map
    if n <= 1:  #   0.0 <= n <= 1.0 : black to red
        r = n  #    r,g,b are initially calculated 0 to 1 range
        g = b = 0
    elif n <= 2:  # 1.0 <= n <= 2.0 : red to yellow
        r = 1
        g = n - 1
        b = 0
    else:  #        2.0 <= n <= 3.0 : yellow to white
        r = g = 1
        b = n - 2
    r = int((r ** gamma) * 255)  #               Gamma correction linearizes
    g = int((g ** gamma) * 255)  #               perceived brightness, then
    b = int((b ** gamma) * 255)  #               scale to 0-255 for LEDs and
    colormap.append((r << 16) | (g << 8) | b)  # store as 'packed' RGB color


# UTILITY FUNCTIONS -----


def interp(ring, led1, led2, level1, level2):
    """Linearly interpolate a range of brightnesses between two LEDs of
    one eyeglass ring, mapping through the global color table. LED range
    is non-inclusive; the first and last LEDs (which overlap matrix pixels)
    are not set. led2 MUST be > led1. LED indices may be >= 24 to 'wrap
    around' the seam at the top of the ring."""
    span = led2 - led1 + 1  #  Number of LEDs
    delta = level2 - level1  # Difference in brightness
    for led in range(led1 + 1, led2):  # For each LED in-between,
        ratio = (led - led1) / span  #   interpolate brightness level
        ring[led % 24] = colormap[min(31, int(level1 + delta * ratio))]


# MAIN LOOP -------------

while True:
    # The try/except here is because VERY INFREQUENTLY the I2C bus will
    # encounter an error when accessing the LED driver, whether from bumping
    # around the wires or sometimes an I2C device just gets wedged. To more
    # robustly handle the latter, the code will restart if that happens.
    try:

        # At the start of each frame, fill the bottom (off matrix) row
        # with random noise. To make things less strobey, old data from the
        # prior frame still has about 1/3 'weight' here. There's no special
        # real-world significance to the 85, it's just an empirically-
        # derived fudge factor that happens to work well with the size of
        # the color map.
        for x in range(1, 19):
            data[5][x] = 0.33 * data[5][x] + 0.67 * random.random() * 85
        # If this were actual SRS BZNS 31337 D3M0SC3N3 code, great care
        # would be taken to avoid floating-point math. But with few pixels,
        # and so this code might be less obtuse, a casual approach is taken.

        # Each row (except last) is then processed, top-to-bottom. This
        # order is important because it's an iterative algorithm...the
        # output of each frame serves as input to the next, and the steps
        # below (looking at the pixels below each row) are what makes the
        # "flames" appear to move "up."
        for y in range(5):  #         Current row of pixels
            y1 = data[y + 1]  #       One row down
            for x in range(1, 19):  # Skip left, right columns in data
                # Each pixel is sort of the average of the three pixels
                # under it (below left, below center, below right), but not
                # exactly. The below center pixel has more 'weight' than the
                # others, and the result is scaled to intentionally land
                # short, making each row bit darker as they move up.
                data[y][x] = (y1[x] + ((y1[x - 1] + y1[x + 1]) * 0.33)) * 0.35
                glasses.pixel(x - 1, y, colormap[min(31, int(data[y][x]))])

        # That's all well and good for the matrix, but what about the extra
        # LEDs in the rings? Since these don't align to the pixel grid,
        # rather than trying to extend the raster data and filter it in
        # somehow, we'll fill those arcs with colors interpolated from the
        # endpoints where rings and matrix intersect. Maybe not perfect,
        # but looks okay enough!
        interp(glasses.left_ring, 7, 17, data[4][8], data[4][1])
        interp(glasses.left_ring, 21, 29, data[0][2], data[2][8])
        interp(glasses.right_ring, 7, 17, data[4][18], data[4][11])
        interp(glasses.right_ring, 19, 27, data[2][11], data[0][17])

        glasses.show()  # Buffered mode MUST use show() to refresh matrix

    except OSError:  # See "try" notes above regarding rare I2C errors.
        print("Restarting")
        reload()

IT’S THE LAW: if it has pixels, we will animate blinking eyes on it. This is just the latest in that very long line of blinky things. Those LED rings were just begging for it, y’know?

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory EyeLights_Blinky_Eyes/EyeLights_Blinky_Eyes_CircuitPython/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
MOVE-AND-BLINK EYES for Adafruit EyeLights (LED Glasses + Driver).

I'd written a very cool squash-and-stretch effect for the eye movement,
but unfortunately the resolution and frame rate are such that the pupils
just look like circles regardless. I'm keeping it in despite the added
complexity, because CircuitPython devices WILL get faster, LED matrix
densities WILL improve, and this way the code won't require a re-write
at such a later time. It's a really adorable effect with enough pixels.
"""

import math
import random
import time
from supervisor import reload
import board
from busio import I2C
import adafruit_is31fl3741
from adafruit_is31fl3741.adafruit_ledglasses import LED_Glasses


# CONFIGURABLES ------------------------

eye_color = (255, 128, 0)  #      Amber pupils
ring_open_color = (75, 75, 75)  # Color of LED rings when eyes open
ring_blink_color = (50, 25, 0)  # Color of LED ring "eyelid" when blinking

radius = 3.4  # Size of pupil (3X because of downsampling later)

# Reading through the code, you'll see a lot of references to this "3X"
# space. What it's referring to is a bitmap that's 3 times the resolution
# of the LED matrix (i.e. 15 pixels tall instead of 5), which gets scaled
# down to provide some degree of antialiasing. It's why the pupils have
# soft edges and can make fractional-pixel motions.
# Because of the way the downsampling is done, the eyelid edge when drawn
# across the eye will always be the same hue as the pupils, it can't be
# set independently like the ring blink color.

gamma = 2.6  # For color adjustment. Leave as-is.


# CLASSES & FUNCTIONS ------------------


class Eye:
    """Holds per-eye positional data; each covers a different area of the
    overall LED matrix."""

    def __init__(self, left, xoff):
        self.left = left  #     Leftmost column on LED matrix
        self.x_offset = xoff  # Horizontal offset (3X space) to fixate

    def smooth(self, data, rect):
        """Scale bitmap (in 'data') to LED array, with smooth 1:3
        downsampling. 'rect' is a 4-tuple rect of which pixels get
        filtered (anything outside is cleared to 0), saves a few cycles."""
        # Quantize bounds rect from 3X space to LED matrix space.
        rect = (
            rect[0] // 3,  #       Left
            rect[1] // 3,  #       Top
            (rect[2] + 2) // 3,  # Right
            (rect[3] + 2) // 3,  # Bottom
        )
        for y in range(rect[1]):  # Erase rows above top
            for x in range(6):
                glasses.pixel(self.left + x, y, 0)
        for y in range(rect[1], rect[3]):  #  Each row, top to bottom...
            pixel_sum = bytearray(6)  #  Initialize row of pixel sums to 0
            for y1 in range(3):  # 3 rows of bitmap...
                row = data[y * 3 + y1]  # Bitmap data for current row
                for x in range(rect[0], rect[2]):  # Column, left to right
                    x3 = x * 3
                    # Accumulate 3 pixels of bitmap into pixel_sum
                    pixel_sum[x] += row[x3] + row[x3 + 1] + row[x3 + 2]
            # 'pixel_sum' will now contain values from 0-9, indicating the
            # number of set pixels in the corresponding section of the 3X
            # bitmap. 'colormap' expands the sum to 24-bit RGB space.
            for x in range(rect[0]):  # Erase any columns to left
                glasses.pixel(self.left + x, y, 0)
            for x in range(rect[0], rect[2]):  # Column, left to right
                glasses.pixel(self.left + x, y, colormap[pixel_sum[x]])
            for x in range(rect[2], 6):  # Erase columns to right
                glasses.pixel(self.left + x, y, 0)
        for y in range(rect[3], 5):  # Erase rows below bottom
            for x in range(6):
                glasses.pixel(self.left + x, y, 0)


# pylint: disable=too-many-locals
def rasterize(data, point1, point2, rect):
    """Rasterize an arbitrary ellipse into the 'data' bitmap (3X pixel
    space), given foci point1 and point2 and with area determined by global
    'radius' (when foci are same point; a circle). Foci and radius are all
    floating point values, which adds to the buttery impression. 'rect' is
    a 4-tuple rect of which pixels are likely affected. Data is assumed 0
    before arriving here; no clearing is performed."""

    dx = point2[0] - point1[0]
    dy = point2[1] - point1[1]
    d2 = dx * dx + dy * dy  # Dist between foci, squared
    if d2 <= 0:
        # Foci are in same spot - it's a circle
        perimeter = 2 * radius
        d = 0
    else:
        # Foci are separated - it's an ellipse.
        d = d2 ** 0.5  # Distance between foci
        c = d * 0.5  # Center-to-foci distance
        # This is an utterly brute-force way of ellipse-filling based on
        # the "two nails and a string" metaphor...we have the foci points
        # and just need the string length (triangle perimeter) to yield
        # an ellipse with area equal to a circle of 'radius'.
        # c^2 = a^2 - b^2  <- ellipse formula
        #   a = r^2 / b    <- substitute
        # c^2 = (r^2 / b)^2 - b^2
        # b = sqrt(((c^2) + sqrt((c^4) + 4 * r^4)) / 2)  <- solve for b
        b2 = ((c ** 2) + (((c ** 4) + 4 * (radius ** 4)) ** 0.5)) * 0.5
        # By my math, perimeter SHOULD be...
        # perimeter = d + 2 * ((b2 + (c ** 2)) ** 0.5)
        # ...but for whatever reason, working approach here is really...
        perimeter = d + 2 * (b2 ** 0.5)

    # Like I'm sure there's a way to rasterize this by spans rather than
    # all these square roots on every pixel, but for now...
    for y in range(rect[1], rect[3]):  # For each row...
        y5 = y + 0.5  #         Pixel center
        dy1 = y5 - point1[1]  # Y distance from pixel to first point
        dy2 = y5 - point2[1]  # " to second
        dy1 *= dy1  # Y1^2
        dy2 *= dy2  # Y2^2
        for x in range(rect[0], rect[2]):  # For each column...
            x5 = x + 0.5  #         Pixel center
            dx1 = x5 - point1[0]  # X distance from pixel to first point
            dx2 = x5 - point2[0]  # " to second
            d1 = (dx1 * dx1 + dy1) ** 0.5  # 2D distance to first point
            d2 = (dx2 * dx2 + dy2) ** 0.5  # " to second
            if (d1 + d2 + d) <= perimeter:
                data[y][x] = 1  # Point is inside ellipse


def gammify(color):
    """Given an (R,G,B) color tuple, apply gamma correction and return
    a packed 24-bit RGB integer."""
    rgb = [int(((color[x] / 255) ** gamma) * 255 + 0.5) for x in range(3)]
    return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]


def interp(color1, color2, blend):
    """Given two (R,G,B) color tuples and a blend ratio (0.0 to 1.0),
    interpolate between the two colors and return a gamma-corrected
    in-between color as a packed 24-bit RGB integer. No bounds clamping
    is performed on blend value, be nice."""
    inv = 1.0 - blend  # Weighting of second color
    return gammify([color1[x] * blend + color2[x] * inv for x in range(3)])


# HARDWARE SETUP -----------------------

# Manually declare I2C (not board.I2C() directly) to access 1 MHz speed...
i2c = I2C(board.SCL, board.SDA, frequency=1000000)

# Initialize the IS31 LED driver, buffered for smoother animation
glasses = LED_Glasses(i2c, allocate=adafruit_is31fl3741.MUST_BUFFER)
glasses.show()  # Clear any residue on startup
glasses.global_current = 20  # Just middlin' bright, please


# INITIALIZE TABLES & OTHER GLOBALS ----

# This table is for mapping 3x3 averaged bitmap values (0-9) to
# RGB colors. Avoids a lot of shift-and-or on every pixel.
colormap = []
for n in range(10):
    colormap.append(gammify([n / 9 * eye_color[x] for x in range(3)]))

# Pre-compute the Y position of 1/2 of the LEDs in a ring, relative
# to the 3X bitmap resolution, so ring & matrix animation can be aligned.
y_pos = []
for n in range(13):
    angle = n / 24 * math.pi * 2
    y_pos.append(10 - math.cos(angle) * 12)

# Pre-compute color of LED ring in fully open (unblinking) state
ring_open_color_packed = gammify(ring_open_color)

# A single pre-computed scanline of "eyelid edge during blink" can be
# stuffed into the 3X raster as needed, avoids setting pixels manually.
eyelid = (
    b"\x01\x01\x00\x01\x01\x00\x01\x01\x00" b"\x01\x01\x00\x01\x01\x00\x01\x01\x00"
)  # 2/3 of pixels set

# Initialize eye position and move/blink animation timekeeping
cur_pos = next_pos = (9, 7.5)  # Current, next eye position in 3X space
in_motion = False  #             True = eyes moving, False = eyes paused
blink_state = 0  #               0, 1, 2 = unblinking, closing, opening
move_start_time = move_duration = blink_start_time = blink_duration = 0

# Two eye objects. The first starts at column 1 of the matrix with its
# pupil offset by +2 (in 3X space), second at column 11 with -2 offset.
# The offsets make the pupils fixate slightly (converge on a point), so
# the two pupils aren't always aligned the same on the pixel grid, which
# would be conspicuously pixel-y.
eyes = [Eye(1, 2), Eye(11, -2)]

frames, start_time = 0, time.monotonic()  # For frames/second calculation


# MAIN LOOP ----------------------------

while True:
    # The try/except here is because VERY INFREQUENTLY the I2C bus will
    # encounter an error when accessing the LED driver, whether from bumping
    # around the wires or sometimes an I2C device just gets wedged. To more
    # robustly handle the latter, the code will restart if that happens.
    try:

        # The eye animation logic is a carry-over from like a billion
        # prior eye projects, so this might be comment-light.
        now = time.monotonic()  # 'Snapshot' the time once per frame

        # Blink logic
        elapsed = now - blink_start_time  # Time since start of blink event
        if elapsed > blink_duration:  #     All done with event?
            blink_start_time = now  #       A new one starts right now
            elapsed = 0
            blink_state += 1  #             Cycle closing/opening/paused
            if blink_state == 1:  #         Starting new blink...
                blink_duration = random.uniform(0.06, 0.12)
            elif blink_state == 2:  #       Switching closing to opening...
                blink_duration *= 2  #      Opens at half the speed
            else:  #                        Switching to pause in blink
                blink_state = 0
                blink_duration = random.uniform(0.5, 4)
        if blink_state:  #                  If currently in a blink...
            ratio = elapsed / blink_duration  # 0.0-1.0 as it closes
            if blink_state == 2:
                ratio = 1.0 - ratio  #          1.0-0.0 as it opens
            upper = ratio * 15 - 4  #       Upper eyelid pos. in 3X space
            lower = 23 - ratio * 8  #       Lower eyelid pos. in 3X space

        # Eye movement logic. Two points, 'p1' and 'p2', are the foci of an
        # ellipse. p1 moves from current to next position a little faster
        # than p2, creating a "squash and stretch" effect (frame rate and
        # resolution permitting). When motion is stopped, the two points
        # are at the same position.
        elapsed = now - move_start_time  # Time since start of move event
        if in_motion:  #                   Currently moving?
            if elapsed > move_duration:  # If end of motion reached,
                in_motion = False  #            Stop motion and
                p1 = p2 = cur_pos = next_pos  # Set to new position
                move_duration = random.uniform(0.5, 1.5)  # Wait this long
            else:  # Still moving
                # Determine p1, p2 position in time
                delta = (next_pos[0] - cur_pos[0], next_pos[1] - cur_pos[1])
                ratio = elapsed / move_duration
                if ratio < 0.6:  # First 60% of move time
                    # p1 is in motion
                    # Easing function: 3*e^2-2*e^3 0.0 to 1.0
                    e = ratio / 0.6  # 0.0 to 1.0
                    e = 3 * e * e - 2 * e * e * e
                    p1 = (cur_pos[0] + delta[0] * e, cur_pos[1] + delta[1] * e)
                else:  # Last 40% of move time
                    p1 = next_pos  # p1 has reached end position
                if ratio > 0.3:  # Last 60% of move time
                    # p2 is in motion
                    e = (ratio - 0.3) / 0.7  #       0.0 to 1.0
                    e = 3 * e * e - 2 * e * e * e  # Easing func.
                    p2 = (cur_pos[0] + delta[0] * e, cur_pos[1] + delta[1] * e)
                else:  # First 40% of move time
                    p2 = cur_pos  # p2 waits at start position
        else:  # Eye is stopped
            p1 = p2 = cur_pos  # Both foci at current eye position
            if elapsed > move_duration:  # Pause time expired?
                in_motion = True  #        Start up new motion!
                move_start_time = now
                move_duration = random.uniform(0.15, 0.25)
                angle = random.uniform(0, math.pi * 2)
                dist = random.uniform(0, 7.5)
                next_pos = (
                    9 + math.cos(angle) * dist,
                    7.5 + math.sin(angle) * dist * 0.8,
                )

        # Draw the raster part of each eye...
        for eye in eyes:
            # Allocate/clear the 3X bitmap buffer
            bitmap = [bytearray(6 * 3) for _ in range(5 * 3)]
            # Each eye's foci are offset slightly, to fixate toward center
            p1a = (p1[0] + eye.x_offset, p1[1])
            p2a = (p2[0] + eye.x_offset, p2[1])
            # Compute bounding rectangle (in 3X space) of ellipse
            # (min X, min Y, max X, max Y). Like the ellipse rasterizer,
            # this isn't optimal, but will suffice.
            bounds = (
                max(int(min(p1a[0], p2a[0]) - radius), 0),
                max(int(min(p1a[1], p2a[1]) - radius), 0, int(upper)),
                min(int(max(p1a[0], p2a[0]) + radius + 1), 18),
                min(int(max(p1a[1], p2a[1]) + radius + 1), 15, int(lower) + 1),
            )
            rasterize(bitmap, p1a, p2a, bounds)  # Render ellipse into buffer
            # If the eye is currently blinking, and if the top edge of the
            # eyelid overlaps the bitmap, draw a scanline across the bitmap
            # and update the bounds rect so the whole width of the bitmap
            # is scaled.
            if blink_state and upper >= 0:
                bitmap[int(upper)] = eyelid
                bounds = (0, int(upper), 18, bounds[3])
            eye.smooth(bitmap, bounds)  # 1:3 downsampling for eye

        # Matrix and rings share a few pixels. To make the rings take
        # precedence, they're drawn later. So blink state is revisited now...
        if blink_state:  # In mid-blink?
            for i in range(13):  # Half an LED ring, top-to-bottom...
                a = min(max(y_pos[i] - upper + 1, 0), 3)
                b = min(max(lower - y_pos[i] + 1, 0), 3)
                ratio = a * b / 9  # Proximity of LED to eyelid edges
                packed = interp(ring_open_color, ring_blink_color, ratio)
                glasses.left_ring[i] = glasses.right_ring[i] = packed
                if 0 < i < 12:
                    i = 24 - i  # Mirror half-ring to other side
                    glasses.left_ring[i] = glasses.right_ring[i] = packed
        else:
            glasses.left_ring.fill(ring_open_color_packed)
            glasses.right_ring.fill(ring_open_color_packed)

        glasses.show()  # Buffered mode MUST use show() to refresh matrix

    except OSError:  # See "try" notes above regarding rare I2C errors.
        print("Restarting")
        reload()

    frames += 1
    elapsed = time.monotonic() - start_time
    print(frames / elapsed)

You might’ve noticed the prior examples were all a bit code-heavy. If you’d just like to draw the animation, we’ve got a trick for that. There’s a tiny bit of CircuitPython code but it’s really quite simple. The rest is just BMP images like you can produce with most image editing software.

The ideas have been used in other projects already, so rather than reiterate we’ll simply point you to these other tutorials: this guide on “sprite sheet” animation is how the matrix animation works, and this one on bitmap-to-NeoPixel animation for the rings (the EyeLights LEDs aren’t NeoPixels, but the idea is the same). The images sizes here are different, that’s really the only change: 18x5 pixels per frame for the matrix, and 48 pixels tall for the rings.

Yes, the “time axis” for each is different. That was done so we could continue using the guides above for reference, and not need to explain the same principles in a new format.

Matrix Layout:

18x5 pixels, each frame stacked vertically, any height (RAM permitting).

The image should be saved as an indexed color BMP image, 4 or 8 bits per pixel.

LED Ring Layout:

48 pixels tall, any width (RAM permitting). The image should be saved as an indexed color BMP, 4 or 8 bits per pixel.

The matrix and rings share a few pixels in common. The rings are normally drawn “on top” and take precedence over the matrix.

If you just want one or the other (matrix or rings, not both), specify None for the corresponding filename in the source.

The matrix and rings do not need to be the same number of frames. The two parts work independently and it’s okay if the durations don’t match (or do, it’s all good).

Source Code and Example Images

Here’s the project source if you’d like to skim it. 

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory EyeLights_BMP_Animation/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
EyeLightsAnim example for Adafruit EyeLights (LED Glasses + Driver).
The accompanying eyelights_anim.py provides pre-drawn frame-by-frame
animation from BMP images. Sort of a catch-all for modest projects that may
want to implement some animation without having to express that animation
entirely in code. The idea is based upon two prior projects:

https://learn.adafruit.com/32x32-square-pixel-display/overview
learn.adafruit.com/circuit-playground-neoanim-using-bitmaps-to-animate-neopixels

The 18x5 matrix and the LED rings are regarded as distinct things, fed from
two separate BMPs (or can use just one or the other). The former guide above
uses the vertical axis for time (like a strip of movie film), while the
latter uses the horizontal axis for time (as in audio or video editing).
Despite this contrast, the same conventions are maintained here to avoid
conflicting explanations...what worked in those guides is what works here,
only the resolutions are different. See also the example BMPs.
"""

import time
import board
from busio import I2C
import adafruit_is31fl3741
from adafruit_is31fl3741.adafruit_ledglasses import LED_Glasses
from eyelights_anim import EyeLightsAnim


# HARDWARE SETUP -----------------------

i2c = I2C(board.SCL, board.SDA, frequency=1000000)

# Initialize the IS31 LED driver, buffered for smoother animation
glasses = LED_Glasses(i2c, allocate=adafruit_is31fl3741.MUST_BUFFER)
glasses.show()  # Clear any residue on startup
glasses.global_current = 20  # Just middlin' bright, please


# ANIMATION SETUP ----------------------

# Two indexed-color BMP filenames are specified: first is for the LED matrix
# portion, second is for the LED rings -- or pass None for one or the other
# if not animating that part. The two elements, matrix and rings, share a
# few LEDs in common...by default the rings appear "on top" of the matrix,
# or you can optionally pass a third argument of False to have the rings
# underneath. There's that one odd unaligned pixel between the two though,
# so this may only rarely be desirable.
anim = EyeLightsAnim(glasses, "matrix.bmp", "rings.bmp")


# MAIN LOOP ----------------------------

# This example just runs through a repeating cycle. If you need something
# else, like ping-pong animation, or frames based on a specific time, the
# anim.frame() function can optionally accept two arguments: an index for
# the matrix animation, and an index for the rings.

while True:
    anim.frame()  #     Advance matrix and rings by 1 frame and wrap around
    glasses.show()  #   Update LED matrix
    time.sleep(0.02)  # Pause briefly
# SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
EyeLightsAnim provides EyeLights LED glasses with pre-drawn frame-by-frame
animation from BMP images. Sort of a catch-all for modest projects that may
want to implement some animation without having to express that animation
entirely in code. The idea is based upon two prior projects:

https://learn.adafruit.com/32x32-square-pixel-display/overview
learn.adafruit.com/circuit-playground-neoanim-using-bitmaps-to-animate-neopixels

The 18x5 matrix and the LED rings are regarded as distinct things, fed from
two separate BMPs (or can use just one or the other). The former guide above
uses the vertical axis for time (like a strip of movie film), while the
latter uses the horizontal axis for time (as in audio or video editing).
Despite this contrast, the same conventions are maintained here to avoid
conflicting explanations...what worked in those guides is what works here,
only the resolutions are different."""

import displayio
import adafruit_imageload


def gamma_adjust(palette):
    """Given a color palette that was returned by adafruit_imageload, apply
    gamma correction and place results back in original palette. This makes
    LED brightness and colors more perceptually linear, to better match how
    the source BMP might've appeared on screen."""

    for index, entry in enumerate(palette):
        palette[index] = sum(
            [
                int(((((entry >> shift) & 0xFF) / 255) ** 2.6) * 255 + 0.5) << shift
                for shift in range(16, -1, -8)
            ]
        )


class EyeLightsAnim:
    """Class encapsulating BMP image-based frame animation for the matrix
    and rings of an LED_Glasses object."""

    def __init__(self, glasses, matrix_filename, ring_filename, rings_on_top=True):
        """Constructor for EyeLightsAnim. Accepts an LED_Glasses object and
        filenames for two indexed-color BMP images: first is a "sprite
        sheet" for animating on the matrix portion of the glasses, second is
        a pixels-over-time graph for the rings portion. Either filename may
        be None if not used. Because the matrix and rings share some pixels
        in common, the last argument determines the "stacking order" - which
        of the two bitmaps is drawn later or "on top." Default of True
        places the rings over the matrix, False gives the matrix priority.
        It's possible to use transparent palette indices but that may be
        more trouble than it's worth."""

        self.glasses = glasses
        self.matrix_bitmap = self.ring_bitmap = None
        self.rings_on_top = rings_on_top

        if matrix_filename:
            self.matrix_bitmap, self.matrix_palette = adafruit_imageload.load(
                matrix_filename, bitmap=displayio.Bitmap, palette=displayio.Palette
            )
            if (self.matrix_bitmap.width < glasses.width) or (
                self.matrix_bitmap.height < glasses.height
            ):
                raise ValueError("Matrix bitmap must be at least 18x5 pixels")
            gamma_adjust(self.matrix_palette)
            self.tiles_across = self.matrix_bitmap.width // glasses.width
            self.tiles_down = self.matrix_bitmap.height // glasses.height
            self.matrix_frames = self.tiles_across * self.tiles_down
            self.matrix_frame = self.matrix_frames - 1

        if ring_filename:
            self.ring_bitmap, self.ring_palette = adafruit_imageload.load(
                ring_filename, bitmap=displayio.Bitmap, palette=displayio.Palette
            )
            if self.ring_bitmap.height < 48:
                raise ValueError("Ring bitmap must be at least 48 pixels tall")
            gamma_adjust(self.ring_palette)
            self.ring_frames = self.ring_bitmap.width
            self.ring_frame = self.ring_frames - 1

    def draw_matrix(self, matrix_frame=None):
        """Draw the matrix portion of EyeLights from one frame of the matrix
        bitmap "sprite sheet." Can either request a specific frame index
        (starting from 0), or pass None (or no arguments) to advance by one
        frame, "wrapping around" to beginning if needed. For internal use by
        library; user code should call frame(), not this function."""

        if matrix_frame:  # Go to specific frame
            self.matrix_frame = matrix_frame
        else:  # Advance one frame forward
            self.matrix_frame += 1
        self.matrix_frame %= self.matrix_frames  # Wrap to valid range

        xoffset = self.matrix_frame % self.tiles_across * self.glasses.width
        yoffset = self.matrix_frame // self.tiles_across * self.glasses.height

        for y in range(self.glasses.height):
            y1 = y + yoffset
            for x in range(self.glasses.width):
                idx = self.matrix_bitmap[x + xoffset, y1]
                if not self.matrix_palette.is_transparent(idx):
                    self.glasses.pixel(x, y, self.matrix_palette[idx])

    def draw_rings(self, ring_frame=None):
        """Draw the rings portion of EyeLights from one frame of the rings
        bitmap graph. Can either request a specific frame index (starting
        from 0), or pass None (or no arguments) to advance by one frame,
        'wrapping around' to beginning if needed. For internal use by
        library; user code should call frame(), not this function."""

        if ring_frame:  # Go to specific frame
            self.ring_frame = ring_frame
        else:  # Advance one frame forward
            self.ring_frame += 1
        self.ring_frame %= self.ring_frames  # Wrap to valid range

        for y in range(24):
            idx = self.ring_bitmap[self.ring_frame, y]
            if not self.ring_palette.is_transparent(idx):
                self.glasses.left_ring[y] = self.ring_palette[idx]
            idx = self.ring_bitmap[self.ring_frame, y + 24]
            if not self.ring_palette.is_transparent(idx):
                self.glasses.right_ring[y] = self.ring_palette[idx]

    def frame(self, matrix_frame=None, ring_frame=None):
        """Draw one frame of animation to the matrix and/or rings portions
        of EyeLights. Frame index (starting from 0) for matrix and rings
        respectively can be passed as arguments, or either/both may be None
        to advance by one frame, 'wrapping around' to beginning if needed.
        Because some pixels are shared in common between matrix and rings,
        the "stacking order" -- which of the two appears "on top", is
        specified as an argument to the constructor."""

        if self.matrix_bitmap and self.rings_on_top:
            self.draw_matrix(matrix_frame)

        if self.ring_bitmap:
            self.draw_rings(ring_frame)

        if self.matrix_bitmap and not self.rings_on_top:
            self.draw_matrix(matrix_frame)
This example requires CircuitPython 7.2.0-alpha.1 or later.

CircuitPython includes DisplayIO a native library for showing text, bitmaps, animations and more. An LED matrix driven by an IS31FL3741 chip, like is found on the Adafruit EyeLights LED Glasses, supports DisplayIO.

The example below demonstrates how to set up the glasses to be a DisplayIO device. The example code scrolls text across the glasses. See the DisplayIO learn guide for more examples of what you can do with DisplayIO.

The following code block is responsible for initializing the display.

displayio.release_displays()
i2c = busio.I2C(board.SCL, board.SDA, frequency=1000000)
is31 = is31fl3741.IS31FL3741(i2c=i2c)
is31_framebuffer = is31fl3741.IS31FL3741_FrameBuffer(
    is31, 54, 15, glassesmatrix_ledmap, scale=True, gamma=True
)
display = framebufferio.FramebufferDisplay(is31_framebuffer)

The IS31FL3741_FrameBuffer class has a keyword scale that is worth explanation. Due to the fact the EyeLights are low resolution, when the scale option is set to True, the DisplayIO canvas created is 3 times larger then the display's physical size. For the EyeLight Glasses with a physical size of 18 x 5 this means the internal DisplayIO canvas is 54 x 15 pixels. When the display is refreshed on the physical device, the internal canvas is averaged and scaled down to match the physical device size. This allows for the illusion of a higher resolution then actually exists, useful for displaying text.

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory IS31FL3741_DisplayIO/scrolling_text/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image.

CIRCUITPY
# SPDX-FileCopyrightText: 2022 Mark Komus
#
# SPDX-License-Identifier: MIT

import random
import time
import board
import busio
import displayio
import framebufferio
import is31fl3741
from adafruit_is31fl3741.led_glasses_map import glassesmatrix_ledmap
from adafruit_display_text import label
from adafruit_bitmap_font import bitmap_font

# List of possible messages to display.
MESSAGES = (
    "DISPLAYIO AMAZES",
    "CIRCUITPYTHON RULES",
    "HELLO WORLD!",
)

TEXT_COLOR = (220, 210, 0) # Yellow

# Remove any existing displays
displayio.release_displays()

# Initialize the LED Glasses
#
# In this example scale is set to True. When True the logical display is
# three times the physical display size and scaled down to allow text to
# look more natural for small display sizes. Hence the display is created
# as 54x15 when the physical display is 18x5.
#
i2c = busio.I2C(board.SCL, board.SDA, frequency=1000000)
is31 = is31fl3741.IS31FL3741(i2c=i2c)
is31_framebuffer = is31fl3741.IS31FL3741_FrameBuffer(
    is31, 54, 15, glassesmatrix_ledmap, scale=True, gamma=True
)
display = framebufferio.FramebufferDisplay(is31_framebuffer, auto_refresh=True)

# Dim the display. Full brightness is BRIGHT
is31_framebuffer.brightness = 0.2

# Load the font to be used - scrolly only has upper case letters
font = bitmap_font.load_font("/fonts/scrolly.bdf")

# Set up the displayio elements
text_area = label.Label(font, text="", color=TEXT_COLOR)
text_area.y = 8
group = displayio.Group()
group.append(text_area)
display.root_group = group

# Continue to scroll messages forever
while True:
    # Pick a random message to display
    text_area.text = random.choice(MESSAGES)

    # Reset the text to start just off the right side
    x = display.width
    text_area.x = x

    # Determine the width of the message to scroll
    width = text_area.bounding_box[2]

    # Scroll the message across the glasses
    while x != -width:
        x = x - 1
        text_area.x = x
        time.sleep(0.05) # adjust to change scrolling speed
This example requires CircuitPython 7.2.0-alpha.1 or later.

The perfect project to get yourself shown on the jumbotron at the next big game. Cheer on your team while scrolling encouraging messages across the LED glasses matrix. Customize the text and ring light colors to match your team colors.

And for when your team scores a run, goal, touchdown, etc. and you want to celebrate, press the button on the top of the LED glasses driver board which trigger an elaborate celebration. A special message scrolls across the display and the eye lights animate using the Adafruit_LED_Library.

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory IS31FL3741_DisplayIO/sports_glasses/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

CIRCUITPY
# SPDX-FileCopyrightText: 2022 Mark Komus
#
# SPDX-License-Identifier: MIT

import random
import time
import board
import busio
import digitalio
import displayio
import framebufferio
import is31fl3741
from adafruit_is31fl3741.is31fl3741_PixelBuf import IS31FL3741_PixelBuf
from adafruit_is31fl3741.led_glasses_map import (
    glassesmatrix_ledmap_no_ring,
    left_ring_map_no_inner,
    right_ring_map_no_inner,
)
from adafruit_display_text import label
from adafruit_bitmap_font import bitmap_font
from adafruit_led_animation.animation.chase import Chase
from adafruit_debouncer import Debouncer

# List of possible messages to display. Randomly chosen
MESSAGES = (
    "GO TEAM GO",
    "WE ARE NUMBER 1",
    "I LIKE THE HALFTIME SHOW",
)

# Colors used for the text and ring lights
BLUE_TEXT = (0, 20, 255)
BLUE_RING = (0, 10, 120)
YELLOW_TEXT = (220, 210, 0)
YELLOW_RING = (150, 140, 0)


def ScrollMessage(text, color, repeat):
    """Scroll a message across the eyeglasses a set number of times"""
    text_area.text = text
    text_area.color = color

    # Start the message just off the side of the glasses
    x = display.width
    text_area.x = x

    # Determine the width of the message to scroll
    width = text_area.bounding_box[2]

    for _ in range(repeat):
        while x != -width:
            x = x - 1
            text_area.x = x

            # Update the switch and if it has been pressed abort scrolling this message
            switch.update()
            if not switch.value:
                return

            time.sleep(0.025) # adjust to change scrolling speed
        x = display.width


def Score(text, color, ring_color, repeat):
    """Show a scrolling text message and animated effects on the eye rings.
    The messages scrolls left to right, then right to left while the eye rings
    are animated using the adafruit_led_animation library."""

    # Set up a led animation chase sequence for both eyelights
    chase_left = Chase(left_eye, speed=0.11, color=ring_color, size=8, spacing=4)
    chase_right = Chase(right_eye, speed=0.07, color=ring_color, size=8, spacing=4)

    text_area.text = text
    text_area.color = color

    x = display.width
    text_area.x = x

    width = text_area.bounding_box[2]

    for _ in range(repeat):
        # Scroll the text left and animate the eyes
        while x != -width:
            x = x - 1
            text_area.x = x
            chase_left.animate()
            chase_right.animate()
            time.sleep(0.008) # adjust to change scrolling speed
        # Scroll the text right and animate the eyes
        while x != display.width:
            x = x + 1
            text_area.x = x
            chase_left.animate()
            chase_right.animate()
            time.sleep(0.008) # adjust to change scrolling speed


# Remove any existing displays
displayio.release_displays()

# Set up the top button used to trigger a special message when pressed
switch_pin = digitalio.DigitalInOut(board.SWITCH)
switch_pin.direction = digitalio.Direction.INPUT
switch_pin.pull = digitalio.Pull.UP
switch = Debouncer(switch_pin)

# Initialize the LED Glasses
#
# In this example scale is set to True. When True the logical display is
# three times the physical display size and scaled down to allow text to
# look more natural for small display sizes. Hence the display is created
# as 54x15 when the physical display is 18x5.
#
i2c = busio.I2C(board.SCL, board.SDA, frequency=1000000)
is31 = is31fl3741.IS31FL3741(i2c=i2c)
is31_framebuffer = is31fl3741.IS31FL3741_FrameBuffer(
    is31, 54, 15, glassesmatrix_ledmap_no_ring, scale=True, gamma=True
)
display = framebufferio.FramebufferDisplay(is31_framebuffer, auto_refresh=True)

# Set up the left and right eyelight rings
# init is set to False as the IS31FL3741_FrameBuffer has already initialized the IS31FL3741 driver
left_eye = IS31FL3741_PixelBuf(
    is31, left_ring_map_no_inner, init=False, auto_write=False
)
right_eye = IS31FL3741_PixelBuf(
    is31, right_ring_map_no_inner, init=False, auto_write=False
)

# Dim the display. Full brightness is BRIGHT
is31_framebuffer.brightness = 0.2

# Load the font to be used - scrolly only has upper case letters
font = bitmap_font.load_font("/fonts/scrolly.bdf")

# Set up the display elements
text_area = label.Label(font, text="", color=(0, 0, 0))
text_area.y = 8
group = displayio.Group()
group.append(text_area)
display.root_group = group

while True:
    # Run the debouncer code to get the updated switch value
    switch.update()

    # If the switch has been pressed interrupt start a special message
    if not switch.value:
        Score("SCORE!", YELLOW_TEXT, BLUE_RING, 2)

    # If the switch is not pressed pick a random message and scroll it
    left_eye.fill(BLUE_RING)
    right_eye.fill(BLUE_RING)
    left_eye.show()
    right_eye.show()
    ScrollMessage(random.choice(MESSAGES), YELLOW_TEXT, 2)

You can install the Adafruit Bluefruit nRF52 BSP (Board Support Package) in two steps:

nRF52 support requires at least Arduino IDE version 1.8.15! Please make sure you have an up to date version before proceeding with this guide!
Please consult the FAQ section at the bottom of this page if you run into any problems installing or using this BSP!

1. BSP Installation

Recommended: Installing the BSP via the Board Manager

  • Download and install the Arduino IDE (At least v1.8)
  • Start the Arduino IDE
  • Go into Preferences
  • Add https://adafruit.github.io/arduino-board-index/package_adafruit_index.json as an 'Additional Board Manager URL' (see image below)
  • Restart the Arduino IDE
  • Open the Boards Manager option from the Tools -> Board menu and install 'Adafruit nRF52 by Adafruit' (see image below)

It will take up to a few minutes to finish installing the cross-compiling toolchain and tools associated with this BSP.

The delay during the installation stage shown in the image below is normal, please be patient and let the installation terminate normally:

Once the BSP is installed, select

  • Adafruit Bluefruit nRF52832 Feather (for the nRF52 Feather)
  • Adafruit Bluefruit nRF52840 Feather Express (for the nRF52840 Feather)
  • Adafruit ItsyBitsy nRF52840 (for the Itsy '850)
  • Adafruit Circuit Playground Bluefruit (for the CPB)
  • etc...

from the Tools -> Board menu, which will update your system config to use the right compiler and settings for the nRF52:

2. LINUX ONLY: adafruit-nrfutil Tool Installation

adafruit-nrfutil is a modified version of Nordic's nrfutil, which is used to flash boards using the built in serial bootloader. It is originally written for python2, but have been migrated to python3 and renamed to adafruit-nrfutil since BSP version 0.8.5.

This step is only required on Linux, pre-built binaries of adafruit-nrfutil for Windows and MacOS are already included in the BSP. That should work out of the box for most setups.

Install python3 if it is not installed in your system already

$ sudo apt-get install python3

Then run the following command to install the tool from PyPi

$ pip3 install --user adafruit-nrfutil

Add pip3 installation dir to your PATH if it is not added already. Make sure adafruit-nrfutil can be executed in terminal by running

$ adafruit-nrfutil version
adafruit-nrfutil version 0.5.3.post12

3. Update the bootloader (nRF52832 ONLY)

To keep up with Nordic's SoftDevice advances, you will likely need to update your bootloader if you are using the original nRF52832 based Bluefruit nRF52 Feather boards.

Follow this link for instructions on how to do that

This step ISN'T required for the newer nRF52840 Feather Express, which has a different bootloader entirely!

Advanced Option: Manually Install the BSP via 'git'

If you wish to do any development against the core codebase (generate pull requests, etc.), you can also optionally install the Adafruit nRF52 BSP manually using 'git', as decribed below:

Adafruit nRF52 BSP via git (for core development and PRs only)

  1. Install BSP via Board Manager as above to install compiler & tools.
  2. Delete the core folder nrf52 installed by Board Manager in Adruino15, depending on your OS. It could be
    macOS~/Library/Arduino15/packages/adafruit/hardware/nrf52
    Linux~/.arduino15/packages/adafruit/hardware/nrf52
    Windows%APPDATA%\Local\Arduino15\packages\adafruit\hardware\nrf52
  3. Go to the sketchbook folder on your command line, which should be one of the following:
    macOS: ~/Documents/Arduino
    Linux: ~/Arduino
    Windows: ~/Documents/Arduino
  4. Create a folder named hardware/Adafruit, if it does not exist, and change directories into it.
  5. Clone the Adafruit_nRF52_Arduino repo in the folder described in step 2:
    git clone --recurse-submodules [email protected]:adafruit/Adafruit_nRF52_Arduino.git
  6. This should result in a final folder name like ~/Documents/Arduino/hardware/Adafruit/Adafruit_nRF52_Arduino (macOS).

  7. Restart the Arduino IDE

Once you have the Bluefruit nRF52 BSP setup on your system, you need to select the appropriate board, which will determine the compiler and expose some new menus options:

1. Select the Board Target

  • Go to the Tools menu
  • Select Tools > Board > Adafruit Bluefruit nRF52 Feather for nRF52832-based boards
  • Select Tools > Board > Adafruit Bluefruit nRF52840 Feather Express for nRF52840-based boards
  • Select Tools > Board > Adafruit CLUE for the Adafruit CLUE

2. Select the USB CDC Serial Port

Finally, you need to set the serial port used by Serial Monitor and the serial bootloader:

  • Go to Tools > Port and select the appropriate device

2.1 Download & Install CP2104 Driver (nRF52832)

For Feather nRF52832 If you don't see the serial ports device listed, you may need to install the SiLabs CP2104 driver on your system.

On MacOS If you see this dialog message while installing driver

On MacOS If you see this dialog message while installing driver, System Extension Blocked

 

And cannot find the serial port of CP2104, it is highly possible that driver is blocked.

To enable it go to System Preferences -> Security & Privacy and click allow if you see Silab in the developer name.

After installing cp210x driver, If feather nRF52832 appear as 2 serial ports on your macos. e.g "/dev/cu.SLAB_USBtoUART" and "/dev/cu.usbserial-1234", the correct port to use is "/dev/cu.usbserial-1234"

2.2 Download & Install Adafruit Driver (nRF52840 Windows)

For Feather nRF52840, If you are using Windows, you will need to follows Windows Driver Installation to download and install driver.

3. Update the bootloader (nRF52832 Feather Only)

To keep up with Nordic's SoftDevice advances, you will likely need to update your bootloader

Follow this link for instructions on how to do that

This step is only necessary on the nRF52832-based devices, NOT on the newer nRF52840 Feather Express.

4. Run a Test Sketch

At this point, you should be able to run a test sketch from the Examples folder, or just flash the following blinky code from the Arduino IDE:

#include <Adafruit_TinyUSB.h> is required when using with nRF52840 based board for Serial port implementation.
#if defined(USE_TINYUSB)
#include <Adafruit_TinyUSB.h> // for Serial
#endif

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

This will blink the red LED beside the USB port on the Feather, or the red LED labeled "LED" by the corner of the USB connector on the CLUE.

Arduino sketch failed to compile with error: ld returned 1 exit status

If the sketch fails to compile and reports an error message like this:

collect2.exe: error: ld returned 1 exit status

exit status 1

Compilation error: exit status 1

Look in the rest of the compile message output (turn on verbose output if needed) and check if the actual error(s) look something like:

undefined reference to `Adafruit_USBD_CDC::begin(unsigned long)

undefined reference to `Adafruit_USBD_CDC::write(unsigned char const*, unsigned int)

If so, the required #include is missing. See the example code above and add the required lines to your sketch.

If Arduino failed to upload sketch to the Feather

If you get this error:

Timed out waiting for acknowledgement from device.

Failed to upgrade target. Error is: No data received on serial port. Not able to proceed.
Traceback (most recent call last):
  File "nordicsemi\__main__.py", line 294, in serial
  File "nordicsemi\dfu\dfu.py", line 235, in dfu_send_images
  File "nordicsemi\dfu\dfu.py", line 203, in _dfu_send_image
  File "nordicsemi\dfu\dfu_transport_serial.py", line 155, in send_init_packet
  File "nordicsemi\dfu\dfu_transport_serial.py", line 243, in send_packet
  File "nordicsemi\dfu\dfu_transport_serial.py", line 282, in get_ack_nr
nordicsemi.exceptions.NordicSemiException: No data received on serial port. Not able to proceed.

This is probably caused by the bootloader version mismatched on your feather and installed BSP. Due to the difference in flash layout (more details) and Softdevice API (which is bundled with bootloader), sketch built with selected bootloader can only upload to board having the same version. In short, you need to upgrade/burn bootloader to match on your Feather, follow above Update The Bootloader guide

It only has to be done once to update your Feather

On Linux I'm getting 'arm-none-eabi-g++: no such file or directory', even though 'arm-none-eabi-g++' exists in the path specified. What should I do?

This is probably caused by a conflict between 32-bit and 64-bit versions of the compiler, libc and the IDE. The compiler uses 32-bit binaries, so you also need to have a 32-bit version of libc installed on your system (details). Try running the following commands from the command line to resolve this:

sudo dpkg --add-architecture i386


sudo apt-get update


sudo apt-get install libc6:i386

We made a few starter projects to demonstrate features of the EyeLights LED Glasses and Driver board such as the accelerometer or microphone input. They’re not highly polished demos, but show how to set up the basics. Consider them starting points and fuel for your own creative ideas.

The next few pages showcase Arduino examples. If CircuitPython is more your style, we have a separate starter projects section for that.

All of these rely on the Adafruit_IS31FL3741 library for Arduino, then each may require one or two other libraries. These can be found and installed with the Arduino Library manager.

The Adafruit_IS31FL3741 library includes a few more introductory examples that work on the EyeLights LED Glasses — these all have names starting with “glassesdemo”.

Don’t be alarmed by the size of the code below…it’s actually more comments than code, to walk you through what it’s doing.

This example demonstrates some basics of using the LED rings and the driver board’s accelerometer.

Although the driver board has a clicky button that can be used for input (PIN_BUTTON1 or digital pin 4 in Arduino), this is one of those “make you think” projects: what if, instead explicitly interacting with devices, they anticipated our needs and did what we want? This is normally a pair of festive Halloween glasses…but when you look down (as when navigating steps or looking in your candy bag) it transitions into bright headlights. Look up again and it’s back to Halloween mode.

This also demonstrates the accelerometer’s tap-detect function (just tap the glasses to select among different color schemes) and smooth “easing” interpolation between colors that gives things a touch of luxury.

The driver board is normally mounted on an eyeglass frame’s temple, with the STEMMA QT connector toward the front. If the code’s look-down behavior seems wrong, it may be that the glasses are folded or the board isn’t mounted the right way.

In addition to the Adafruit_IS31FL3741 library, this also requires the Adafruit_Sensor and Adafruit_LIS3DH libraries.

There’s also a CircuitPython version of this project on an earlier page.

If you’d prefer a pre-compiled binary: download this .UF2 file. Connect the EyeLights driver board to your computer with a USB cable, set the power switch “on,” double-tap the reset button and a small flash drive named GLASSESBOOT appears. Then drag the .UF2 file to GLASSESBOOT and wait several seconds while it copies.

// SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
//
// SPDX-License-Identifier: MIT

/*
ACCELEROMETER INPUT DEMO: while the LED Glasses Driver has a perfectly
good clicky button for input, this code shows how one might instead use
the onboard accelerometer for interactions*.

Worn normally, the LED rings are simply lit a solid color.
TAP the eyeglass frames to cycle among a list of available colors.
LOOK DOWN to light the LED rings bright white -- for navigating steps
or finding the right key. LOOK BACK UP to return to solid color.
This uses only the rings, not the matrix portion.

* Like, if you have big ol' monster hands, that little button can be
  hard to click, y'know?
*/

#include <Adafruit_IS31FL3741.h> // For LED driver
#include <Adafruit_LIS3DH.h>     // For accelerometer
#include <Adafruit_Sensor.h>     // For m/s^2 accel units

Adafruit_LIS3DH             accel;
Adafruit_EyeLights_buffered glasses; // Buffered for smooth animation

// Here's a list of colors that we cycle through when tapped, specified
// as {R,G,B} values from 0-255. These are intentionally a bit dim --
// both to save battery and to make the "ground light" mode more dramatic.
// Rather than primary color red/green/blue sequence which is just so
// over-done at this point, let's use some HALLOWEEN colors!
uint8_t colors[][3] = {
  {27, 9, 0},  // Orange
  {12, 0, 24}, // Purple
  {5, 31, 0},  // Green
};
#define NUM_COLORS (sizeof colors / sizeof colors[0]) // List length
uint8_t looking_down_color[] = {255, 255, 255};       // Max white

uint8_t  color_index = 0;   // Begin at first color in list
uint8_t *target_color;      // Pointer to color we're aiming for
float    interpolated_color[] = {0.0, 0.0, 0.0}; // Current color along the way
float    filtered_y;        // De-noised accelerometer reading
bool     looking_down;      // Set true when glasses are oriented downward
sensors_event_t event;      // For accelerometer conversion
uint32_t last_tap_time = 0; // For accelerometer tap de-noising

// Crude error handler, prints message to Serial console, flashes LED
void err(char *str, uint8_t hz) {
  Serial.println(str);
  pinMode(LED_BUILTIN, OUTPUT);
  for (;;) digitalWrite(LED_BUILTIN, (millis() * hz / 500) & 1);
}

void setup() { // Runs once at program start...

  // Initialize hardware
  Serial.begin(115200);
  if (! accel.begin())   err("LIS3DH not found", 5);
  if (! glasses.begin()) err("IS3741 not found", 2);

  // Configure accelerometer and get initial state
  accel.setClick(1, 100); // Set threshold for single tap
  accel.getEvent(&event); // Current accel in m/s^2
  // Check accelerometer to see if we've started in the looking-down state,
  // set the target color (what we're aiming for) appropriately. Only the
  // Y axis is needed for this.
  filtered_y = event.acceleration.y;
  looking_down = (filtered_y > 5.0);
  // If initially looking down, aim for the look-down color,
  // else aim for the first item in the color list.
  target_color = looking_down ? looking_down_color : colors[color_index];

  // Configure glasses for max brightness, enable output
  glasses.setLEDscaling(0xFF);
  glasses.setGlobalCurrent(0xFF);
  glasses.enable(true);
}

void loop() { // Repeat forever...

  // interpolated_color blends from the prior to the next ("target")
  // LED ring colors, with a pleasant ease-out effect.
  for(uint8_t i=0; i<3; i++) { // R, G, B
    interpolated_color[i] = interpolated_color[i] * 0.97 + target_color[i] * 0.03;
  }
  // Convert separate red, green, blue to "packed" 24-bit RGB value
  uint32_t rgb = ((int)interpolated_color[0] << 16) |
                 ((int)interpolated_color[1] << 8) |
                  (int)interpolated_color[2];
  // Fill both rings with packed color, then refresh the LEDs.
  glasses.left_ring.fill(rgb);
  glasses.right_ring.fill(rgb);
  glasses.show();

  // The look-down detection only needs the accelerometer's Y axis.
  // This works with the Glasses Driver mounted on either temple,
  // with the glasses arms "open" (as when worn).
  accel.getEvent(&event);
  // Smooth the accelerometer reading the same way RGB colors are
  // interpolated. This avoids false triggers from jostling around.
  filtered_y = filtered_y * 0.97 + event.acceleration.y * 0.03;

  // The threshold between "looking down" and "looking up" depends
  // on which of those states we're currently in. This is an example
  // of hysteresis in software...a change of direction requires a
  // little extra push before it takes, which avoids oscillating if
  // there was just a single threshold both ways.
  if (looking_down) {       // Currently in the looking-down state...
    (void)accel.getClick(); // Discard any taps while looking down
    if (filtered_y < 3.5) { // Have we crossed the look-up threshold?
      target_color = colors[color_index]; // Back to list color
      looking_down = false;               // We're looking up now!
    }
  } else {                  // Currently in the looking-up state...
    if (filtered_y > 5.0) { // Crossed the look-down threshold?
      target_color = looking_down_color; // Aim for white
      looking_down = true;               // We're looking down now!
    } else if (accel.getClick()) {
      // No look up/down change, but the accelerometer registered
      // a tap. Compare this against the last time we sensed one,
      // and only do things if it's been more than half a second.
      // This avoids spurious double-taps that can occur no matter
      // how carefully the tap threshold was set.
      uint32_t now = millis();
      uint32_t elapsed = now - last_tap_time;
      if (elapsed > 500) {
        // A good tap was detected. Cycle to the next color in
        // the list and note the time of this tap.
        color_index = (color_index + 1) % NUM_COLORS;
        target_color = colors[color_index];
        last_tap_time = now;
      }
    }
  }
}

This is another example demonstrating the LED rings and accelerometer, not the matrix portion of the glasses yet. The rings swivel and spin in response to movement, as if filled with liquid, or like jiggling plastic “googly eyes.” The idea and math are adapted from an earlier project, Bill Earl's STEAM-Punk Goggles.

The driver board is normally mounted on an eyeglass frame’s temple, with the STEMMA QT connector toward the front. If gravity’s behavior seems wrong, it may be that the glasses are folded or the board isn’t mounted right.

In addition to the Adafruit_IS31FL3741 library, this also requires the Adafruit_Sensor and Adafruit_LIS3DH libraries.

There’s also a CircuitPython version of this project on an earlier page.

If you’d prefer a pre-compiled binary: download this .UF2 file. Connect the EyeLights driver board to your computer with a USB cable, set the power switch “on,” double-tap the reset button and a small flash drive named GLASSESBOOT appears. Then drag the .UF2 file to GLASSESBOOT and wait several seconds while it copies.

// SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
//
// SPDX-License-Identifier: MIT

/*
GOOGLY EYES for Adafruit EyeLight LED glasses + driver. Pendulum physics
simulation using accelerometer and math. This uses only the rings, not the
matrix portion. Adapted from Bill Earl's STEAM-Punk Goggles project:
https://learn.adafruit.com/steam-punk-goggles
*/

#include <Adafruit_IS31FL3741.h> // For LED driver
#include <Adafruit_LIS3DH.h>     // For accelerometer
#include <Adafruit_Sensor.h>     // For m/s^2 accel units

Adafruit_LIS3DH             accel;
Adafruit_EyeLights_buffered glasses; // Buffered for smooth animation

// A small class for our pendulum simulation.
class Pendulum {
public:
  // Constructor. Pass pointer to EyeLights ring, and a 3-byte color array.
  Pendulum(Adafruit_EyeLights_Ring_buffered *r, uint8_t *c) {
    ring  = r;
    color = c;
    // Initial pendulum position, plus axle friction, are randomized
    // so rings don't spin in perfect lockstep.
    angle = random(1000);
    momentum = 0.0;
    friction = 0.94 + random(300) * 0.0001; // Inverse friction, really
  }

  // Given a pixel index (0-23) and a scaling factor (0.0-1.0),
  // interpolate between LED "off" color (at 0.0) and this item's fully-
  // lit color (at 1.0) and set pixel to the result.
  void interp(uint8_t pixel, float scale) {
    // Convert separate red, green, blue to "packed" 24-bit RGB value
    ring->setPixelColor(pixel,
        (int(color[0] * scale) << 16) |
        (int(color[1] * scale) <<  8) |
         int(color[2] * scale));
  }

  // Given an accelerometer reading, run one cycle of the pendulum
  // physics simulation and render the corresponding LED ring.
  void iterate(sensors_event_t &event) {
    // Minus here is because LED pixel indices run clockwise vs. trigwise.
    // 0.006 is just an empirically-derived scaling fudge factor that looks
    // good; smaller values for more sluggish rings, higher = more twitch.
    momentum =  momentum * friction - 0.006 *
      (cos(angle) * event.acceleration.z +
       sin(angle) * event.acceleration.x);
    angle += momentum;

    // Scale pendulum angle into pixel space
    float midpoint = fmodf(angle * 12.0 / M_PI, 24.0);

    // Go around the whole ring, setting each pixel based on proximity
    // (this is also to erase the prior position)...
    for (uint8_t i=0; i<24; i++) {
        float dist = fabs(midpoint - (float)i); // Pixel to pendulum distance...
        if (dist > 12.0)                   // If it crosses the "seam" at top,
            dist = 24.0 - dist;            //   take the shorter path.
        if (dist > 5.0)                    // Not close to pendulum,
            ring->setPixelColor(i, 0);     //   erase pixel.
        else if (dist < 2.0)               // Close to pendulum,
            interp(i, 1.0);                //   solid color
        else                               // Anything in-between,
            interp(i, (5.0 - dist) / 3.0); //   interpolate
    }
  }
private:
  Adafruit_EyeLights_Ring_buffered *ring; // -> glasses ring
  uint8_t *color;    // -> array of 3 uint8_t's [R,G,B]
  float    angle;    // Current position around ring
  float    momentum; // Current 'oomph'
  float    friction; // A scaling constant to dampen motion
};

Pendulum pendulums[] = {
    Pendulum(&glasses.left_ring, (uint8_t[3]){0, 20, 50}),  // Cerulean blue,
    Pendulum(&glasses.right_ring, (uint8_t[3]){0, 20, 50}), // 50 is plenty bright!
};
#define N_PENDULUMS (sizeof pendulums / sizeof pendulums[0])

// Crude error handler, prints message to Serial console, flashes LED
void err(char *str, uint8_t hz) {
  Serial.println(str);
  pinMode(LED_BUILTIN, OUTPUT);
  for (;;) digitalWrite(LED_BUILTIN, (millis() * hz / 500) & 1);
}

void setup() { // Runs once at program start...

  // Initialize hardware
  Serial.begin(115200);
  if (! accel.begin())   err("LIS3DH not found", 5);
  if (! glasses.begin()) err("IS3741 not found", 2);

  // Configure glasses for max brightness, enable output
  glasses.setLEDscaling(0xFF);
  glasses.setGlobalCurrent(0xFF);
  glasses.enable(true);
}

void loop() { // Repeat forever...
  sensors_event_t event;
  accel.getEvent(&event); // Read accelerometer once
  for (uint8_t i=0; i<N_PENDULUMS; i++) { // For each pendulum...
    pendulums[i].iterate(event);          // Do math with accel data
  }
  glasses.show();
}

OK, now let’s put that microphone and 18x5 RGB LED matrix to good use…this project reacts to sound and music as a flashy audio spectrum visualizer.

In addition to the Adafruit_IS31FL3741 library, this project requires the PDM library (bundled as part of recent Arduino IDE releases) and the Adafruit_ZeroFFT library (which can be located and installed via the Arduino Library manager).

There’s also a CircuitPython version of this project on an earlier page.

If you’d prefer a pre-compiled binary: download this .UF2 file. Connect the EyeLights driver board to your computer with a USB cable, set the power switch “on,” double-tap the reset button and a small flash drive named GLASSESBOOT appears. Then drag the .UF2 file to GLASSESBOOT and wait several seconds while it copies.

// SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
//
// SPDX-License-Identifier: MIT

/*
AUDIO SPECTRUM LIGHT SHOW for Adafruit EyeLights (LED Glasses + Driver).
Uses onboard microphone and a lot of math to react to music.
REQUIRES Adafruit_ZeroFFT LIBRARY, install via Arduino Library manager.
*/

#include <Adafruit_IS31FL3741.h> // For LED driver
#include <PDM.h>                 // For microphone
#include <Adafruit_ZeroFFT.h>    // For math

// FFT/SPECTRUM CONFIG ----

#define NUM_SAMPLES   512               // Audio & FFT buffer, MUST be a power of two
#define SPECTRUM_SIZE (NUM_SAMPLES / 2) // Output spectrum is 1/2 of FFT output
// Bottom of spectrum tends to be noisy, while top often exceeds musical
// range and is just harmonics, so clip both ends off:
#define LOW_BIN  5   // Lowest bin of spectrum that contributes to graph
#define HIGH_BIN 150 // Highest bin "

// GLOBAL VARIABLES -------

Adafruit_EyeLights_buffered glasses; // LED matrix is buffered for smooth animation
extern PDMClass PDM;                 // Microphone
short audio_buf[3][NUM_SAMPLES];     // Audio input buffers, 16-bit signed
uint8_t active_buf = 0;              // Buffer # into which audio is currently recording
volatile int samples_read = 0;       // # of samples read into current buffer thus far
volatile bool mic_on = false;        // true when reading from mic, false when full/stopped
float spectrum[SPECTRUM_SIZE];       // FFT results are stored & further processed here
float dynamic_level = 10.0;          // For adapting to changing audio volume
int frames;                          // For frames-per-second calculation
uint32_t start_time;                 // Ditto

struct { // Values associated with each column of the matrix
  int      first_bin;   // First spectrum bin index affecting column
  int      num_bins;    // Number of spectrum bins affecting column
  float   *bin_weights; // List of spectrum bin weightings
  uint32_t color;       // GFX-style 'RGB565' color for column
  float    top;         // Current column top position
  float    dot;         // Current column 'falling dot' position
  float    velocity;    // Current velocity of falling dot
} column_table[18];

// Crude error handler, prints message to Serial console, flashes LED
void err(char *str, uint8_t hz) {
  Serial.println(str);
  pinMode(LED_BUILTIN, OUTPUT);
  for (;;) digitalWrite(LED_BUILTIN, (millis() * hz / 500) & 1);
}

void setup() { // Runs once at program start...

  Serial.begin(115200);
  //while(!Serial);
  if (! glasses.begin()) err("IS3741 not found", 2);

  // FFT/SPECTRUM SETUP -----

  uint8_t spectrum_bits = (int)log2f((float)SPECTRUM_SIZE); // e.g. 8 = 256 bin spectrum
  // Scale LOW_BIN and HIGH_BIN to 0.0 to 1.0 equivalent range in spectrum
  float low_frac = log2f((float)LOW_BIN) / (float)spectrum_bits;
  float frac_range = log2((float)HIGH_BIN) / (float)spectrum_bits - low_frac;
  // Serial.printf("%d %f %f\n", spectrum_bits, low_frac, frac_range);

  // To keep the display lively, tables are precomputed where each column of
  // the matrix (of which there are few) is the sum value and weighting of
  // several bins from the FFT spectrum output (of which there are many).
  // The tables also help visually linearize the output so octaves are evenly
  // spaced, as on a piano keyboard, whereas the source spectrum data is
  // spaced by frequency in Hz.

  for (int column=0; column<18; column++) {
    // Determine the lower and upper frequency range for this column, as
    // fractions within the scaled 0.0 to 1.0 spectrum range. 0.95 below
    // creates slight frequency overlap between columns, looks nicer.
    float lower = low_frac + frac_range * ((float)column / 18.0 * 0.95);
    float upper = low_frac + frac_range * ((float)(column + 1) / 18.0);
    float mid = (lower + upper) * 0.5;               // Center of lower-to-upper range
    float half_width = (upper - lower) * 0.5 + 1e-2; // 1/2 of lower-to-upper range
    // Map fractions back to spectrum bin indices that contribute to column
    int first_bin = int(pow(2, (float)spectrum_bits * lower) + 1e-4);
    int last_bin = int(pow(2, (float)spectrum_bits * upper) + 1e-4);
    //Serial.printf("%d %d %d\n", column, first_bin, last_bin);
    float total_weight = 0.0; // Accumulate weight for this bin
    int num_bins = last_bin - first_bin + 1;
    // Allocate space for bin weights for column, stop everything if out of RAM.
    column_table[column].bin_weights = (float *)malloc(num_bins * sizeof(float));
    if (column_table[column].bin_weights == NULL) err("Malloc fail", 10);
    for (int bin_index = first_bin; bin_index <= last_bin; bin_index++) {
      // Find distance from column's overall center to individual bin's
      // center, expressed as 0.0 (bin at center) to 1.0 (bin at limit of
      // lower-to-upper range).
      float bin_center = log2f((float)bin_index + 0.5) / (float)spectrum_bits;
      float dist = fabs(bin_center - mid) / half_width;
      if (dist < 1.0) {  // Filter out a few math stragglers at either end
        // Bin weights have a cubic falloff curve within range:
        dist = 1.0 - dist; // Invert dist so 1.0 is at center
        float bin_weight = (((3.0 - (dist * 2.0)) * dist) * dist);
        column_table[column].bin_weights[bin_index - first_bin] = bin_weight;
        total_weight += bin_weight;
      }
    }
    //Serial.println(column);
    // Scale bin weights so total is 1.0 for each column, but then mute
    // lower columns slightly and boost higher columns. It graphs better.
    for (int i=0; i<num_bins; i++) {
      column_table[column].bin_weights[i] = column_table[column].bin_weights[i] /
        total_weight * (0.6 + (float)i / 18.0 * 2.0);
      //Serial.printf("  %f\n", column_table[column].bin_weights[i]);
    }
    column_table[column].first_bin = first_bin;
    column_table[column].num_bins = num_bins;
    column_table[column].color = glasses.color565(glasses.ColorHSV(
      57600UL * column / 18, 255, 255)); // Red (0) to purple (57600)
    column_table[column].top = 6.0;      // Start off bottom of graph
    column_table[column].dot = 6.0;
    column_table[column].velocity = 0.0;
  }

  for (int i=0; i<SPECTRUM_SIZE; i++) spectrum[i] = 0.0;

  // HARDWARE SETUP ---------

  // Configure glasses for max brightness, enable output
  glasses.setLEDscaling(0xFF);
  glasses.setGlobalCurrent(0xFF);
  glasses.enable(true);

  // Configure PDM mic, mono 16 KHz
  PDM.onReceive(onPDMdata);
  PDM.begin(1, 16000);

  start_time = millis();
}

void loop() { // Repeat forever...

  short *audio_data; // Pointer to newly-received audio

  while (mic_on) yield(); // Wait for next buffer to finish recording
  // Full buffer received -- active_buf is index to new data
  audio_data = &audio_buf[active_buf][0]; // New data is here
  active_buf = 1 - active_buf; // Swap buffers to record into other one,
  mic_on = true;               // and start recording next batch

  // Perform FFT operation on newly-received data,
  // results go back into the same buffer.
  ZeroFFT(audio_data, NUM_SAMPLES);

  // Convert FFT output to spectrum. log(y) looks better than raw data.
  // Only LOW_BIN to HIGH_BIN elements are needed.
  for(int i=LOW_BIN; i<=HIGH_BIN; i++) {
    spectrum[i] = (audio_data[i] > 0) ? log((float)audio_data[i]) : 0.0;
  }

  // Find min & max range of spectrum bin values, with limits.
  float lower = spectrum[LOW_BIN], upper = spectrum[LOW_BIN];
  for (int i=LOW_BIN+1; i<=HIGH_BIN; i++) {
    if (spectrum[i] < lower) lower = spectrum[i];
    if (spectrum[i] > upper) upper = spectrum[i];
  }
  //Serial.printf("%f %f\n", lower, upper);
  if (upper < 2.5) upper = 2.5;

  // Adjust dynamic level to current spectrum output, keeps the graph
  // 'lively' as ambient volume changes. Sparkle but don't saturate.
  if (upper > dynamic_level) {
    // Got louder. Move level up quickly but allow initial "bump."
    dynamic_level = dynamic_level * 0.5 + upper * 0.5;
  } else {
    // Got quieter. Ease level down, else too many bumps.
    dynamic_level = dynamic_level * 0.75 + lower * 0.25;
  }

  // Apply vertical scale to spectrum data. Results may exceed
  // matrix height...that's OK, adds impact!
  float scale = 15.0 / (dynamic_level - lower);
  for (int i=LOW_BIN; i<=HIGH_BIN; i++) {
    spectrum[i] = (spectrum[i] - lower) * scale;
  }

  // Clear screen, filter and draw each column of the display...
  glasses.fill(0);
  for(int column=0; column<18; column++) {
    int first_bin = column_table[column].first_bin;
    // Start BELOW matrix and accumulate bin weights UP, saves math
    float column_top = 7.0;
    for (int bin_offset=0; bin_offset<column_table[column].num_bins; bin_offset++) {
      column_top -= spectrum[first_bin + bin_offset] * column_table[column].bin_weights[bin_offset];
    }
    // Column top positions are filtered to appear less 'twitchy' --
    // last data still has a 30% influence on current positions.
    column_top = (column_top * 0.7) +  (column_table[column].top * 0.3);
    column_table[column].top = column_top;

    if(column_top < column_table[column].dot) {    // Above current falling dot?
      column_table[column].dot = column_top - 0.5; // Move dot up
      column_table[column].velocity = 0.0;         // and clear out velocity
    } else {
      column_table[column].dot += column_table[column].velocity; // Move dot down
      column_table[column].velocity += 0.015;                    // and accelerate
    }

    // Draw column and peak dot
    int itop = (int)column_top; // Quantize column top to pixel space
    glasses.drawLine(column, itop, column, itop + 20, column_table[column].color);
    glasses.drawPixel(column, (int)column_table[column].dot, 0xE410);
  }

  glasses.show(); // Buffered mode MUST use show() to refresh matrix

  frames += 1;
  uint32_t elapsed = millis() - start_time;
  //Serial.println(frames * 1000 / elapsed);
}

// PDM mic interrupt handler, called when new data is ready
void onPDMdata() {
  //digitalWrite(LED_BUILTIN, millis() & 1024); // Debug heartbeat
  if (int bytes_to_read = PDM.available()) {
    if (mic_on) {
      int byte_limit = (NUM_SAMPLES - samples_read) * 2; // Space remaining,
      bytes_to_read = min(bytes_to_read, byte_limit);    // don't overflow!
      PDM.read(&audio_buf[active_buf][samples_read], bytes_to_read);
      samples_read += bytes_to_read / 2; // Increment counter
      if (samples_read >= NUM_SAMPLES) { // Buffer full?
        mic_on = false;                  // Stop and
        samples_read = 0;                // reset counter for next time
      }
    } else {
      // Mic is off (code is busy) - must read but discard data.
      // audio_buf[2] is a 'bit bucket' for this.
      PDM.read(audio_buf[2], bytes_to_read);
    }
  }
}

This example is based on a staple of the 8-bit demoscene days, where the goal was to create impressive animation when RAM and CPU cycles were scarce. The fire effect translates well to the bright colors and limited pixels of the LED matrix. It’s not based on real flame physics — mathematically it’s fairly crude and comments in the code below explain each step — but like those animated flame lights in stores, it does a reasonable job fooling the eye!

There’s also a CircuitPython version of this project on an earlier page.

If you’d prefer a pre-compiled binary: download this .UF2 file. Connect the EyeLights driver board to your computer with a USB cable, set the power switch “on,” double-tap the reset button and a small flash drive named GLASSESBOOT appears. Then drag the .UF2 file to GLASSESBOOT and wait several seconds while it copies.

// SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
//
// SPDX-License-Identifier: MIT

/*
FIRE EFFECT for Adafruit EyeLights (LED Glasses + Driver).
A demoscene classic that produces a cool analog-esque look with
modest means, iteratively scrolling and blurring raster data.
*/

#include <Adafruit_IS31FL3741.h> // For LED driver

Adafruit_EyeLights_buffered glasses; // Buffered for smooth animation

// The raster data is intentionally one row taller than the LED matrix.
// Each frame, random noise is put in the bottom (off matrix) row. There's
// also an extra column on either side, to avoid needing edge clipping when
// neighboring pixels (left, center, right) are averaged later.
float data[6][20]; // 2D array where elements are accessed as data[y][x]

// Each element in the raster is a single value representing brightness.
// A pre-computed lookup table maps these to RGB colors. This one happens
// to have 32 elements, but as we're not on an actual paletted hardware
// framebuffer it could be any size really (with suitable changes throughout).
uint32_t colormap[32];
#define GAMMA 2.6

// Crude error handler, prints message to Serial console, flashes LED
void err(char *str, uint8_t hz) {
  Serial.println(str);
  pinMode(LED_BUILTIN, OUTPUT);
  for (;;) digitalWrite(LED_BUILTIN, (millis() * hz / 500) & 1);
}

void setup() { // Runs once at program start...

  // Initialize hardware
  Serial.begin(115200);
  if (! glasses.begin()) err("IS3741 not found", 2);

  // Configure glasses for reduced brightness, enable output
  glasses.setLEDscaling(0xFF);
  glasses.setGlobalCurrent(20);
  glasses.enable(true);

  memset(data, 0, sizeof data);

  for(uint8_t i=0; i<32; i++) {
    float n = i * 3.0 / 31.0; // 0.0 <= n <= 3.0 from start to end of map
    float r, g, b;
    if (n <= 1) { //             0.0 <= n <= 1.0 : black to red
      r = n;      //               r,g,b are initially calculated 0 to 1 range
      g = b = 0.0;
    } else if (n <= 2) { //      1.0 <= n <= 2.0 : red to yellow
      r = 1.0;
      g = n - 1.0;
      b = 0.0;
    } else { //                  2.0 <= n <= 3.0 : yellow to white
      r = g = 1.0;
      b = n - 2.0;
    }
    // Gamma correction linearizes perceived brightness, then scale to
    // 0-255 for LEDs and store as a 'packed' RGB color.
    colormap[i] = (uint32_t(pow(r, GAMMA) * 255.0) << 16) |
                  (uint32_t(pow(g, GAMMA) * 255.0) <<  8) |
                   uint32_t(pow(b, GAMMA) * 255.0);
  }
}

// Linearly interpolate a range of brightnesses between two LEDs of
// one eyeglass ring, mapping through the global color table. LED range
// is non-inclusive; the first and last LEDs (which overlap matrix pixels)
// are not set. led2 MUST be > led1. LED indices may be >= 24 to 'wrap
// around' the seam at the top of the ring.
void interp(bool isRight, int led1, int led2, float level1, float level2) {
  int span = led2 - led1 + 1;                   // Number of LEDs
  float delta = level2 - level1;                // Difference in brightness
  for (int led = led1 + 1; led < led2; led++) { // For each LED in-between,
    float ratio = (float)(led - led1) / span;   // interpolate brightness level
    uint32_t color = colormap[min(31, int(level1 + delta * ratio))];
    if (isRight) glasses.right_ring.setPixelColor(led % 24, color);
    else         glasses.left_ring.setPixelColor(led % 24, color);
  }
}

void loop() { // Repeat forever...
  // At the start of each frame, fill the bottom (off matrix) row
  // with random noise. To make things less strobey, old data from the
  // prior frame still has about 1/3 'weight' here. There's no special
  // real-world significance to the 85, it's just an empirically-
  // derived fudge factor that happens to work well with the size of
  // the color map.
  for (uint8_t x=1; x<19; x++) {
    data[5][x] = 0.33 * data[5][x] + 0.67 * ((float)random(1000) / 1000.0) * 85.0;
  }
  // If this were actual SRS BZNS 31337 D3M0SC3N3 code, great care
  // would be taken to avoid floating-point math. But with few pixels,
  // and so this code might be less obtuse, a casual approach is taken.

  // Each row (except last) is then processed, top-to-bottom. This
  // order is important because it's an iterative algorithm...the
  // output of each frame serves as input to the next, and the steps
  // below (looking at the pixels below each row) are what makes the
  // "flames" appear to move "up."
  for (uint8_t y=0; y<5; y++) {        // Current row of pixels
    float *y1 = &data[y + 1][0];       // One row down
    for (uint8_t x = 1; x < 19; x++) { // Skip left, right columns in data
      // Each pixel is sort of the average of the three pixels
      // under it (below left, below center, below right), but not
      // exactly. The below center pixel has more 'weight' than the
      // others, and the result is scaled to intentionally land
      // short, making each row bit darker as they move up.
      data[y][x] = (y1[x] + ((y1[x - 1] + y1[x + 1]) * 0.33)) * 0.35;
      glasses.drawPixel(x - 1, y, glasses.color565(colormap[min(31, int(data[y][x]))]));
      // Remember that the LED matrix uses GFX-style "565" colors,
      // hence the round trip through color565() here, whereas the LED
      // rings (referenced in interp()) use NeoPixel-style 24-bit colors
      // (those can reference colormap[] directly).
    }
  }

  // That's all well and good for the matrix, but what about the extra
  // LEDs in the rings? Since these don't align to the pixel grid,
  // rather than trying to extend the raster data and filter it in
  // somehow, we'll fill those arcs with colors interpolated from the
  // endpoints where rings and matrix intersect. Maybe not perfect,
  // but looks okay enough!
  interp(false, 7, 17, data[4][8], data[4][1]);   // Left ring bottom
  interp(false, 21, 29, data[0][2], data[1][8]);  // Left ring top
  interp(true, 7, 17, data[4][18], data[4][11]);  // Right ring bottom
  interp(true, 19, 27, data[1][11], data[0][17]); // Right ring top

  glasses.show();
  delay(25);
}

IT’S THE LAW: if it has pixels, we will animate blinking eyes on it. This is just the latest in that very long line of blinky things. Those LED rings were just begging for it, y’know?

There’s also a CircuitPython version of this project on an earlier page.

And here’s a simpler Arduino eyes project on Github.

If you’d prefer a pre-compiled binary: download this .UF2 file. Connect the EyeLights driver board to your computer with a USB cable, set the power switch “on,” double-tap the reset button and a small flash drive named GLASSESBOOT appears. Then drag the .UF2 file to GLASSESBOOT and wait several seconds while it copies.

// SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
//
// SPDX-License-Identifier: MIT

/*
MOVE-AND-BLINK EYES for Adafruit EyeLights (LED Glasses + Driver).

I'd written a very cool squash-and-stretch effect for the eye movement,
but unfortunately the resolution is such that the pupils just look like
circles regardless. I'm keeping it in despite the added complexity,
because this WILL look great later on a bigger matrix or a TFT/OLED,
and this way the hard parts won't require a re-write at such time.
It's a really adorable effect with enough pixels.
*/

#include <Adafruit_IS31FL3741.h> // For LED driver

// CONFIGURABLES ------------------------

#define RADIUS 3.4 // Size of pupil (3X because of downsampling later)

uint8_t eye_color[3] = { 255, 128, 0 };      // Amber pupils
uint8_t ring_open_color[3] = { 75, 75, 75 }; // Color of LED rings when eyes open
uint8_t ring_blink_color[3] = { 50, 25, 0 }; // Color of LED ring "eyelid" when blinking

// Some boards have just one I2C interface, but some have more...
TwoWire *i2c = &Wire; // e.g. change this to &Wire1 for QT Py RP2040

// GLOBAL VARIABLES ---------------------

Adafruit_EyeLights_buffered glasses(true); // Buffered spex + 3X canvas
GFXcanvas16 *canvas;                       // Pointer to canvas object

// Reading through the code, you'll see a lot of references to this "3X"
// space. This is referring to the glasses' optional "offscreen" drawing
// canvas that's 3 times the resolution of the LED matrix (i.e. 15 pixels
// tall instead of 5), which gets scaled down to provide some degree of
// antialiasing. It's why the pupils have soft edges and can make
// fractional-pixel motions.

float cur_pos[2] = { 9.0, 7.5 };  // Current position of eye in canvas space
float next_pos[2] = { 9.0, 7.5 }; // Next position "
bool in_motion = false;           // true = eyes moving, false = eyes paused
uint8_t blink_state = 0;          // 0, 1, 2 = unblinking, closing, opening
uint32_t move_start_time = 0;     // For animation timekeeping
uint32_t move_duration = 0;
uint32_t blink_start_time = 0;
uint32_t blink_duration = 0;
float y_pos[13];                 // Coords of LED ring pixels in canvas space
uint32_t ring_open_color_packed; // ring_open_color[] as packed RGB integer
uint16_t eye_color565;           // eye_color[] as a GFX packed '565' value
uint32_t frames = 0;             // For frames-per-second calculation
uint32_t start_time;

// These offsets position each pupil on the canvas grid and make them
// fixate slightly (converge on a point) so they're not always aligned
// the same on the pixel grid, which would be conspicuously pixel-y.
float x_offset[2] = { 5.0, 31.0 };
// These help perform x-axis clipping on the rasterized ellipses,
// so they don't "bleed" outside the rings and require erasing.
int box_x_min[2] = { 3, 33 };
int box_x_max[2] = { 21, 51 };

#define GAMMA  2.6 // For color correction, shouldn't need changing


// HELPER FUNCTIONS ---------------------

// Crude error handler, prints message to Serial console, flashes LED
void err(char *str, uint8_t hz) {
  Serial.println(str);
  pinMode(LED_BUILTIN, OUTPUT);
  for (;;) digitalWrite(LED_BUILTIN, (millis() * hz / 500) & 1);
}

// Given an [R,G,B] color, apply gamma correction, return packed RGB integer.
uint32_t gammify(uint8_t color[3]) {
  uint32_t rgb[3];
  for (uint8_t i=0; i<3; i++) {
    rgb[i] = uint32_t(pow((float)color[i] / 255.0, GAMMA) * 255 + 0.5);
  }
  return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
}

// Given two [R,G,B] colors and a blend ratio (0.0 to 1.0), interpolate between
// the two colors and return a gamma-corrected in-between color as a packed RGB
// integer. No bounds clamping is performed on blend value, be nice.
uint32_t interp(uint8_t color1[3], uint8_t color2[3], float blend) {
  float inv = 1.0 - blend; // Weighting of second color
  uint8_t rgb[3];
  for(uint8_t i=0; i<3; i++) {
    rgb[i] = (int)((float)color1[i] * blend + (float)color2[i] * inv);
  }
  return gammify(rgb);
}

// Rasterize an arbitrary ellipse into the offscreen 3X canvas, given
// foci point1 and point2 and with area determined by global RADIUS
// (when foci are same point; a circle). Foci and radius are all
// floating point values, which adds to the buttery impression. 'rect'
// is a bounding rect of which pixels are likely affected. Canvas is
// assumed cleared before arriving here.
void rasterize(float point1[2], float point2[2], int rect[4]) {
  float perimeter, d;
  float dx = point2[0] - point1[0];
  float dy = point2[1] - point1[1];
  float d2 = dx * dx + dy * dy; // Dist between foci, squared
  if (d2 <= 0.0) {
    // Foci are in same spot - it's a circle
    perimeter = 2.0 * RADIUS;
    d = 0.0;
  } else {
    // Foci are separated - it's an ellipse.
    d = sqrt(d2); // Distance between foci
    float c = d * 0.5; // Center-to-foci distance
    // This is an utterly brute-force way of ellipse-filling based on
    // the "two nails and a string" metaphor...we have the foci points
    // and just need the string length (triangle perimeter) to yield
    // an ellipse with area equal to a circle of 'radius'.
    // c^2 = a^2 - b^2  <- ellipse formula
    //   a = r^2 / b    <- substitute
    // c^2 = (r^2 / b)^2 - b^2
    // b = sqrt(((c^2) + sqrt((c^4) + 4 * r^4)) / 2)  <- solve for b
    float c2 = c * c;
    float b2 = (c2 + sqrt((c2 * c2) + 4 * (RADIUS * RADIUS * RADIUS * RADIUS))) * 0.5;
    // By my math, perimeter SHOULD be...
    // perimeter = d + 2 * sqrt(b2 + c2);
    // ...but for whatever reason, working approach here is really...
    perimeter = d + 2 * sqrt(b2);
  }

  // Like I'm sure there's a way to rasterize this by spans rather than
  // all these square roots on every pixel, but for now...
  for (int y=rect[1]; y<rect[3]; y++) {   // For each row...
    float y5 = (float)y + 0.5;            // Pixel center
    float dy1 = y5 - point1[1];           // Y distance from pixel to first point
    float dy2 = y5 - point2[1];           // " to second
    dy1 *= dy1;                           // Y1^2
    dy2 *= dy2;                           // Y2^2
    for (int x=rect[0]; x<rect[2]; x++) { // For each column...
      float x5 = (float)x + 0.5;          // Pixel center
      float dx1 = x5 - point1[0];         // X distance from pixel to first point
      float dx2 = x5 - point2[0];         // " to second
      float d1 = sqrt(dx1 * dx1 + dy1);   // 2D distance to first point
      float d2 = sqrt(dx2 * dx2 + dy2);   // " to second
      if ((d1 + d2 + d) <= perimeter) {   // Point inside ellipse?
        canvas->drawPixel(x, y, eye_color565);
      }
    }
  }
}


// ONE-TIME INITIALIZATION --------------

void setup() {
  // Initialize hardware
  Serial.begin(115200);
  if (! glasses.begin(IS3741_ADDR_DEFAULT, i2c)) err("IS3741 not found", 2);

  canvas = glasses.getCanvas();
  if (!canvas) err("Can't allocate canvas", 5);

  i2c->setClock(1000000); // 1 MHz I2C for extra butteriness

  // Configure glasses for reduced brightness, enable output
  glasses.setLEDscaling(0xFF);
  glasses.setGlobalCurrent(20);
  glasses.enable(true);

  // INITIALIZE TABLES & OTHER GLOBALS ----

  // Pre-compute the Y position of 1/2 of the LEDs in a ring, relative
  // to the 3X canvas resolution, so ring & matrix animation can be aligned.
  for (uint8_t i=0; i<13; i++) {
    float angle = (float)i / 24.0 * M_PI * 2.0;
    y_pos[i] = 10.0 - cos(angle) * 12.0;
  }

  // Convert some colors from [R,G,B] (easier to specify) to packed integers
  ring_open_color_packed = gammify(ring_open_color);
  eye_color565 = glasses.color565(eye_color[0], eye_color[1], eye_color[2]);

  start_time = millis(); // For frames-per-second math
}

// MAIN LOOP ----------------------------

void loop() {
  canvas->fillScreen(0);

  // The eye animation logic is a carry-over from like a billion
  // prior eye projects, so this might be comment-light.
  uint32_t now = micros(); // 'Snapshot' the time once per frame

  float upper, lower, ratio;

  // Blink logic
  uint32_t elapsed = now - blink_start_time; // Time since start of blink event
  if (elapsed > blink_duration) {  // All done with event?
    blink_start_time = now;        // A new one starts right now
    elapsed = 0;
    blink_state++;                 // Cycle closing/opening/paused
    if (blink_state == 1) {        // Starting new blink...
      blink_duration = random(60000, 120000);
    } else if (blink_state == 2) { // Switching closing to opening...
      blink_duration *= 2;         // Opens at half the speed
    } else {                       // Switching to pause in blink
      blink_state = 0;
      blink_duration = random(500000, 4000000);
    }
  }
  if (blink_state) {            // If currently in a blink...
    float ratio = (float)elapsed / (float)blink_duration; // 0.0-1.0 as it closes
    if (blink_state == 2) ratio = 1.0 - ratio;            // 1.0-0.0 as it opens
    upper = ratio * 15.0 - 4.0; // Upper eyelid pos. in 3X space
    lower = 23.0 - ratio * 8.0; // Lower eyelid pos. in 3X space
  }

  // Eye movement logic. Two points, 'p1' and 'p2', are the foci of an
  // ellipse. p1 moves from current to next position a little faster
  // than p2, creating a "squash and stretch" effect (frame rate and
  // resolution permitting). When motion is stopped, the two points
  // are at the same position.
  float p1[2], p2[2];
  elapsed = now - move_start_time;             // Time since start of move event
  if (in_motion) {                             // Currently moving?
    if (elapsed > move_duration) {             // If end of motion reached,
      in_motion = false;                       // Stop motion and
      memcpy(&p1, &next_pos, sizeof next_pos); // set everything to new position
      memcpy(&p2, &next_pos, sizeof next_pos);
      memcpy(&cur_pos, &next_pos, sizeof next_pos);
      move_duration = random(500000, 1500000); // Wait this long
    } else { // Still moving
      // Determine p1, p2 position in time
      float delta[2];
      delta[0] = next_pos[0] - cur_pos[0];
      delta[1] = next_pos[1] - cur_pos[1];
      ratio = (float)elapsed / (float)move_duration;
      if (ratio < 0.6) { // First 60% of move time, p1 is in motion
        // Easing function: 3*e^2-2*e^3 0.0 to 1.0
        float e = ratio / 0.6; // 0.0 to 1.0
        e = 3 * e * e - 2 * e * e * e;
        p1[0] = cur_pos[0] + delta[0] * e;
        p1[1] = cur_pos[1] + delta[1] * e;
      } else {                                   // Last 40% of move time
        memcpy(&p1, &next_pos, sizeof next_pos); // p1 has reached end position
      }
      if (ratio > 0.3) { // Last 70% of move time, p2 is in motion
        float e = (ratio - 0.3) / 0.7; // 0.0 to 1.0
        e = 3 * e * e - 2 * e * e * e; // Easing func.
        p2[0] = cur_pos[0] + delta[0] * e;
        p2[1] = cur_pos[1] + delta[1] * e;
      } else {                                 // First 30% of move time
        memcpy(&p2, &cur_pos, sizeof cur_pos); // p2 waits at start position
      }
    }
  } else { // Eye is stopped
    memcpy(&p1, &cur_pos, sizeof cur_pos); // Both foci at current eye position
    memcpy(&p2, &cur_pos, sizeof cur_pos);
    if (elapsed > move_duration) { // Pause time expired?
      in_motion = true;            // Start up new motion!
      move_start_time = now;
      move_duration = random(150000, 250000);
      float angle = (float)random(1000) / 1000.0 * M_PI * 2.0;
      float dist = (float)random(750) / 100.0;
      next_pos[0] = 9.0 + cos(angle) * dist;
      next_pos[1] = 7.5 + sin(angle) * dist * 0.8;
    }
  }

  // Draw the raster part of each eye...
  for (uint8_t e=0; e<2; e++) {
    // Each eye's foci are offset slightly, to fixate toward center
    float p1a[2], p2a[2];
    p1a[0] = p1[0] + x_offset[e];
    p2a[0] = p2[0] + x_offset[e];
    p1a[1] = p2a[1] = p1[1];
    // Compute bounding rectangle (in 3X space) of ellipse
    // (min X, min Y, max X, max Y). Like the ellipse rasterizer,
    // this isn't optimal, but will suffice.
    int bounds[4];
    bounds[0] = max(int(min(p1a[0], p2a[0]) - RADIUS), box_x_min[e]);
    bounds[1] = max(max(int(min(p1a[1], p2a[1]) - RADIUS), 0), (int)upper);
    bounds[2] = min(int(max(p1a[0], p2a[0]) + RADIUS + 1), box_x_max[e]);
    bounds[3] = min(int(max(p1a[1], p2a[1]) + RADIUS + 1), 15);
    rasterize(p1a, p2a, bounds); // Render ellipse into buffer
  }

  // If the eye is currently blinking, and if the top edge of the eyelid
  // overlaps the bitmap, draw lines across the bitmap as if eyelids.
  if (blink_state and upper >= 0.0) {
    int iu = (int)upper;
    canvas->drawLine(box_x_min[0], iu, box_x_max[0] - 1, iu, eye_color565);
    canvas->drawLine(box_x_min[1], iu, box_x_max[1] - 1, iu, eye_color565);
  }

  glasses.scale(); // Smooth filter 3X canvas to LED grid

  // Matrix and rings share a few pixels. To make the rings take
  // precedence, they're drawn later. So blink state is revisited now...
  if (blink_state) { // In mid-blink?
    for (uint8_t i=0; i<13; i++) { // Half an LED ring, top-to-bottom...
      float a = min(max(y_pos[i] - upper + 1.0, 0.0), 3.0);
      float b = min(max(lower - y_pos[i] + 1.0, 0.0), 3.0);
      ratio = a * b / 9.0; // Proximity of LED to eyelid edges
      uint32_t packed = interp(ring_open_color, ring_blink_color, ratio);
      glasses.left_ring.setPixelColor(i, packed);
      glasses.right_ring.setPixelColor(i, packed);
      if ((i > 0) && (i < 12)) {
        uint8_t j = 24 - i; // Mirror half-ring to other side
        glasses.left_ring.setPixelColor(j, packed);
        glasses.right_ring.setPixelColor(j, packed);
      }
    }
  } else {
    glasses.left_ring.fill(ring_open_color_packed);
    glasses.right_ring.fill(ring_open_color_packed);
  }

  glasses.show();

  frames += 1;
  elapsed = millis() - start_time;
  Serial.println(frames * 1000 / elapsed);
}

This project works together with the Adafruit Bluefruit LE Connect app for iOS and Android to control a scrolling message across the 18x5 RGB LED matrix.

When first run, the glasses will scroll the message “RUN BLUEFRUIT CONNECT APP”. Self explanatory. When you run this app on your phone or tablet, you’ll see the EyeLights device as “LED Glasses Driver nRF52840.” Tap the corresponding “Connect” button.

Once connected, the app will show this “MODULES” screen. The items of interest here are UART and CONTROLLER.

UART provides a text field into which you can type a message, up to a maximum of 50 characters. Press the “Send” button to update the glasses.

Tip: the exclamation point character (“!”) is off-limits…that has special meaning to the software. Any other ASCII characters (letters, numbers, punctuation) are fair game. Upper or lower case doesn’t matter…because the matrix is small and requires a chunky font, everything will be converted to upper case.

Or, from the “Controller” screen, click “Color Picker.”

Here you can select a color from the wheel and a brightness level with the slider. Tapping “Send selected color” will change the color of the scrolling message.

The above two settings — message and color — are the only options that have any bearing on this project. Although the app can issue other data like game pad buttons or a compass heading, we didn’t want to go overboard and make the code too complex to follow. Consider it a starting point for your own ideas.

The text looks rough when testing right in front of you…but from a few feet away the image blends together and is more legible. Try it with a mirror!

If you’d prefer a pre-compiled binary: download this .UF2 file. Connect the EyeLights driver board to your computer with a USB cable, set the power switch “on,” double-tap the reset button and a small flash drive named GLASSESBOOT appears. Then drag the .UF2 file to GLASSESBOOT and wait several seconds while it copies.

// SPDX-FileCopyrightText: 2021 Phil Burgess for Adafruit Industries
//
// SPDX-License-Identifier: MIT

/*
BLUETOOTH SCROLLING MESSAGE for Adafruit EyeLights (LED Glasses + Driver).
Use BLUEFRUIT CONNECT app on iOS or Android to connect to LED glasses.
Use the app's UART input to enter a new message.
Use the app's Color Picker (under "Controller") to change text color.
This is based on the glassesdemo-3-smooth example from the
Adafruit_IS31FL3741 library, with Bluetooth additions on top. If this
code all seems a bit too much, you can start with that example (or the two
that precede it) to gain an understanding of the LED glasses basics, then
return here to see what the extra Bluetooth layers do.
*/

#include <Adafruit_IS31FL3741.h> // For LED driver
#include <bluefruit.h>           // For Bluetooth communication
#include <EyeLightsCanvasFont.h> // Smooth scrolly font for glasses

// These items are over in the packetParser.cpp tab:
extern uint8_t packetbuffer[];
extern uint8_t readPacket(BLEUart *ble, uint16_t timeout);
extern int8_t packetType(uint8_t *buf, uint8_t len);
extern float parsefloat(uint8_t *buffer);
extern void printHex(const uint8_t * data, const uint32_t numBytes);

// GLOBAL VARIABLES -------

// 'Buffered' glasses for buttery animation,
// 'true' to allocate a drawing canvas for smooth graphics:
Adafruit_EyeLights_buffered glasses(true);
GFXcanvas16 *canvas; // Pointer to glasses' canvas object
// Because 'canvas' is a pointer, always use -> when calling
// drawing functions there. 'glasses' is an object in itself,
// so . is used when calling its functions.

char message[51] = "Run Bluefruit Connect app"; // Scrolling message
int16_t text_x;   // Message position on canvas
int16_t text_min; // Leftmost position before restarting scroll

BLEUart bleuart;  // Bluetooth low energy UART

int8_t last_packet_type = 99; // Last BLE packet type, init to nonsense value

// ONE-TIME SETUP ---------

void setup() { // Runs once at program start...

  Serial.begin(115200);
  //while(!Serial);

  // Configure and start the BLE UART service
  Bluefruit.begin();
  Bluefruit.setTxPower(4);
  bleuart.begin();
  startAdv(); // Set up and start advertising

  if (!glasses.begin()) err("IS3741 not found", 2);

  canvas = glasses.getCanvas();
  if (!canvas) err("Can't allocate canvas", 5);

  // Configure glasses for full brightness and enable output
  glasses.setLEDscaling(0xFF);
  glasses.setGlobalCurrent(0xFF);
  glasses.enable(true);

  // Set up for scrolling text, initialize color and position
  canvas->setFont(&EyeLightsCanvasFont);
  canvas->setTextWrap(false); // Allow text to extend off edges
  canvas->setTextColor(glasses.color565(0x303030)); // Dim white to start
  reposition_text(); // Sets up initial position & scroll limit
}

// Crude error handler, prints message to Serial console, flashes LED
void err(char *str, uint8_t hz) {
  Serial.println(str);
  pinMode(LED_BUILTIN, OUTPUT);
  for (;;) digitalWrite(LED_BUILTIN, (millis() * hz / 500) & 1);
}

// Set up, start BLE advertising
void startAdv(void) {
  // Advertising packet
  Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
  Bluefruit.Advertising.addTxPower();
  
  // Include the BLE UART (AKA 'NUS') 128-bit UUID
  Bluefruit.Advertising.addService(bleuart);

  // Secondary Scan Response packet (optional)
  // Since there is no room for 'Name' in Advertising packet
  Bluefruit.ScanResponse.addName();

  // Start Advertising
  // - Enable auto advertising if disconnected
  // - Interval:  fast mode = 20 ms, slow mode = 152.5 ms
  // - Timeout for fast mode is 30 seconds
  // - Start(timeout) with timeout = 0 will advertise forever (until connected)
  // 
  // For recommended advertising interval
  // https://developer.apple.com/library/content/qa/qa1931/_index.html   
  Bluefruit.Advertising.restartOnDisconnect(true);
  Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
  Bluefruit.Advertising.setFastTimeout(30);   // number of seconds in fast mode
  Bluefruit.Advertising.start(0);             // 0 = Don't stop advertising after n seconds  
}

// MAIN LOOP --------------

void loop() { // Repeat forever...
  // The packet read timeout (9 ms here) also determines the text
  // scrolling speed -- if no data is received over BLE in that time,
  // the function exits and returns here with len=0.
  uint8_t len = readPacket(&bleuart, 9);
  if (len) {
    int8_t type =  packetType(packetbuffer, len);
    // The Bluefruit Connect app can return a variety of data from
    // a phone's sensors. To keep this example relatively simple,
    // we'll only look at color and text, but here's where others
    // would go if we were to extend this. See Bluefruit library
    // examples for the packet data formats. packetParser.cpp
    // has a couple functions not used in this code but that may be
    // helpful in interpreting these other packet types.
    switch(type) {
     case 0: // Accelerometer
      Serial.println("Accel");
      break;
     case 1: // Gyro:
      Serial.println("Gyro");
      break;
     case 2: // Magnetometer
      Serial.println("Mag");
      break;
     case 3: // Quaternion
      Serial.println("Quat");
      break;
     case 4: // Button
      Serial.println("Button");
      break;
     case 5: // Color
      Serial.println("Color");
      // packetbuffer[2] through [4] contain R, G, B byte values.
      // Because the drawing canvas uses lower-precision '565' color,
      // and because glasses.scale() applies gamma correction and may
      // quantize the dimmest colors to 0, set a brightness floor here
      // so text isn't invisible.
      for (uint8_t i=2; i<=4; i++) {
        if (packetbuffer[i] < 0x20) packetbuffer[i] = 0x20;
      }
      canvas->setTextColor(glasses.color565(glasses.Color(
        packetbuffer[2], packetbuffer[3], packetbuffer[4])));
      break;
     case 6: // Location
      Serial.println("Location");
      break;
     default: // -1
      // Packet is not one of the Bluefruit Connect types. Most programs
      // will ignore/reject it as not valud, but in this case we accept
      // it as a freeform string for the scrolling message.
      if (last_packet_type != -1) {
        // If prior data was a packet, this is a new freeform string,
        // initialize the message string with it...
        strncpy(message, (char *)packetbuffer, 20);
      } else {
        // If prior data was also a freeform string, concatenate this onto
        // the message (up to the max message length). BLE packets can only
        // be so large, so long strings are broken into multiple packets.
        uint8_t message_len = strlen(message);
        uint8_t max_append = sizeof message - 1 - message_len;
        strncpy(&message[message_len], (char *)packetbuffer, max_append);
        len = message_len + max_append;
      }
      message[len] = 0; // End of string NUL char
      Serial.println(message);
      reposition_text(); // Reset text off right edge of canvas
    }
    last_packet_type = type; // Save packet type for next pass
  } else {
    last_packet_type = 99; // BLE read timeout, reset last type to nonsense
  }

  canvas->fillScreen(0); // Clear the whole drawing canvas
  // Update text to new position, and draw on canvas
  if (--text_x < text_min) {  // If text scrolls off left edge,
    text_x = canvas->width(); // reset position off right edge
  }
  canvas->setCursor(text_x, canvas->height());
  canvas->print(message);
  glasses.scale(); // 1:3 downsample canvas to LED matrix
  glasses.show();  // MUST call show() to update matrix
}

// When new message text is assigned, call this to reset its position
// off the right edge and calculate column where scrolling resets.
void reposition_text() {
  uint16_t w, h, ignore;
  canvas->getTextBounds(message, 0, 0, (int16_t *)&ignore, (int16_t *)&ignore, &w, &ignore);
  text_x = canvas->width();
  text_min = -w; // Off left edge this many pixels
}

This guide was first published on Oct 12, 2021. It was last updated on Dec 10, 2023.