# Adafruit MatrixPortal M4

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/095/022/medium800thumb/led_matrices_4745-05.jpg?1600966357)

Folks love Adafruit's [wide selection of RGB matrices](https://www.adafruit.com/category/327) and accessories for making custom colorful LED displays... and Adafruit RGB Matrix Shields and FeatherWings can be quickly soldered together to make the wiring much easier.

But what if we made it&nbsp;_even easier_&nbsp;than that?&nbsp; **Like, no solder, no wiring, just instant plug-and-play?&nbsp;** Dream no more - with the **Adafruit Matrix Portal add-on for RGB Matrices** , there has never been an easier way to create powerful internet-connected LED displays.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/024/medium800/led_matrices_4745-06.jpg?1600966487)

Plug The Matrix Portal directly into the back of [any HUB-75 compatible display (all the ones we stock will work) from 16x32 up to 64x64](https://www.adafruit.com/category/327)! Use the included screws to attach the power cable to the power plugs with a common screwdriver, then power it with any USB C power supply. (For larger projects, power the matrices with a separate 5V power adapter)

![](https://cdn-learn.adafruit.com/assets/assets/000/095/023/medium800/led_matrices_4745-12.jpg?1600966452)

Then code up your project in&nbsp;[CircuitPython](https://learn.adafruit.com/rgb-led-matrices-matrix-panels-with-circuitpython)&nbsp;or&nbsp;[Arduino](https://learn.adafruit.com/adafruit-protomatter-rgb-matrix-library), the Adafruit Protomatter matrix library works great on the SAMD51 chipset, knowing that you've got the wiring and level shifting all handled. Here's what you get:

- **ATSAMD51J19 Cortex M4 processor** , 512KB flash, 192K of SRAM, with full Arduino or CircuitPython support
- **ESP32 WiFi co-processor** &nbsp;with TLS support and SPI interface to the M4, with full Arduino or CircuitPython support
- **USB Type C** &nbsp;connector for data and power connectivity
- [**I2C STEMMA QT connector&nbsp;** for plug-n-play use of any of our STEMMA QT devices or sensors](https://www.adafruit.com/category/620)&nbsp;can also be used with&nbsp;[any Grove I2C devices using this adapter cable](https://www.adafruit.com/product/4528)
- **JST 3-pin connector** &nbsp;that also has analog input/output,&nbsp;[say for adding audio playback to projects](https://www.adafruit.com/product/3885)
- **LIS3DH accelerometer** &nbsp;for digital sand projects or detecting taps/orientation.
- **GPIO breakouts** &nbsp;including 4 analog outputs with PWM and SPI support for adding other hardware.
- **Address E line jumper** &nbsp;for use with 64x64 matrices (check your matrix to see which pin is used for address E!
- **Two user interface buttons** &nbsp;+ one reset button
- **Indicator NeoPixel** &nbsp;and red LED
- **Green power indicator LEDs** &nbsp;for both 3V and 5V power
- **2x10 socket connector** &nbsp;fits snugly into 2x8 HUB75 ports without worrying about 'off by one' errors.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/026/medium800/led_matrices_4745-07.jpg?1600966542)

The Matrix Portal uses an ATMEL (Microchip) ATSAMD51J19, and an Espressif ESP32 Wi-Fi coprocessor with TLS/SSL support built-in. The M4 and ESP32 are a great couple - and each bring their own strengths to this board. The SAMD51 M4 has native USB, so it can show up like a disk drive, act as a MIDI or HID keyboard/mouse, and of course bootload and debug over a serial port. It also has DACs, ADC, PWM, and tons of GPIO, so it can handle the high speed updating of the RGB matrix.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/027/medium800/led_matrices_4745-09.jpg?1600966566)

Meanwhile, the ESP32 has secure WiFi capabilities, and plenty of Flash and RAM to buffer sockets. By letting the ESP32 focus on the complex TLS/SSL computation and socket buffering, it frees up the SAMD51 to act as the user interface. You get a great programming experience thanks to the native USB with files available for drag-n-drop, and you don't have to spend a ton of processor time and memory to do SSL encryption/decryption and certificate management. It's the best of both worlds!

![](https://cdn-learn.adafruit.com/assets/assets/000/095/028/medium800/led_matrices_4745-08.jpg?1600966772)

# Adafruit MatrixPortal M4

## Pinouts

![](https://cdn-learn.adafruit.com/assets/assets/000/095/052/medium800/led_matrices_matrixportal_pinout_overview.jpg?1600989989)

![](https://cdn-learn.adafruit.com/assets/assets/000/133/096/medium800/led_matrices_Adafruit_MatrixPortal_M4_Pinout.png?1728586623)

[Click here to view a PDF version of the pinout diagram](https://github.com/adafruit/Adafruit-MatrixPortal-M4-PCB/blob/main/Adafruit%20MatrixPortal%20M4%20Pinout.pdf)

There are so many great features on the Adafruit MatrixPortal M4. Let's take a look at what's available!

## Microcontroller and Flash
The main processor chip is the&nbsp; **ATSAMD51J19 Cortex M4** &nbsp;running at 120MHz with 3.3v logic/power. It has 512KB of Flash and 192KB of RAM.

We also include **2 MB of QSPI Flash** &nbsp;for storing images, sounds, animations, whatever!

![led_matrices_matrixportal_pinout_mc_flash.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/053/medium640/led_matrices_matrixportal_pinout_mc_flash.jpg?1600990095)

## WiFi
The WiFi capability uses an&nbsp; **Espressif ESP32 Wi-Fi coprocessor** &nbsp;with TLS/SSL support built-in.

The ESP32 uses the SPI port for data, and also uses a CS pin (`board.ESP_CS`&nbsp;or Arduino&nbsp;`33`), Ready/Busy pin (`board.ESP_BUSY`&nbsp;or Arduino&nbsp;`31`), and reset pin (`board.ESP_RESET`&nbsp;or Arduino&nbsp;`30`)

![led_matrices_matrixportal_pinout_wifi.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/054/medium640/led_matrices_matrixportal_pinout_wifi.jpg?1600990274)

## HUB75 Connector
There is a **2x8 pin HUB75** connector on the reverse side that plugs directly into the HUB75 port on your RGB Matrix.

The socket itself is 2x10 so that it fits snug and lined up in a 2x8 IDC socket. Otherwise its easy to get it 'off by one'

![led_matrices_matrixportal_pinout_hub75_back.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/059/medium640/led_matrices_matrixportal_pinout_hub75_back.jpg?1600991627)

![led_matrices_matrixportal_pinout_hub75.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/060/medium640/led_matrices_matrixportal_pinout_hub75.jpg?1600991650)

## RGB Matrix Power
There are **+5V** and **Ground** M3-threaded screw terminals on either side of the HUB75 connector. These provide power to the RGB Matrix.

If you would like to power the RGB Matrix with external power, we recommend disconnecting it from here and providing power directly to the matrix.

These terminals were designed as outputs ONLY - power from the USB port connects directly to these pads, so you should power from USB and then connect the matrix power inputs to these terminals.

While it's _technically_ possible to power the MatrixPortal through here, we strongly discourage that because **plugging anything into the USB port at the same time could result in damage.**

![led_matrices_matrixportal_pinout_power.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/064/medium640/led_matrices_matrixportal_pinout_power.jpg?1600992780)

## Sensors
The MatrixPortal M4 includes a **LIS3DH Triple-Axis Accelerometer**. The accelerometer is connected via the I2C bus.

**Please note the address of the accelerometer is 0x19 not 0x18 which is the default in our libraries.**

![led_matrices_matrixportal_pinout_accelerometer.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/055/medium640/led_matrices_matrixportal_pinout_accelerometer.jpg?1600990768)

## Stemma QT Connector
There is a 4-pin **Stemma QT&nbsp;connector** on the left. The I2C has pullups to 3.3V power and is connected to the LIS3DH already.

In CircuitPython, you can use the STEMMA connector with&nbsp;`board.SCL`&nbsp;and&nbsp;`board.SDA`, or&nbsp;`board.STEMMA_I2C()`.

![led_matrices_matrixportal_pinout_stemmaqt.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/056/medium640/led_matrices_matrixportal_pinout_stemmaqt.jpg?1600991160)

## Reset Pin
 **RST** is the Reset pin. Tie to ground to manually reset the ATSAMD51, as well as launch the bootloader manually.

![led_matrices_matrixportal_pinout_reset.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/096/medium640/led_matrices_matrixportal_pinout_reset.jpg?1601065666)

## Debugging Interface
If you'd like to do more advanced development, trace-debugging, or not use the bootloader, we have the SWD interface exposed.

![led_matrices_matrixportal_pinout_debug.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/097/medium640/led_matrices_matrixportal_pinout_debug.jpg?1601065756)

## Serial UART Pins
The **TX pin** and **RX pin** are for serial communication with the SAMD51 microcontroller and can be used to connect various peripherals such as a GPS.

The RX pin is attached to `board.RX` and Arduino `0` and the TX pin is attached to `board.TX` and Arduino `1`.

![led_matrices_matrixportal_pinout_serial.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/066/medium640/led_matrices_matrixportal_pinout_serial.jpg?1600993269)

## Analog Connector/Pins
On the bottom side towards the right, there is a connector labeled **A0**. This is a&nbsp; **3-pin JST analog connector** for sensors or NeoPixels, analog output or input

Along the bottom there are also pins labeled `A1` through `A4`.

All of these pins can be used for analog inputs or digital I/O.

![led_matrices_matrixportal_pinout_analog.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/061/medium640/led_matrices_matrixportal_pinout_analog.jpg?1600991865)

## Power Pins
 **3V** is the output from the 3.3V regulator, it can supply 500mA peak.

**GND** is the common ground for all power and logic.

![led_matrices_matrixportal_pinout_power.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/098/medium640/led_matrices_matrixportal_pinout_power.jpg?1601065819)

## Status LED and NeoPixel
There are two LEDs on the board.

There is the RGB&nbsp; **status NeoPixel** &nbsp;labeled "STATUS". It is connected to&nbsp;`board.NEOPIXEL`&nbsp;or Arduino&nbsp;`4`

As well, there is the&nbsp; **D13 LED**. This is attached to&nbsp;`board.LED`&nbsp;and Arduino&nbsp;`13`

![led_matrices_matrixportal_pinout_leds.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/062/medium640/led_matrices_matrixportal_pinout_leds.jpg?1600992536)

## USB-C Connector
There is one USB port on the board.

On the left side, towards the bottom, is a&nbsp; **USB Type C&nbsp;** port, which is used for powering and programming both the board and RGB Matrix.

![led_matrices_matrixportal_pinout_usbc.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/063/medium640/led_matrices_matrixportal_pinout_usbc.jpg?1600992645)

## Buttons
There are three buttons along the left side of the MatrixPortal M4.

The&nbsp; **reset button&nbsp;** is located in the top position. Click it once to re-start your firmware. Click twice to enter bootloader mode.

The **up button** is located in the middle and is attached to&nbsp;`board.BUTTON_UP`&nbsp;and Arduino&nbsp;`2`.

The **down button** is located on the bottom and is attached to `board.BUTTON_DOWN`&nbsp;and Arduino&nbsp;`3`.

The up and down buttons do not have any pull-up resistors connected to them and pressing either of them pulls the input low.

![led_matrices_matrixportal_pinout_buttons.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/065/medium640/led_matrices_matrixportal_pinout_buttons.jpg?1600992892)

## Address E Line Jumper
This jumper is used for use with **64x64 matrices** and is either connected to pin 8 or pin 16 of the HUB75 connector. Check your matrix to see which pin is used for address E.

You can close the jumper by using your soldering iron to melt a blob of solder on the bottom solder jumper so the middle pad is 'shorted' to 8. _(This is compatible with 64x64 matrices in the Adafruit store. For 64x64 matrices from other sources, you might need to use 16 instead, check the datasheet of your display.)_

&nbsp;

![led_matrices_matrixportal_pinout_e_jumper.jpg](https://cdn-learn.adafruit.com/assets/assets/000/095/067/medium640/led_matrices_matrixportal_pinout_e_jumper.jpg?1600993807)

# Adafruit MatrixPortal M4

## Prep the MatrixPortal

## Power Prep

The MatrixPortal supplies power to the matrix display panel via two standoffs. These come with protective tape applied (part of our manufacturing process) which MUST BE REMOVED!

Use some tweezers or a fingernail to remove the two amber circles.

![adafruit_io_mxprtl-3866.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/902/medium640/adafruit_io_mxprtl-3866.jpg?1600706317)

![adafruit_io_mxprtl-3867.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/903/medium640/adafruit_io_mxprtl-3867.jpg?1600706324)

## Power Terminals

Next, screw in the spade connectors to the corresponding standoff.

- **red** wire goes to **+5V** &nbsp;
- **black** wire goes to **GND**

![adafruit_io_mxprtl-3869.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/907/medium640/adafruit_io_mxprtl-3869.jpg?1600706432)

![adafruit_io_mxprtl-3871.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/908/medium640/adafruit_io_mxprtl-3871.jpg?1600706551)

## Panel Power

Plug either one of the four-conductor power plugs into the power connector pins on the panel. The plug can only go in one way, and that way is marked on the board's silkscreen.

![adafruit_io_mxprtl-3872.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/910/medium640/adafruit_io_mxprtl-3872.jpg?1600706597)

![adafruit_io_mxprtl-3873.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/911/medium640/adafruit_io_mxprtl-3873.jpg?1600706672)

## Dual Matrix Setup

If you're planning to use a 64x64 matrix, [follow these instructions on soldering the Address E Line jumper](https://learn.adafruit.com/adafruit-matrixportal-m4/pinouts#address-e-line-jumper-3072815).

## Board Connection

Now, plug the board into the left side shrouded 8x2 connector as shown. The orientation matters, so take a moment to confirm that the **white indicator arrow on the matrix panel is oriented pointing up and right** as seen here and the MatrixPortal overhangs the edge of the panel when connected. This allows you to use the edge buttons from the front side.

&nbsp;

Check nothing is impeding the board from plugging in firmly. If there's a plastic nub on the matrix that's keeping the Portal from sitting flat, cut it off with diagonal cutters

![adafruit_io_mxprtl-3874.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/912/medium640/adafruit_io_mxprtl-3874.jpg?1600706721)

![adafruit_io_mxprtl-3875.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/913/medium640/adafruit_io_mxprtl-3875.jpg?1600706732)

![](https://cdn-learn.adafruit.com/assets/assets/000/094/914/medium800/adafruit_io_mxprtl-3876.jpg?1600706891)

![](https://cdn-learn.adafruit.com/assets/assets/000/094/915/medium800/adafruit_io_mxprtl-3877.jpg?1600706894)

Info: 

# Adafruit MatrixPortal M4

## LED Matrix Diffuser

## LED Diffusion Acrylic

You can add an [LED diffusion acrylic faceplate](https://www.adafruit.com/product/4594) to the your LED matrix display. (Pictured here with the [ON AIR project](https://learn.adafruit.com/rgb-matrix-automatic-youtube-on-air-sign))

This can help protect the LEDs as well as enhance the look of the sign both indoors and out by reducing glare and specular highlights of the plastic matrix grid.

![led_matrices_onairbuild-3367.jpg](https://cdn-learn.adafruit.com/assets/assets/000/093/987/medium640/led_matrices_onairbuild-3367.jpg?1597088161)

## Measure and Cut the Plastic

You can use the sign to measure and mark cut lines on the paper backing of the acrylic sheet.

Then, use a tablesaw or bandsaw with a fine toothed blade and a guide or sled to make the cuts.

Note: it is possible to score and snap acrylic, but it can be very tricky to get an even snap without proper clamping.

![led_matrices_onairbuild-3343.jpg](https://cdn-learn.adafruit.com/assets/assets/000/093/988/medium640/led_matrices_onairbuild-3343.jpg?1597088278)

![led_matrices_onairbuild-3346.jpg](https://cdn-learn.adafruit.com/assets/assets/000/093/989/medium640/led_matrices_onairbuild-3346.jpg?1597088290)

![led_matrices_onairbuild-3347.jpg](https://cdn-learn.adafruit.com/assets/assets/000/093/991/medium640/led_matrices_onairbuild-3347.jpg?1597089259)

![led_matrices_onairbuild-3349.jpg](https://cdn-learn.adafruit.com/assets/assets/000/093/992/medium640/led_matrices_onairbuild-3349.jpg?1597089270)

![](https://cdn-learn.adafruit.com/assets/assets/000/093/998/medium800/led_matrices_onairbuild-3352.jpg?1597089308)

Peel away the paper backing from both sides and set the acrylic onto your matrix display with the matte finished side facing out.

![led_matrices_onairbuild-3355.jpg](https://cdn-learn.adafruit.com/assets/assets/000/093/999/medium640/led_matrices_onairbuild-3355.jpg?1597089331)

## Uglu Dashes

The best method we've found for adhering acrylic to the matrix display is to use [Uglu Dashes clear adhesive rectangles from Pro Tapes](https://www.protapes.com/products/uglu-600-dashes-sheets). They are incredibly strong (although can be removed if necessary), easy to apply, and are invisible once attached.

Use one at each corner and one each at the halfway point of the long edges, then press the acrylic and matrix panel together for about 20 seconds.

![adafruit_io_weathermx-2-3.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/842/medium640/adafruit_io_weathermx-2-3.jpg?1600463849)

![adafruit_io_weathermx-2.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/843/medium640/adafruit_io_weathermx-2.jpg?1600463856)

![adafruit_io_weathermx-2-2.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/844/medium640/adafruit_io_weathermx-2-2.jpg?1600463866)

Here you can see the impact of using the diffusion acrylic. (Pictured here with the ON AIR sign project)

![](https://cdn-learn.adafruit.com/assets/assets/000/094/006/medium800thumb/led_matrices_diffusionOnAir.jpg?1597089757)

## Stand

A very simple and attractive way to display your matrix is with the adjustable [bent-wire stand](https://www.adafruit.com/product/1679).

![led_matrices_onairbuild-3418.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/032/medium640/led_matrices_onairbuild-3418.jpg?1597094067)

![led_matrices_onairbuild-3419.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/033/medium640/led_matrices_onairbuild-3419.jpg?1597094085)

![led_matrices_onairbuild-3421.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/034/medium640/led_matrices_onairbuild-3421.jpg?1597094097)

![led_matrices_onairbuild-3422.jpg](https://cdn-learn.adafruit.com/assets/assets/000/094/035/medium640/led_matrices_onairbuild-3422.jpg?1597094107)

![](https://cdn-learn.adafruit.com/assets/assets/000/095/378/medium800/adafruit_io_led_matrices_onairbuild-3383.jpg?1602006263)

Alternately, you can use a frame, [3D printed brackets](https://learn.adafruit.com/led-protest-sign/build-the-sign#step-3065326), tape, glue, or even large binder clips to secure the acrylic to the sign and then mount it on on a wall, shelf, or display cabinet.

[These mini-magnet feet](https://www.adafruit.com/product/4631) can be used to stick the sign to a ferrous surface.

# Adafruit MatrixPortal M4

## Install CircuitPython

[CircuitPython](https://github.com/adafruit/circuitpython) is a derivative of [MicroPython](https://micropython.org) designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the **CIRCUITPY** drive to iterate.

## Set up CircuitPython Quick Start!

Follow this quick step-by-step for super-fast Python power :)

[Download the latest version of CircuitPython for this board via circuitpython.org](https://circuitpython.org/board/matrixportal_m4/)
## Further Information

For more detailed info on installing CircuitPython, check out [Installing CircuitPython](https://learn.adafruit.com/welcome-to-circuitpython/installing-circuitpython).

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

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

![led_matrices_Save_to_Desktop.png](https://cdn-learn.adafruit.com/assets/assets/000/095/075/medium640/led_matrices_Save_to_Desktop.png?1601050695)

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

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

Double-click the **Reset** button (indicated by the green arrow) on your board, and you will see the NeoPixel RGB LED (indicated by the magenta arrow) turn green. If it turns red, check the USB cable, try another USB port, etc.

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

![led_matrices_matrixportal_install_cp.jpg](https://cdn-learn.adafruit.com/assets/assets/000/125/447/medium640/led_matrices_matrixportal_install_cp.jpg?1697644568)

You will see a new disk drive appear called **MATRIXBOOT**.

&nbsp;

Drag the **adafruit\_circuitpython\_etc.uf2** file to **MATRIXBOOT****.**

![led_matrices_MATRIXBOOT.png](https://cdn-learn.adafruit.com/assets/assets/000/125/448/medium640/led_matrices_MATRIXBOOT.png?1697644692)

![led_matrices_Drag_to_Drive.png](https://cdn-learn.adafruit.com/assets/assets/000/125/449/medium640/led_matrices_Drag_to_Drive.png?1697644703)

The LED will flash. Then, the **MATRIXBOOT** &nbsp;drive will disappear and a new disk drive called **CIRCUITPY** will appear.

That's it, you're done! :)

![led_matrices_circuitpy.png](https://cdn-learn.adafruit.com/assets/assets/000/125/450/medium640/led_matrices_circuitpy.png?1697645066)

# Adafruit MatrixPortal M4

## What is CircuitPython?

CircuitPython is a programming language designed to simplify experimenting and learning to program on low-cost microcontroller boards. It makes getting started easier than ever with no upfront desktop downloads needed. Once you get your board set up, open any text editor, and get started editing code. It's that simple.

![](https://cdn-learn.adafruit.com/assets/assets/000/049/445/medium800/circuitpython_python-logo-master-flat.png?1513729728)

# CircuitPython is based on Python

Python is the fastest growing programming language. It's taught in schools and universities. It's a high-level programming language which means it's designed to be easier to read, write and maintain. It supports modules and packages which means it's easy to reuse your code for other projects. It has a built in interpreter which means there are no extra steps, like _compiling_, to get your code to work. And of course, Python is Open Source Software which means it's free for anyone to use, modify or improve upon.

CircuitPython adds hardware support to all of these amazing features. If you already have Python knowledge, you can easily apply that to using CircuitPython. If you have no previous experience, it's really simple to get started!

![](https://cdn-learn.adafruit.com/assets/assets/000/049/441/medium800/circuitpython_circuit_playground_adafruit_blinka_computer.png?1513729326)

## Why would I use CircuitPython?
CircuitPython is designed to run on microcontroller boards. A microcontroller board is a board with a microcontroller chip that's essentially an itty-bitty all-in-one computer. The board you're holding is a microcontroller board! CircuitPython is easy to use because all you need is that little board, a USB cable, and a computer with a USB connection. But that's only the beginning.

Other reasons to use CircuitPython include:

- **You want to get up and running quickly.** Create a file, edit your code, save the file, and it runs immediately. There is no compiling, no downloading and no uploading needed.
- **You're new to programming.** CircuitPython is designed with education in mind. It's easy to start learning how to program and you get immediate feedback from the board.
- **Easily update your code.** Since your code lives on the disk drive, you can edit it whenever you like, you can also keep multiple files around for easy experimentation.
- **The serial console and REPL.** These allow for live feedback from your code and interactive programming.
- **File storage.** The internal storage for CircuitPython makes it great for data-logging, playing audio clips, and otherwise interacting with files.
- **Strong hardware support.** CircuitPython has builtin support for microcontroller hardware features like digital I/O pins, hardware buses (UART, I2C, SPI), audio I/O, and other capabilities. There are also many libraries and drivers for sensors, breakout boards and other external components.
- **It's Python!** Python is the fastest-growing programming language. It's taught in schools and universities. CircuitPython is almost-completely compatible with Python. It simply adds hardware support.

This is just the beginning. CircuitPython continues to evolve, and is constantly being updated. Adafruit welcomes and encourages feedback from the community, and incorporate it into the development of CircuitPython. That's the core of the open source concept. This makes CircuitPython better for you and everyone who uses it!

# Adafruit MatrixPortal M4

## CircuitPython Setup

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

# Adafruit CircuitPython Bundle

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

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

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

- **adafruit\_matrixportal** - this library is the main library used with the MatrixPortal.
- **adafruit\_debouncer.mpy** - this library is&nbsp;used for debouncing a digital input pin
- **adafruit\_portalbase** &nbsp;- This is the base library that adafruit\_matrixportal is built on top of.
- **adafruit\_esp32spi** - this is the library that gives you internet access via the ESP32 using (you guessed it!) SPI transport. You need this for anything Internet
- **neopixel.mpy** - for controlling the onboard neopixel
- **adafruit\_bus\_device** - low level support for I2C/SPI
- **adafruit\_requests.mpy** - this library allows us to perform HTTP requests and get responses back from servers. GET/POST/PUT/PATCH - they're all in here!
- **adafruit\_fakerequests.mpy&nbsp;** &nbsp;- This library allows you to create fake HTTP requests by using local files.
- **adafruit\_io** - this library helps connect the PyPortal to our free data logging and viewing service
- **adafruit\_bitmap\_font** - we have fancy font support, and it's easy to make new fonts. This library reads and parses font files.
- **adafruit\_display\_text** - not surprisingly, it displays text on the screen
- **adafruit\_lis3dh.mpy** - this library is used for the onboard accelerometer to detect the orientation of the MatrixPortal
- **adafruit\_minimqtt** - this is used for communicating with MQTT servers.

# Adafruit MatrixPortal M4

## Create Your settings.toml File

CircuitPython works with WiFi-capable boards to enable you to make projects that have network connectivity. This means working with various passwords and API keys. As of [CircuitPython 8](https://circuitpython.org/downloads), there is support for a **settings.toml** file. This is a file that is stored on your **CIRCUITPY** drive, that contains all of your secret network information, such as your SSID, SSID password and any API keys for IoT services. It is designed to separate your sensitive information from your **code.py** file so you are able to share your code without sharing your credentials.

CircuitPython previously used a **secrets.py** file for this purpose. The **settings.toml** file is quite similar.

Warning: Your **settings.toml** file should be stored in the main directory of your **CIRCUITPY** drive. It should not be in a folder.

## CircuitPython **settings.toml** File

This section will provide a couple of examples of what your **settings.toml** file should look like, specifically for CircuitPython WiFi projects in general.

The most minimal **settings.toml** file must contain your WiFi SSID and password, as that is the minimum required to connect to WiFi. Copy this example, paste it into your **settings.toml** , and update:

- `your_wifi_ssid`
- `your_wifi_password`

```auto
CIRCUITPY_WIFI_SSID = "your_wifi_ssid"
CIRCUITPY_WIFI_PASSWORD = "your_wifi_password"
```

Many CircuitPython network-connected projects on the Adafruit Learn System involve using Adafruit IO. For these projects, you must _also_ include your Adafruit IO username and key. Copy the following example, paste it into your settings.toml file, and update:

- `your_wifi_ssid`
- `your_wifi_password`
- `your_aio_username`
- `your_aio_key`

```auto
CIRCUITPY_WIFI_SSID = "your_wifi_ssid"
CIRCUITPY_WIFI_PASSWORD = "your_wifi_password"
ADAFRUIT_AIO_USERNAME = "your_aio_username"
ADAFRUIT_AIO_KEY = "your_aio_key"
```

Some projects use different variable names for the entries in the **settings.toml** file. For example, a project might use `ADAFRUIT_AIO_ID` in the place of `ADAFRUIT_AIO_USERNAME`. **If you run into connectivity issues, one of the first things to check is that the names in the settings.toml file match the names in the code.**

Warning: Not every project uses the same variable name for each entry in the **settings.toml** file! Always verify it matches the code.

## **settings.toml** File Tips
Here is an example **settings.toml** file.

```auto
# Comments are supported
CIRCUITPY_WIFI_SSID = "guest wifi"
CIRCUITPY_WIFI_PASSWORD = "guessable"
CIRCUITPY_WEB_API_PORT = 80
CIRCUITPY_WEB_API_PASSWORD = "passw0rd"
test_variable = "this is a test"
thumbs_up = "\U0001f44d"
```

In a **settings.toml** file, it's important to keep these factors in mind:

- Strings are wrapped in double quotes; ex: `"your-string-here"`
- Integers are _ **not** _ quoted and may be written in decimal with optional sign (`+1`, `-1`, `1000`) or hexadecimal (`0xabcd`).
  - Floats (decimal numbers), octal (`0o567`) and binary (`0b11011`) are not supported.

- Use `\u` escapes for weird characters, `\x` and `\ooo` escapes are not available in **.toml** files
  - Example: `\U0001f44d` for 👍 (thumbs up emoji) and `\u20ac` for € (EUR sign)

- Unicode emoji, and non-ASCII characters, stand for themselves as long as you're careful to save in "UTF-8 without BOM" format

&nbsp;

&nbsp;

When your&nbsp; **settings.toml&nbsp;** file is ready, you can save it in your text editor with the **.toml** &nbsp;extension.

![adafruit_products_dotToml.jpg](https://cdn-learn.adafruit.com/assets/assets/000/117/071/medium640/adafruit_products_dotToml.jpg?1671034293)

## Accessing Your **settings.toml** Information in **code.py**
In your **code.py** file, you'll need to `import` the `os` library to access the **settings.toml** file. Your settings are accessed with the `os.getenv()` function. You'll pass your settings entry to the function to import it into the **code.py** file.

```python
import os

print(os.getenv("test_variable"))
```

![](https://cdn-learn.adafruit.com/assets/assets/000/117/072/medium800/adafruit_products_tomlOutput.jpg?1671034496)

In the upcoming CircuitPython WiFi examples, you'll see how the **settings.toml&nbsp;** file is used for connecting to your SSID and accessing your API keys.

# Adafruit MatrixPortal M4

## Internet Connect!

# Connect to WiFi

OK, now that you have your&nbsp; **settings.toml** file set up - you can connect to the Internet.

To do this, 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 **examples/** 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](https://adafruit.github.io/Adafruit_CircuitPython_Bundle/esp32spi_esp32spi_simpletest.py.png )

Info: Update to CircuitPython 9.2.x or later to use this example.

https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/blob/main/examples/esp32spi_simpletest.py

And save it to your board, with the name **code.py**.

Don't forget you'll also need to create the **settings.toml** file as seen above, with your WiFi ssid and password.

In a serial console, you should see something like the following. For more information about connecting with a serial console, view the guide [Connecting to the Serial Console](https://learn.adafruit.com/welcome-to-circuitpython/kattni-connecting-to-the-serial-console).

```terminal
&gt;&gt;&gt; import wifitest
ESP32 SPI webclient test
ESP32 found and in idle mode
Firmware vers. 1.7.5
MAC addr: 24:C9:DC:BD:0F:3F
	HomeNetwork             RSSI: -46
	HomeNetwork             RSSI: -76
	Fios-12345              RSSI: -92
	FiOS-AB123              RSSI: -92
	NETGEAR53               RSSI: -93
Connecting to AP...
Connected to HomeNetwork 	RSSI: -45
My IP address is 192.168.1.245
IP lookup adafruit.com: 104.20.39.240
Ping google.com: 30 ms
Fetching text from http://wifitest.adafruit.com/testwifi/index.html
----------------------------------------
This is a test of Adafruit WiFi!
If you can read this, its working :)
----------------------------------------

Fetching json from http://wifitest.adafruit.com/testwifi/sample.json
----------------------------------------
{'fun': True, 'company': 'Adafruit', 'founded': 2005, 'primes': [2, 3, 5], 'pi': 3.14, 'mixed': [False, None, 3, True, 2.7, 'cheese']}
----------------------------------------
Done!
```

Going over the example above, here's a breakdown of what the program is doing:

- Initialize the ESP32 over SPI using the SPI port and 3 control pins:

```python
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

#...

else:
    spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
```

- Get the socket pool and the SSL context, and then tell the `adafruit_requests` library about them.

```python
pool = adafruit_connection_manager.get_radio_socketpool(esp)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
requests = adafruit_requests.Session(pool, ssl_context)
```

- Verify an ESP32 is found, checks the firmware and MAC address

```auto
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
print("Firmware vers.", esp.firmware_version)
print("MAC addr:", ":".join("%02X" % byte for byte in esp.MAC_address))
```

- Perform a scan of all access points it can see and print out the name and signal strength.

```python
for ap in esp.scan_networks():
    print("\t%-23s RSSI: %d" % (ap.ssid, ap.rssi))
```

- Connect to the AP we've defined here, then print out the local IP address. Then attempt to do a domain name lookup and ping google.com to check network connectivity. (Note sometimes the ping fails or takes a while; this isn't a big deal.)

```python
print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(ssid, password)
    except OSError as e:
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", esp.ap_info.ssid, "\tRSSI:", esp.ap_info.rssi)
print("My IP address is", esp.ipv4_address)
print(
    "IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com"))
)
```

Now we're getting to the really interesting part of the example program. We've written a library for web fetching web data, named [adafruit\_requests](https://github.com/adafruit/Adafruit_CircuitPython_Requests). It is a lot like the regular Python library named [requests](https://requests.readthedocs.io/en/latest/). This library allows you to send HTTP and HTTPS requests easily and provides helpful methods for parsing the response from the server.

- Here is the part of the example program is fetching text data from a URL.

```python
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"  # Further up in the program

# ...

print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL)
print('-' * 40)
print(r.text)
print('-' * 40)
r.close()
```

- Finally, here the program is fetching some JSON data. The `adafruit_requests` library will parse the JSON into a Python dictionary whose structure is the same as the structure of the JSON.

```auto
JSON_URL = "http://wifitest.adafruit.com/testwifi/sample.json"   # Further up in the program

# ...

print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL)
print('-' * 40)
print(r.json())
print('-' * 40)
r.close()
```

# Advanced Requests Usage

Want to send custom HTTP headers, parse the response as raw bytes, or handle a response's http status code in your CircuitPython code?

We've written an&nbsp;example to show advanced usage of the requests module below.

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 **examples/** 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.

https://github.com/adafruit/Adafruit_CircuitPython_Requests/blob/main/examples/esp32spi/requests_esp32spi_advanced.py

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

![CIRCUITPY](https://adafruit.github.io/Adafruit_CircuitPython_Bundle/requests_esp32spi_requests_esp32spi_advanced.py.png )

# WiFi Manager

The way the examples above connect to WiFi works but it's a little finicky. Since WiFi is not necessarily so reliable, you may have disconnects and need to reconnect. For more advanced uses, we recommend using the `WiFiManager` class. It will wrap the connection/status/requests loop for you - reconnecting if WiFi drops, resetting the ESP32 if it gets into a bad state, etc.

Here's a more advanced example that shows using the `WiFiManager` and also how to fetch the current time from a web source.

https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/blob/main/examples/esp32spi_localtime.py

# Further Information

For more information on the basics of doing networking in CircuitPython, see this guide:

### Networking in CircuitPython

[Networking in CircuitPython](https://learn.adafruit.com/networking-in-circuitpython)
# Adafruit MatrixPortal M4

## MatrixPortal Library Overview

The MatrixPortal library was inspired by the PyPortal library, but a slightly different approach was taken. Rather than having everything in a single module, it was divided into layers. The reason for having different layers is you can use lower layers if you want more control and better memory usage.

The main library now piggyback's on top of the base library. The base library was named PortalBase which is split up into 3 components. The main base, the GraphicsBase, and the NetworkBase. In the diagram, you can see these components represented in blue.

[We also have a library for lower-level control of just the RGB Matrix](https://learn.adafruit.com/rgb-led-matrices-matrix-panels-with-circuitpython), but it doesn't have integrated WiFi access so we recommend using the MatrixPortal library.

Here is the way it is logically laid out with dependencies. The MatrixPortal library is comprised of the top layer, the Network and Graphics layers, and the WiFi and Matrix layers in the diagram.

![](https://cdn-learn.adafruit.com/assets/assets/000/098/460/medium800/led_matrices_MatrixPortal_Hierarchy.png?1609871487)

There are two main branches of dependencies related to Network Functionality and Graphics functionality. The **MatrixPortal** library ties them both together and allows easier coding, but at the cost of more memory usage and less control. We'll go through each of the classes starting from the bottom and working our way up the diagram starting with the Network branch.

## Network Branch

The network branch contains all of the functionality related to connecting to the internet and retrieving data. You will want to use this branch if your project need to retrieve any data that is not stored on the device itself.

### WiFi Module

The WiFi module is responsible for initializing the hardware libraries, controlling the status NeoPixel colors, and initializing the WiFi manager. You would want to use this library if you only wanted to handle the automatic initialization of hardware and connection to WiFi and didn't need any other functionality.

### Network Module

The network module has many convenience functions for making network calls. It handles a lot of things from automatically establishing the connection to getting the time from the internet, to getting data at certain URLs. This is one of the largest of the modules as there is a lot of functionality packed into this.

## Graphics Branch

This branch is a lot lighter than the Network Branch because so much of the functionality is built into CircuitPython and displayio.

### Matrix Module

The matrix module is responsible for detecting and initializing the matrix through the CircuitPython rgbmatrix and framebufferio modules. It currently supports the MatrixPortal M4 and Metro M4 with RGB Matrix Shield. If you just wanted to initialize the matrix, you could use this module. If you would like to go lower level than this and use the rgbmatrix and framebufferio libraries directly, be sure to check out the guide [RGB LED Matrices with CircuitPython](https://learn.adafruit.com/rgb-led-matrices-matrix-panels-with-circuitpython).

### Graphics Module

This module will initialize the Matrix through the matrix module. The main purpose of this module was to add any graphics convenience functions in such as displaying a background easily.

## MatrixPortal Module

The MatrixPortal module is top level module and will handle initializing everything below it. Using this module is very similar to using the PyPortal library. The main differences are:

- Text labels are added after the module is initialized.
- Text labels can either be scrolling or static.
- There are more Adafruit IO functions

## Library Demos

The MatrixPortal library has been used in a number of projects. Here are a few of them with guides available.

- [RGB Matrix Automatic YouTube ON AIR Sign](https://learn.adafruit.com/rgb-matrix-automatic-youtube-on-air-sign)
- [Network Connected RGB Matrix Clock](https://learn.adafruit.com/network-connected-metro-rgb-matrix-clock)
- [Weather Display Matrix](https://learn.adafruit.com/weather-display-matrix)
- [Custom Scrolling Quote Board Matrix Display](https://learn.adafruit.com/aio-quote-board-matrix-display)
- [Halloween Countdown Display Matrix](https://learn.adafruit.com/halloween-countdown-display-matrix)
- [Moon Phase Clock for Adafruit Matrix Portal](https://learn.adafruit.com/moon-phase-clock-for-adafruit-matrixportal)

# Adafruit MatrixPortal M4

## CircuitPython Pins and Modules

CircuitPython is designed to run on microcontrollers and allows you to interface with all kinds of sensors, inputs and other hardware peripherals. There are tons of guides showing how to wire up a circuit, and use CircuitPython to, for example, read data from a sensor, or detect a button press. Most CircuitPython code includes hardware setup which requires various modules, such as `board` or `digitalio`. You import these modules and then use them in your code. How does CircuitPython know to look for hardware in the specific place you connected it, and where do these modules come from?

This page explains both. You'll learn how CircuitPython finds the pins on your microcontroller board, including how to find the available pins for your board and what each pin is named. You'll also learn about the modules built into CircuitPython, including how to find all the modules available for your board.

# CircuitPython Pins

When using hardware peripherals with a CircuitPython compatible microcontroller, you'll almost certainly be utilising pins. This section will cover how to access your board's pins using CircuitPython, how to discover what pins and board-specific objects are available in CircuitPython for your board, how to use the board-specific objects, and how to determine all available pin names for a given pin on your board.

## `import board`

When you're using any kind of hardware peripherals wired up to your microcontroller board, the import list in your code will include `import board`. The `board` module is built into CircuitPython, and is used to provide access to a series of board-specific objects, including pins. Take a look at your microcontroller board. You'll notice that next to the pins are pin labels. You can always access a pin by its pin label. However, there are almost always multiple names for a given pin.

To see all the available board-specific objects and pins for your board, enter the REPL (`>>>`) and run the following commands:

```python
import board
dir(board)
```

Here is the output for the QT Py SAMD21. **You may have a different board, and this list will vary, based on the board.**

![](https://cdn-learn.adafruit.com/assets/assets/000/099/189/medium800/circuitpython_dir-board-output-qt-py.png?1612291495)

The following pins have labels on the physical QT Py SAMD21 board: A0, A1, A2, A3, SDA, SCL, TX, RX, SCK, MISO, and MOSI. You see that there are many more entries available in `board` than the labels on the QT Py.

You can use the pin names on the physical board, regardless of whether they seem to be specific to a certain protocol.

For example, you do not _have_ to use the SDA pin for I2C - you can use it for a button or LED.

On the flip side, there may be multiple names for one pin. For example, on the QT Py SAMD21, pin **A0** is labeled on the physical board silkscreen, but it is available in CircuitPython as both `A0` and `D0`. For more information on finding all the names for a given pin, see the [What Are All the Available Pin Names?](https://learn.adafruit.com/circuitpython-essentials/circuitpython-pins-and-modules#what-are-all-the-available-names-3082670-14) section below.

The results of `dir(board)` for CircuitPython compatible boards will look similar to the results for the QT Py SAMD21 in terms of the pin names, e.g. A0, D0, etc. However, some boards, for example, the Metro ESP32-S2, have different styled pin names. Here is the output for the Metro ESP32-S2.

![](https://cdn-learn.adafruit.com/assets/assets/000/099/215/medium800/circuitpython_Essentials_dir_board_Metro_ESP32-S2.png?1612374794)

Note that most of the pins are named in an IO# style, such as **IO1** and **IO2**. Those pins on the physical board are labeled only with a number, so an easy way to know how to access them in CircuitPython, is to run those commands in the REPL and find the pin naming scheme.

Info: 

## I2C, SPI, and UART

You'll also see there are often (_ **but not always!** _) three special board-specific objects included: `I2C`, `SPI`, and `UART` - each one is for the default pin-set used for each of the three common protocol busses they are named for. These are called _singletons_.

What's a singleton? When you create an object in CircuitPython, you are _instantiating_ ('creating') it. Instantiating an object means you are creating an instance of the object with the unique values that are provided, or "passed", to it.

For example, When you instantiate an I2C object using the `busio` module, it expects two pins: clock and data, typically SCL and SDA. It often looks like this:

```python
i2c = busio.I2C(board.SCL, board.SDA)
```

Then, you pass the I2C object to a driver for the hardware you're using. For example, if you were using the TSL2591 light sensor and its CircuitPython library, the next line of code would be:

```python
tsl2591 = adafruit_tsl2591.TSL2591(i2c)
```

However, CircuitPython makes this simpler by including the `I2C` singleton in the `board` module. Instead of the two lines of code above, you simply provide the singleton as the I2C object. So if you were using the TSL2591 and its CircuitPython library, the two above lines of code would be replaced with:

```python
tsl2591 = adafruit_tsl2591.TSL2591(board.I2C())
```

Info: 

This eliminates the need for the `busio` module, and simplifies the code. Behind the scenes, the `board.I2C()`&nbsp; object is instantiated when you call it, but not before, and on subsequent calls, it returns the same object. Basically, it does not create an object until you need it, and provides the same object every time you need it. You can call `board.I2C()` as many times as you like, and it will always return the same object.

Info: 

## What Are All the Available Names?

Many pins on CircuitPython compatible microcontroller boards have multiple names, however, typically, there's only one name labeled on the physical board. So how do you find out what the other available pin names are? Simple, with the following script! Each line printed out to the serial console contains the set of names for a particular pin.

On a microcontroller board running CircuitPython, first, connect to the serial console.

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\_Essentials/Pin\_Map\_Script/** 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](https://adafruit.github.io/Adafruit_Learning_System_Guides/CircuitPython_Essentials_Pin_Map_Script.png )

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/CircuitPython_Essentials/Pin_Map_Script/code.py

Here is the result when this script is run on QT Py SAMD21:

![](https://cdn-learn.adafruit.com/assets/assets/000/122/945/medium800/leds_CPE_pin_map_script_QT_Py_M0.png?1690233285)

Each line represents a single pin. Find the line containing the pin name that's labeled on the physical board, and you'll find the other names available for that pin. For example, the first pin on the board is labeled **A0**. The first line in the output is `board.A0 board.D0 (PA02)`. This means that you can access pin **A0** in CircuitPython using both `board.A0` and `board.D0`.

The pins in parentheses are the microcontroller pin names. See the next section for more info on those.

You'll notice there are two "pins" that aren't labeled on the board but appear in the list: `board.NEOPIXEL` and `board.NEOPIXEL_POWER`. Many boards have several of these special pins that give you access to built-in board hardware, such as an LED or an on-board sensor. The QT Py SAMD21 only has one on-board extra piece of hardware, a NeoPixel LED, so there's only the one available in the list. But you can also control whether or not power is applied to the NeoPixel, so there's a separate pin for that.

That's all there is to figuring out the available names for a pin on a compatible microcontroller board in CircuitPython!

## Microcontroller Pin Names

The pin names available to you in the CircuitPython `board` module are not the same as the names of the pins on the microcontroller itself. The board pin names are aliases to the microcontroller pin names. If you look at the datasheet for your microcontroller, you'll likely find a pinout with a series of pin names, such as "PA18" or "GPIO5". If you want to get to the actual microcontroller pin name in CircuitPython, you'll need the `microcontroller.pin` module. As with `board`, you can run `dir(microcontroller.pin)` in the REPL to receive a list of the microcontroller pin names.

![](https://cdn-learn.adafruit.com/assets/assets/000/099/290/medium800/circuitpython_Essentials_microcontroller_pin_names.png?1612822277 Microcontroller pin names for QT Py SAMD21.)

# CircuitPython Built-In Modules

There is a set of modules used in most CircuitPython programs. One or more of these modules is always used in projects involving hardware. Often hardware requires installing a separate library from the Adafruit CircuitPython Bundle. But, if you try to find `board` or `digitalio` in the same bundle, you'll come up lacking. So, where do these modules come from? They're built into CircuitPython! You can find an comprehensive list of built-in CircuitPython modules and the technical details of their functionality from CircuitPython [here](https://circuitpython.readthedocs.io/en/latest/shared-bindings/index.html#modules) and the Python-like modules included [here](https://circuitpython.readthedocs.io/en/latest/docs/library/index.html). However, **not every module is available for every board** due to size constraints or hardware limitations. How do you find out what modules are available for your board?

There are two options for this. You can check the [support matrix](https://circuitpython.readthedocs.io/en/latest/shared-bindings/support_matrix.html#), and search for your board by name. Or, you can use the REPL.

Plug in your board, connect to the serial console and enter the REPL. Type the following command.

```python
help("modules")
```

![](https://cdn-learn.adafruit.com/assets/assets/000/099/208/medium800/circuitpython_Essentials_help_modules_QT_Py.png?1612372532 help("modules") results for QT Py)

That's it! You now know two ways to find all of the modules built into CircuitPython for your compatible microcontroller board.

# Adafruit MatrixPortal M4

## PortalBase Library Docs

# Adafruit MatrixPortal M4

## MatrixPortal Library Docs

# Adafruit MatrixPortal M4

## CircuitPython RGB Matrix Library

# Adafruit MatrixPortal M4

## CircuitPython BLE

## CircuitPython BLE UART Example

It's easy to use Adafruit AirLift ESP32 co-processor boards for Bluetooth Low Energy (BLE) with CircuitPython. When you reset the ESP32, you can put it in WiFi mode (the default), or in BLE mode; you cannot use both modes simultaneously.

Here's a simple example of using BLE to connect CircuitPython with the Bluefruit Connect app. Use CircuitPython 6.0.0 or later.

**Note:** Don't confuse the **ESP32** with the **ESP32-S2** , which is a different module with a similar name. The ESP32-S2 does not support BLE.

Warning: Currently, AirLift BLE support is not currently available on boards with Espressif chips. If the Espressif board provides `_bleio`, it is for native BLE support (e.g. ESP32-S3), not AirLift.

Info: 

## On-Board Airlift Co-Processor - No Wiring Needed

If you have an **Adafruit Metro M4 AirLift Lite** , an **Adafruit PyPortal** (regular, **Pynt** or **Titano** ), an **Adafruit MatrixPortal** , or other Adafruit board with an onboard ESP32 co-processor, then everything is prewired for you, and the pins you need to use are predefined in CircuitPython.

## Update the AirLift Firmware

You will need to update the AirLift's firmware to at least version 1.7.1. **Previous versions of the AirLift firmware do not support BLE.&nbsp;**

Follow the instructions in the guide below, and come back to this page when you've upgraded the AirLift's firmware:

[Upgrade ESP32 AirLift Firmware](https://learn.adafruit.com/upgrading-esp32-firmware/upgrade-all-in-one-esp32-airlift-firmware)
Warning: 

## Install CircuitPython Libraries

First make sure you are running the [latest version of Adafruit CircuitPython](https://learn.adafruit.com/welcome-to-circuitpython/installing-circuitpython) for your board.

Next you'll need to install the necessary libraries to use the hardware. 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, and copy the **entire lib folder** and the **code.py** file to your **CIRCUITPY** drive.

Your **CIRCUITPY/lib** folder should contain the following folders and files:

- **/adafruit\_airlift**
- **/adafruit\_ble**
- **/adafruit\_bus\_device**
- **/adafruit\_esp32spi**
- **adafruit\_requests.mpy**

![CIRCUITPY](https://adafruit.github.io/Adafruit_Learning_System_Guides/CircuitPython_Templates_airlift_ble_example.png )

## Install the Adafruit Bluefruit LE Connect App

The Adafruit Bluefruit LE Connect iOS and Android apps allow you to connect to BLE peripherals that provide a over-the-air "UART" service. Follow the instructions in the [Bluefruit LE Connect Guide](https://learn.adafruit.com/bluefruit-le-connect/) to download and install the app on your phone or tablet.

## BLE Example
Warning: 

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/CircuitPython_Templates/airlift_ble_example/code.py

## Talk to the AirLift via the Bluefruit LE Connect App

Start the Bluefruit LE Connect App on your phone or tablet. You should see a CIRCUITPY device available to connect to. Tap the Connect button (1):

![](https://cdn-learn.adafruit.com/assets/assets/000/096/566/medium800/adafruit_products_airlift-connect.png?1603914360)

You'll then see a list of Bluefruit Connect functions ("modules"). Choose the UART module (2):

![](https://cdn-learn.adafruit.com/assets/assets/000/096/567/medium800/adafruit_products_airlift-uart.png?1603914460)

On the UART module page, you can type a string and press Send (3). You'll see that string entered, and then see it echoed back (echoing is in gray).

![](https://cdn-learn.adafruit.com/assets/assets/000/096/569/medium800/adafruit_products_airlift-echo.png?1603914605)

# Adafruit MatrixPortal M4

## Arduino IDE Setup

The first thing you will need to do is to download the latest release of the Arduino IDE. You will need to&nbsp;be using **version 1.8** or higher for this guide

[Arduino IDE Download](http://www.arduino.cc/en/Main/Software)
After you have downloaded and installed **the latest version of Arduino IDE** , you will need to start the IDE&nbsp;and navigate to&nbsp;the **Preferences** menu. You can access it from the **File** menu in _Windows_ or _Linux_, or the **Arduino** menu on _OS X_.

![](https://cdn-learn.adafruit.com/assets/assets/000/041/549/medium800/flora_prefs.png?1494204209)

A dialog will pop up just like the one shown below.

![](https://cdn-learn.adafruit.com/assets/assets/000/108/455/medium800/trinket_arduino-preferences-before.png?1643387570)

We will be adding a URL to the new **Additional Boards Manager URLs** option. The list of URLs is comma separated, and _you will only have to add each&nbsp;URL once._&nbsp;New Adafruit boards and updates to existing boards&nbsp;will automatically be picked up&nbsp;by the Board Manager each time&nbsp;it is opened. The URLs point to index files that the Board Manager uses to build the list of available & installed boards.

To find the most up to date list of URLs you can&nbsp;add, you can visit the list of [third party board URLs on the Arduino IDE wiki](https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls#list-of-3rd-party-boards-support-urls). We will only need to add one URL to the IDE in this example, but _ **you can add multiple URLS by separating them with commas** _. Copy and paste the link below into the&nbsp; **Additional Boards Manager URLs** option in the Arduino IDE preferences.

### `https://adafruit.github.io/arduino-board-index/package_adafruit_index.json`
![](https://cdn-learn.adafruit.com/assets/assets/000/108/456/medium800/trinket_arduino-preferences.png?1643387643)

Here's a short description of each of the Adafruit supplied packages that will be available in the Board Manager when you add the URL:

- **Adafruit AVR Boards** - Includes support for Flora, Gemma, Feather 32u4, ItsyBitsy 32u4, Trinket, & Trinket Pro.
- **Adafruit SAMD Boards** - Includes support for Feather M0 and M4, Metro M0 and M4, ItsyBitsy M0 and M4, Circuit Playground Express, Gemma M0 and Trinket M0
- **Arduino Leonardo & Micro MIDI-USB** - This adds MIDI over USB support for the Flora, Feather 32u4, Micro and Leonardo using the [arcore project](https://github.com/rkistner/arcore).

If you have multiple boards you want to support, say ESP8266 and Adafruit, have both URLs in the text box separated by a comma (,)

Once done click **OK** to save the new preference settings. Next we will look at installing boards with the Board Manager.

Now continue to the next step to actually install the board support package!

# Adafruit MatrixPortal M4

## Using with Arduino IDE

Adafruit boards that use ATSAMD21 ("M0") or ATSAMD51 ("M4") chips are easy to get working with the Arduino IDE. Most libraries (including the popular ones like NeoPixels and display) will work with those boards, especially devices & sensors that use I2C or SPI.

Now that you have added the appropriate URLs to the Arduino IDE preferences in the previous page, you can open the **Boards Manager** by navigating to the **Tools-\>Board** &nbsp;menu.

![](https://cdn-learn.adafruit.com/assets/assets/000/028/791/medium800/adafruit_products_boardmanager.png?1448652571)

Once the Board Manager opens, click on the category drop down menu on the top left hand side of the window and select **All**. You will then be able to select and install the boards supplied&nbsp;by the URLs added to the preferences.

Warning: 

# Install SAMD Support

First up, install the latest **Arduino SAMD Boards (**version **1.6.11&nbsp;** or later)

You can type **Arduino SAMD** in the top search bar, then when you see the entry, click **Install**

![](https://cdn-learn.adafruit.com/assets/assets/000/028/792/medium800/adafruit_products_arduinosamd162.png?1448652786)

# Install Adafruit SAMD

Next you can install the Adafruit SAMD package to add the board file definitions

Make sure you have **Type All** selected to the left of the _Filter your search..._ box

You can type **Adafruit SAMD** in the top search bar, then when you see the entry, click **Install**

![](https://cdn-learn.adafruit.com/assets/assets/000/028/794/medium800/adafruit_products_adafruitsamd.png?1448652973)

 **Quit and reopen&nbsp;the Arduino IDE** to ensure that all of the boards are properly installed. You should now be able to select and upload to the new boards listed in the **Tools-\>Board** menu.

Select the matching board, the current options are:

- **Feather M0** (for use with any Feather M0 other than the Express)
- **Feather M0 Express**
- **Metro M0 Express**
- **Circuit Playground Express**  
- **Gemma M0**
- **Trinket M0**  
- **QT Py M0**  
- **ItsyBitsy M0**
- **Hallowing M0**
- **Crickit M0** (this is for direct programming of the Crickit, which is probably not what you want! For advanced hacking only)
- **Metro M4 Express**
- **Grand Central M4 Express**
- **ItsyBitsy M4 Express**
- **Feather M4 Express**
- **Trellis M4 Express**
- **PyPortal M4**
- **PyPortal M4 Titano**
- **PyBadge M4 Express**
- **Metro M4 Airlift Lite**
- **PyGamer M4 Express**
- **MONSTER M4SK**
- **Hallowing M4**
- **MatrixPortal M4**
- **BLM Badge**

![](https://cdn-learn.adafruit.com/assets/assets/000/053/074/medium800/adafruit_products_availboards.png?1524019356)

## Windows 7 and 8.1
Warning: **Windows 7 and Windows 8.1** have reached end-of-life and are no longer supported. They required driver installation. A [limited set of drivers is available for older boards](https://github.com/adafruit/Adafruit_Windows_Drivers/releases), but drivers for most newer boards are not available.

# Blink

Now you can upload your first blink sketch!

Plug in the SAMD21 M0 or SAMD51 M4 board, and wait for it to be recognized by the OS (just takes a few seconds). It will create a serial/COM port, you can now select it from the drop-down, it'll even be 'indicated' as Trinket/Gemma/Metro/Feather/ItsyBitsy/QT Py/Trellis or whatever the board is named!

Info: A few boards, such as the QT Py SAMD21, Trellis M4 Express, and certain Trinkey boards, do not have an onboard pin 13 LED. You can follow this section to practice uploading but you won't see an LED blink!

![](https://cdn-learn.adafruit.com/assets/assets/000/028/796/medium800/adafruit_products_comport.png?1448653712)

Now load up the Blink 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
}
```

And click upload! That's it, you will be able to see the LED blink rate change as you adapt the **delay()** calls.

Info: 

# Successful Upload

If you have a successful upload, you'll get a bunch of red text that tells you that the device was found and it was programmed, verified & reset

![](https://cdn-learn.adafruit.com/assets/assets/000/028/797/medium800/adafruit_products_uploading.png?1448653908)

After uploading, you may see a message saying "Disk Not&nbsp;Ejected&nbsp;Properly" about the ...BOOT drive. You can ignore that message: it's an artifact of how the bootloader and uploading work.

# Compilation Issues

If you get an alert that looks like

**Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-non-eabi-g++"**

Make sure you have installed the **Arduino SAMD** boards package, you need _both_ Arduino & Adafruit SAMD board packages

![](https://cdn-learn.adafruit.com/assets/assets/000/028/798/medium800/adafruit_products_gppnotfound.png?1448653960)

# Manually bootloading

If you ever get in a 'weird' spot with the bootloader, or you have uploaded code that crashes and doesn't auto-reboot into the bootloader, click the **RST** button **twice** (like a double-click)to get back into the bootloader.

**The red LED will pulse and/or RGB LED will be green, so you know that its in bootloader mode.**

Once it is in bootloader mode, you can select the newly created COM/Serial port and re-try uploading.

![](https://cdn-learn.adafruit.com/assets/assets/000/028/799/medium800/adafruit_products_bootloadport.png?1448654424)

You may need to go back and reselect the 'normal' USB serial port next time you want to use the normal upload.

# Ubuntu&nbsp;& Linux Issue Fix

&nbsp;[Follow the steps for installing Adafruit's udev rules on this page.](../../../../adafruit-arduino-ide-setup/linux-setup#udev-rules)

# Adafruit MatrixPortal M4

## Arduino Libraries

OK now that you have Arduino IDE set up, drivers installed if necessary and you've practiced uploading code, you can start installing all the Libraries we'll be using to program it.

There's a lot of libraries!

# Install Libraries

Open up the library manager...

![](https://cdn-learn.adafruit.com/assets/assets/000/073/288/medium800/circuitpython_managelib.png?1552873775)

And install the following libraries:

## Adafruit NeoPixel

This will let you light up the status LED on the back

![](https://cdn-learn.adafruit.com/assets/assets/000/073/289/medium800/circuitpython_adafruit_products_image.png?1552873804)

## Adafruit SPIFlash

This is also needed to use the filesystem on QSPI

![](https://cdn-learn.adafruit.com/assets/assets/000/073/292/medium800/circuitpython_adafruit_products_SPIFlash_lib.jpg?1552873977)

## Adafruit Protomatter

This library is used for writing to the RGB Matrix.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/078/medium800/led_matrices_protomatter.png?1601053982)

## Adafruit LIS3DH

This will let you use the onboard accelerometer

![](https://cdn-learn.adafruit.com/assets/assets/000/095/077/medium800/led_matrices_lis3dh.png?1601053969)

## Adafruit GFX

This is the graphics library used to draw to the screen

![](https://cdn-learn.adafruit.com/assets/assets/000/073/293/medium800/circuitpython_image.png?1552874131)

If using an older (pre-1.8.10) Arduino IDE, locate and install **Adafruit\_BusIO** (newer versions do this automatically when installing Adafruit\_GFX).

## WiFiNINA

Will talk to the ESP32 WiFi co-processor to connect to the internet! We're using a variant of the Arduino WiFiNINA library, which is amazing and written by the Arduino team!&nbsp; **The official WiFi101 library won't work because it doesn't support the ability to change the pins**.

So! We made a fork that you can install. For more installation information see [Arduino IO Library](https://learn.adafruit.com/adafruit-io-basics-airlift/arduino-io-library).

[Download Adafruit's version of WiFiNINA](https://github.com/adafruit/WiFiNINA/archive/master.zip)
## Adafruit ImageReader

For reading bitmaps from SD and displaying

![](https://cdn-learn.adafruit.com/assets/assets/000/073/298/medium800/circuitpython_image.png?1552874434)

## Adafruit PixelDust

To compile and run the PixelDust demo, you will need this library. This library calculates where the particles should be.

![](https://cdn-learn.adafruit.com/assets/assets/000/095/079/medium800/led_matrices_pixeldust.png?1601054231)

# Adafruit MatrixPortal M4

## Using the Protomatter Library

Let’s look at a **minimal Arduino example** &nbsp;for the Adafruit\_Protomatter library to illustrate how this works (this is pared down from the “ **simple** ” example sketch):

```cpp
#include &lt;Adafruit_Protomatter.h&gt;

uint8_t rgbPins[]  = {7, 8, 9, 10, 11, 12};
uint8_t addrPins[] = {17, 18, 19, 20, 21};
uint8_t clockPin   = 14;
uint8_t latchPin   = 15;
uint8_t oePin      = 16;

Adafruit_Protomatter matrix(
  64, 4, 1, rgbPins, 4, addrPins, clockPin, latchPin, oePin, false);

void setup(void) {
  Serial.begin(9600);

  // Initialize matrix...
  ProtomatterStatus status = matrix.begin();
  Serial.print("Protomatter begin() status: ");
  Serial.println((int)status);
  if(status != PROTOMATTER_OK) {
    for(;;);
  }

  // Make four color bars (red, green, blue, white) with brightness ramp:
  for(int x=0; x&lt;matrix.width(); x++) {
    uint8_t level = x * 256 / matrix.width(); // 0-255 brightness
    matrix.drawPixel(x, matrix.height() - 4, matrix.color565(level, 0, 0));
    matrix.drawPixel(x, matrix.height() - 3, matrix.color565(0, level, 0));
    matrix.drawPixel(x, matrix.height() - 2, matrix.color565(0, 0, level));
    matrix.drawPixel(x, matrix.height() - 1, matrix.color565(level, level, level));
  }

  // Simple shapes and text, showing GFX library calls:
  matrix.drawCircle(12, 10, 9, matrix.color565(255, 0, 0));               // Red
  matrix.drawRect(14, 6, 17, 17, matrix.color565(0, 255, 0));             // Green
  matrix.drawTriangle(32, 9, 41, 27, 23, 27, matrix.color565(0, 0, 255)); // Blue
  matrix.println("ADAFRUIT"); // Default text color is white

  // AFTER DRAWING, A show() CALL IS REQUIRED TO UPDATE THE MATRIX!

  matrix.show(); // Copy data to matrix buffers
}

void loop(void) {
  Serial.print("Refresh FPS = ~");
  Serial.println(matrix.getFrameCount());
  delay(1000);
}
```

Breaking it down into steps…

# Include Protomatter Library

First is to `#include` the library’s header file. This in turn `#includes` **Adafruit\_GFX.h** , so you don’t have to.

```cpp
#include &lt;Adafruit_Protomatter.h&gt;
```

# Setting Up Matrix Pin Usage

The next few lines spell out the pin numbers being used. Using variables for this isn’t entirely necessary…one _could_ just pass the same numeric values directly to functions…but it makes the code a little more self-documenting (and easier to adapt the same sketch for multiple boards — the full example code has #ifdefs for each board with different pin assignments). These also could be `#defines` or `const` if one wants to be all Proper™ about it.

_Technical stuff for developers, skip this if you just want to use the library:_

This is the one part of the Arduino code where **some knowledge of the underlying hardware is required**. `rgbPins[]` and `clockPin` **must all be on the same GPIO PORT peripheral** (e.g. all PORTA, all PORTB, etc.). The **other pins have no such restrictions**. Additionally, if the PORT has an atomic bit-toggle register, RAM requirements are minimized if `rgbPins[]` and `clockPin` are all **within the same byte** of that PORT\*. They _do not need to be contiguous nor in any particular sequence_ within that byte. If not within the same byte, next most efficient has them in the same upper or lower 16-bit word of the PORT. Scattered around a full 32-bit PORT still works but is the least RAM-efficient option.

\* For devices lacking an atomic bit-toggle register…`clockPin` _does not_ need to be in the same byte, but still must be in the same PORT. Should still aim for `rgbPins[]` in a single byte or word though!

With those constraints in mind, here’s what the code looks like for an Adafruit MatrixPortal M4 with a 64x32 pixel matrix:

```cpp
uint8_t rgbPins[]  = {7, 8, 9, 10, 11, 12};
uint8_t addrPins[] = {17, 18, 19, 20, 21};
uint8_t clockPin   = 14;
uint8_t latchPin   = 15;
uint8_t oePin      = 16;
```

The full “simple” example sketch has setups for a number of different boards and adapters.

# Create the Protomatter Object

Next, still in the global area above `setup()`, we call the _constructor._ The Arduino library can only drive one matrix at a time (or one _chain_ of matrices, where “out” from one is linked to “in” of the next), so we just have one instance of an `Adafruit_Protomatter` object here, which we’ll call `matrix`:

```cpp
Adafruit_Protomatter matrix(
  64, 4, 1, rgbPins, 4, addrPins, clockPin, latchPin, oePin, false);
```

The `Adafruit_Protomatter` constructor expects between 9 and 11 arguments depending on the situation. The vital ones here, in order, are:

- `64` — the total matrix chain width, in pixels. This will usually be `64` or `32`, the width of most common RGB LED matrices…but, if you have some other size or multiple matrices chained together, add up the total width here. For example, three chained 32-pixel-wide matrices would be `96`.
- `4` — the bit depth, in planes, from 1 to 6 (see below). More bitplanes provides greater color fidelity at the expense of more RAM. A value of 4 here (4 bits) provides 16 brightness levels each for red, green and blue — yielding 4,096 distinct colors possible.
- `1` — the number of matrix chains in parallel. This will almost always be 1, but the library could conceivably support up to 5, _if_ the hardware driving it is set up _precisely just so._
- `rgbPins` — a `uint8_t` array of pin numbers, which issue the red, green and blue data for the upper and lower half of the matrix (sometimes labeled R1, G1, B1, R2, G2, B2 on the matrix input).. The array should contain six times the prior argument…so, usually, six. If driving two chains in parallel, then 12 pin numbers and so forth. Obviously 12 pins won’t fit in a single PORT byte, and you should aim for the upper or lower 16 bit word in that case, for best RAM utilization. Three or more chains, doesn’t matter, but the pins all do still need to be in the same PORT.
- `4` — the number of row-select “address lines” used by the LED matrix (sometimes labeled A, B, C, etc. on the matrix input). 16-pixel-tall matrices will be three row-select lines, 32-pixel will have four, and 64-pixel will have five. Matrix height is always _inferred_ from this value, not passed explicitly like width.
- `addrPins` — a `uint8_t` array of pin numbers, one for each row-select address line, starting from least-significant bit. These _do not_ need to be on the same PORT as `rgbPins` or each other…they can be mixed about anywhere.
- `clockPin` — pin number which drives the RGB clock (CLK on matrix input). This _must_ be on the same PORT register as `rgbPins`, and in most cases should also try to be in the same _byte._
- `latchPin` — pin number for “latch” signal (LAT on matrix input), indicating end-of-data. Can be any output-capable pin, no special constraints.
- `oePin` — pin number for “!OE” signal (output-enable low, OE on matrix input). Can be any output-capable pin, no special constraints.
- `false` — this flag indicates if the display should be _double-buffered,_ better for animation at the expense of double the RAM usage. Since the protomatter example isn’t using animation, it passes `false` here…but if you look at the **doublebuffer\_scrolltext** example, it uses `true`. A double-buffered display only modifies the matrix between refreshes, avoiding “tearing” artifacts. Optional. Default, if left unspecified, is `false`.
- Not used here, an optional 11th argument supports “tiling” of matrices vertically. Horizontal tiling is already implicit in the first argument — if you had two 64x32 matrices side-by-side, you’d pass 128 there. But if you had _four_ such matrices arranged 2x2, you’d still pass 128 for the first argument, but then add either 2 here (if cabling is in a “progressive” order) or -2 (if a “serpentine” order, where the second row of panels is rotated 180° relative to the first…the cabling is a little easier). The “tiled.ino” example demonstrates this. The concept is explained further in the [CircuitPython LED Matrix guide](https://learn.adafruit.com/rgb-led-matrices-matrix-panels-with-circuitpython/advanced-multiple-panels)…the same principles apply to the Arduino library, the arguments are just a little different here. Default if unspecified is 1 (no vertical tiling).
- Also not used here, an optional 12th argument is a pointer to a hardware-specific timer structure…this is _super exceedingly esoteric_ and not really used for now, but in principle would allow the library to work with other timer peripherals than the default.

# Begin Protomatter Driver

Now, with the matrix object created, inside&nbsp;`setup()`&nbsp;we call its `begin()` function. It’s pretty important to look at the value returned, which is a `ProtomatterStatus` type:

```cpp
ProtomatterStatus status = matrix.begin();
```

Possible return status values include:

- `PROTOMATTER_OK` — everything is good and the program can proceed (otherwise it should _stop…_the example code is not a good neighbor in this regard).
- `PROTOMATTER_ERR_PINS` — the RGB data and clock pins are not all on the same PORT. Can’t continue, the library _requires_ these pins in this layout.
- `PROTOMATTER_ERR_MALLOC` — couldn’t allocate enough memory for display. Can’t continue. This is usually an error that happens in the `begin()` function, but in extreme cases even the constructor could hit an allocation problem, but you won’t get this response until calling `begin()`.
- `PROTOMATTER_ERR_ARG` — some other bad input to function, distinct from PROTOMATTER\_ERR\_PINS. _Exceedingly_ rare, might only happen if constructor failed.

# Draw Shapes & Text Using Adafruit GFX

Then we draw some stuff on the display. **Any graphics primitive supported by the [Adafruit\_GFX library](https://learn.adafruit.com/adafruit-gfx-graphics-library)&nbsp;is available here.**

## **_Adafruit\_GFX_ is the same library that drives many of our LCD and OLED displays…if you’ve done other graphics projects, you might already be familiar! And if not, [we have a separate guide explaining all of the available drawing functions](https://learn.adafruit.com/adafruit-gfx-graphics-library/overview).&nbsp;Most folks can get a quick start by looking at the “simple” and “doublebuffer\_scrolltext” examples and tweaking these for their needs.**

Any color argument passed to a drawing function here is a 16-bit value, with the highest 5 bits representing red brightness (0 to 31), middle 6 bits for green (0 to 63), and least 5 bits for blue (0 to 31). It’s just how Adafruit\_GFX works and is a carryover from early PC graphics and most small LCD/OLED displays.

The effect of bit depth on image quality.&nbsp;Color values are always specified as full 16-bit “565” values, but will quantize to coarser representations at lower bit depths.

Sometimes you might want to avoid 6-bit depth even if RAM permits it. Only green handles the full 6 bits, while red and blue are quantized to 5 bits. This can result in some colors or gradients having slight green or magenta tints to them. 5-bit depth is slightly blockier but colors are more predictable.

![led_matrices_bit-depths.png](https://cdn-learn.adafruit.com/assets/assets/000/091/116/medium640/led_matrices_bit-depths.png?1589342795)

```cpp
matrix.drawCircle(12, 10, 9, matrix.color565(255, 0, 0));               // Red
matrix.drawRect(14, 6, 17, 17, matrix.color565(0, 255, 0));             // Green
...etc...
matrix.show(); // Copy data to matrix buffers
```

Notice though the call to `matrix.show()`&nbsp;at the end. Drawing operations have no immediate effect on the LED matrix, and instead are working on a buffer in RAM behind the scenes. Calling `show()`&nbsp;is **required** — it “pushes” the display data from that buffer to the matrix. You can call it after each drawing function, or group up a bunch of drawing commands with a single `show()` afterward to all appear at once. If you’ve worked with NeoPixel programming, it’s a similar phenomenon.

Since this program isn’t animating anything, it’s finished at that point and `loop()` _could_ be empty.

# Check Refresh Rate

For the sake of curious information though, the example shows the matrix refresh rate using&nbsp;`getFrameCount()`.&nbsp;This returns the _number of frames_ since the _last call to the same function,_ not the refresh rate…but if spaced about one second apart (`delay(1000)`), you get a fair approximation of refresh rate:

```cpp
Serial.println(matrix.getFrameCount());
delay(1000);
```

The matrix refresh rate is influenced by so many factors…processor speed, matrix chain length, bit depth…that it’s difficult to accurately predict ahead of time, so this is a way to see what you get when changing different values in the constructor.

This is a subjective thing, but in broad terms 200 Hz or better should provide a solid image…any less and it starts to become flickery, so you might want a lower bit depth in that case.&nbsp;Conversely, refreshing too fast would waste CPU cycles that you probably want for other tasks like animation. The library does its best to throttle back and not refresh faster than practically needed.

# Adafruit MatrixPortal M4

## Arduino Sand Demo

We have a Sand/Pixel Dust demo available for the MatrixPortal that runs in Arduino. Below is the code to run it. The demo is also available as an example in the **Arduino Protomatter** library.

https://github.com/adafruit/Adafruit_Protomatter/blob/master/examples/pixeldust/pixeldust.ino

This sketch was written for a **64x32** pixel matrix but is **easily modified** for a **64x64** matrix!

Look for this line in the code:

```cpp
#define HEIGHT  32 // Matrix height (pixels) - SET TO 64 FOR 64x64 MATRIX!
```

and change it to:

```cpp
#define HEIGHT  64 // Matrix height (pixels) - SET TO 64 FOR 64x64 MATRIX!
```

Now upload the sketch to your Qualia S3and make sure a round display is connected. You may need to press the Reset button to reset the microcontroller. You should see a series of colored rectangles along the bottom. Go ahead and start moving the matrix around!

![](https://cdn-learn.adafruit.com/assets/assets/000/095/081/medium800thumb/led_matrices_pixel_dust_demo.jpg?1601055861)

If you have a 3D Printer, be sure to check out the [Matrix Portal Sand Handles](https://learn.adafruit.com/matrix-portal-sand) guide.

# Adafruit MatrixPortal M4

## Protomatter Library

# Adafruit MatrixPortal M4

## Using the Accelerometer

![](https://cdn-learn.adafruit.com/assets/assets/000/096/628/medium800/led_matrices_matrixportal_pinout_accelerometer.png?1604163358)

On the back of the MatrixPortal is a triple-axis accelerometer that you can use to detect motion. (That's how our cool digital sand demo works!)

You can use this sensor in both CircuitPython and Arduino. After the library support is installed, you can then use the example code provided to get X, Y and Z acceleration values.

[For more details on the LIS3DH sensor, we have a full guide you should read once you get the basics working below](https://learn.adafruit.com/adafruit-lis3dh-triple-axis-accelerometer-breakout/overview)

# Arduino Usage

In Arduino, [make sure to install our LIS3DH library, our guide for the individual sensor covers all that here](https://learn.adafruit.com/adafruit-lis3dh-triple-axis-accelerometer-breakout/arduino#download-adafruit-lis3dh-library-1729233-8)

You can then load up this example

**However, before you upload it - change this line:**

` if (! lis.begin(0x18)) { // change this to 0x19 for alternative i2c address`

**to:**

` if (! lis.begin(0x19)) { // change this to 0x19 for alternative i2c address`

This will change the library to use the alternate address 0x19 of the accelerometer instead of the default 0x18!

https://github.com/adafruit/Adafruit_LIS3DH/blob/master/examples/acceldemo/acceldemo.ino

# CircuitPython Usage

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 **examples/** 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](https://adafruit.github.io/Adafruit_CircuitPython_Bundle/lis3dh_lis3dh_simpletest.py.png )

https://github.com/adafruit/Adafruit_CircuitPython_LIS3DH/blob/main/examples/lis3dh_simpletest.py

Before you save, however, you must tell the example where to find the sensor!

**Remove these lines:**

```python
# Hardware I2C setup. Use the CircuitPlayground built-in accelerometer if available;
# otherwise check I2C pins.
if hasattr(board, "ACCELEROMETER_SCL"):
    i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
    lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
else:
    i2c = board.I2C()  # uses board.SCL and board.SDA
    # i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
    lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c)
```

And 'uncomment' these lines:

```python
# PyGamer or MatrixPortal I2C Setup:
# i2c = board.I2C()  # uses board.SCL and board.SDA
# lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
```

So they look like this:

```python
# PyGamer or MatrixPortal I2C Setup:
i2c = board.I2C()  # uses board.SCL and board.SDA
lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
```

Now you can save, and check the REPL for acceleration data!

# Adafruit MatrixPortal M4

## Updating ESP32 Firmware

There may come a time when you want to update the firmware on the ESP32 itself. This isn't something we expect you'll do often if at all, but its good to know how if you need to.

[We have a guide here which details the process of updating the ESP32 firmware on Airlift All-in-One boards (including the PyPortal, MatrixPortal, and Metro M4 AirLift) here...](https://learn.adafruit.com/upgrading-esp32-firmware/upgrade-all-in-one-esp32-airlift-firmware)

# Adafruit MatrixPortal M4

## USB Power

If powering a MatrixPortal and associated LED matrix solely through the USB port, you might encounter a situation where the image appears stable when only a few pixels are lit, but brighter images with more pixels lit may exhibit “ghosting” or “sparkling” artifacts.

This is **not a software bug**. Please do not report it as a software bug.

This is a **USB power issue**. It does not affect everyone because there are _so many_ different USB power sources and permutations. What follows is an explanation and some workarounds.

## The Source of Gremlins
Not all USB ports are created equal. The ports on many computers are designed to provide 5 Volts at a maximum of 1 Ampere (1A)…or sometimes as little as 500 mA (0.5A). Likewise with USB wall chargers: small ones might deliver 1A or less, and even beefier models seldom exceed 2–2.5A.

LED matrices can be power hungry. And the more pixels in use, the hungrier they are. When a matrix demands more power than is available through the USB port, this can result in a momentary _brown-out_ condition, and the sort of visual glitches described above. This can be exacerbated by cheap, thin USB cables that have a lot of resistance.

Complicating issues, the _voltage and current from a USB port are not rock steady._ This is especially true of USB battery banks. The buck/boost converter circuit in these devices creates a sort of “buzz” in the output; on _average_ it might be 5V 2A, but the _instantaneous_ voltage and current will oscillate around this. This is no problem for a typical steady use like charging a phone, but LED matrices are weird…it’s not just that they’re hungry, but like the supply voltage, the LED current draw _also_ oscillates they’re actually flashed on and off hundreds of times a second to produce an image.

## Some Solutions to Try

If you encounter the aforementioned phenomenon, here are some things to try, starting from the very simple and working our way up…

- Try **swapping the USB cable** if the one you have seems thin. That free cable included for charging a mouse or Bluetooth speaker might be unsuitable for the amount of current we need. Look for something beefy, like a tablet or laptop charging cable. Those luxury braided cables are also sometimes a sign of “substance.”
- If powering from a **computer’s USB port** : try using a sizable (2A or better) **USB wall charger** instead.
- If powering from a **USB wall charger** or **USB battery bank** : Try **swapping out** for any others you might have on hand. More current (higher amperage) is always nice, but that’s not the whole story. As explained above, the output filtering (or lack of) can affect the steadiness of the output voltage and current.

Those are the easy “switch something out” fixes. If none of those address the issue, now things get progressively more complex…

- Try **powering the MatrixPortal and LED matrix separately** : USB for the MatrixPortal, and a 5V DC “wall wart” supply (2A or preferably more) for the matrix, using one of these screw terminal power adapters (i.e. don’t use the screw terminals on the MatrixPortal, use this instead):

### Female DC Power adapter - 2.1mm jack to screw terminal block

[Female DC Power adapter - 2.1mm jack to screw terminal block](https://www.adafruit.com/product/368)
If you need to connect a DC power wall wart to a board that doesn't have a DC jack - this adapter will come in very handy! There is a 2.1mm DC jack on one end, and a screw terminal block on the other. The terminals are labeled with positive/negative assuming a positive-tip configuration...

In Stock
[Buy Now](https://www.adafruit.com/product/368)
[Related Guides to the Product](https://learn.adafruit.com/products/368/guides)
![Angle shot Female DC Power adapter - 2.1mm jack to screw terminal block](https://cdn-shop.adafruit.com/640x480/368-03.jpg)

- If the project _must_ be powered from a **USB battery bank** and you’ve already tested some others: try powering the LED matrix and the MatrixPortal **separately**. This might involve two power banks, or one with multiple ports might suffice (most enforce per-port current limits), you’ll need to experiment. Cables exist to convert USB type A or C to a DC plug that’s compatible with the screw terminal adapter above — one would power the LED matrix through this, and the MatrixPortal through a normal USB cable. Just make sure the cable provides 5V output; some are “booster” cables to higher voltages that could _destroy_ the matrix.

- If nothing else seems to work, the last line of defense is **better filtering** on the power supply output. This involves adding one or more **capacitors** across the + and – terminals until the image stabilizes. Unfortunately there is no one-size-fits-all solution here…it requires **experimentation** with an assortment of caps on hand. One might start with a 1000 µF cap, and work up or down from there. If something seems promising but imperfect, two or more with different values might be needed in parallel (e.g. 100 µF + 1000 µF).

This photo shows NeoPixels, but the principle is _exactly_ the same: capacitance helps smooth out fluctuations in the power supply. Look for something at least 10V rated (higher is OK) and values from 50 µF to 2000 µF. Folks who’ve been doing electronics for a while usually end up with a little parts drawer of random caps, so maybe you (or someone you know, or a local maker space) already have something suitable.

![led_matrices_leds_cap.jpg](https://cdn-learn.adafruit.com/assets/assets/000/125/104/medium640/led_matrices_leds_cap.jpg?1697061543)

# Adafruit MatrixPortal M4

## Downloads

## Files

- [ATSAMD51J19 datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/SAM_D5xE5x_Family_Data_Sheet_DS60001507F.pdf)
- [EagleCAD PCB files on GitHub](https://github.com/adafruit/Adafruit-MatrixPortal-M4-PCB)
- [Fritzing object in Adafruit Fritzing Library](https://github.com/adafruit/Fritzing-Library/blob/master/parts/Adafruit%20PyPortal%20-%20CircuitPython%20Powered%20Internet%20Display.fzpz)
- [PDF for MatrixPortal M4 Board Diagram on GitHub](https://github.com/adafruit/Adafruit-MatrixPortal-M4-PCB/blob/main/Adafruit%20MatrixPortal%20M4%20Pinout.pdf)

[SVG for MatrixPortal M4 Board Diagram](https://cdn-learn.adafruit.com/assets/assets/000/111/882/original/Adafruit_MatrixPortal_M4_Pinout.svg?1653078637)
[Simpletest UF2 for MatrixPortal M4 + 64x32 Matrix](https://cdn-learn.adafruit.com/assets/assets/000/123/404/original/matrixportal_m4_simpletest.UF2?1691705208)
[Simpletest UF2 for MatrixPortal M4 + 64x64 Matrix](https://cdn-learn.adafruit.com/assets/assets/000/123/405/original/matrixportal_m4_simpletest_64x64.UF2?1691705232)
## Schematic
![](https://cdn-learn.adafruit.com/assets/assets/000/095/095/medium800/led_matrices_MatrixPortal_M4_Schematic.png?1601064911)

## Fab Print
![](https://cdn-learn.adafruit.com/assets/assets/000/095/084/medium800/led_matrices_MatrixPortal_M4_Fab_Print.png?1601061698)


## Primary Products

### Adafruit Matrix Portal - CircuitPython Powered Internet Display

[Adafruit Matrix Portal - CircuitPython Powered Internet Display](https://www.adafruit.com/product/4745)
Folks love our [wide selection of RGB matrices](https://www.adafruit.com/category/327) and accessories, for making custom colorful LED displays... and our RGB Matrix Shields and FeatherWings can be quickly soldered together to make the wiring much easier. But what if we made it...

In Stock
[Buy Now](https://www.adafruit.com/product/4745)
[Related Guides to the Product](https://learn.adafruit.com/products/4745/guides)

## Featured Products

### 64x32 RGB LED Matrix - 6mm pitch

[64x32 RGB LED Matrix - 6mm pitch](https://www.adafruit.com/product/2276)
Bring a little bit of Times Square into your home with this sweet 64x32 square RGB LED matrix panel. These panels are normally used to make video walls, here in New York we see them on the sides of busses and bus stops, to display animations or short video clips. We thought they looked really...

In Stock
[Buy Now](https://www.adafruit.com/product/2276)
[Related Guides to the Product](https://learn.adafruit.com/products/2276/guides)
### 64x32 RGB LED Matrix - 5mm pitch

[64x32 RGB LED Matrix - 5mm pitch](https://www.adafruit.com/product/2277)
Bring a little bit of Times Square into your home with this sweet 64x32 square RGB LED matrix panel. These panels are normally used to make video walls, here in New York we see them on the sides of busses and bus stops, to display animations or short video clips. We thought they looked really...

In Stock
[Buy Now](https://www.adafruit.com/product/2277)
[Related Guides to the Product](https://learn.adafruit.com/products/2277/guides)
### 64x32 Flexible RGB LED Matrix - 4mm Pitch

[64x32 Flexible RGB LED Matrix - 4mm Pitch](https://www.adafruit.com/product/3826)
If you've played with multiplexed RGB matrices, you may have wondered "hey, could we possibly manufacture these on a thin enough PCB, so it's flexible?" and the answer is&nbsp; **Yes!** &nbsp;[T](http://www.adafruit.com/?q=64x32%20RGB)<a...></a...>

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/3826)
[Related Guides to the Product](https://learn.adafruit.com/products/3826/guides)
### 64x32 Flexible RGB LED Matrix - 5mm Pitch

[64x32 Flexible RGB LED Matrix - 5mm Pitch](https://www.adafruit.com/product/3803)
If you've played with multiplexed RGB matrices, you may have wondered "hey, could we possibly manufacture these on a thin enough PCB so it's flexible?" and the answer is **Yes!** [T](http://www.adafruit.com/?q=64x32%20RGB)<a...></a...>

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/3803)
[Related Guides to the Product](https://learn.adafruit.com/products/3803/guides)
### 64x32 RGB LED Matrix - 3mm pitch

[64x32 RGB LED Matrix - 3mm pitch](https://www.adafruit.com/product/2279)
Bring a little bit of Times Square into your home with this sweet 64 x 32 square RGB LED matrix panel. These panels are normally used to make video walls, here in New York we see them on the sides of busses and bus stops, to display animations or short video clips. We thought they looked...

In Stock
[Buy Now](https://www.adafruit.com/product/2279)
[Related Guides to the Product](https://learn.adafruit.com/products/2279/guides)
### 64x32 RGB LED Matrix - 4mm pitch

[64x32 RGB LED Matrix - 4mm pitch](https://www.adafruit.com/product/2278)
Bring a little bit of Times Square into your home with this sweet 64 x 32 square RGB LED matrix panel. These panels are normally used to make video walls, here in New York we see them on the sides of busses and bus stops, to display animations or short video clips. We thought they looked...

In Stock
[Buy Now](https://www.adafruit.com/product/2278)
[Related Guides to the Product](https://learn.adafruit.com/products/2278/guides)
### Black LED Diffusion Acrylic Panel 12" x 12" - 0.1" / 2.6mm thick

[Black LED Diffusion Acrylic Panel 12" x 12" - 0.1" / 2.6mm thick](https://www.adafruit.com/product/4594)
A nice whoppin' slab of some lovely black acrylic to add some extra diffusion to your LED Matrix project. This material is 2.6mm (0.1") thick and is made of special cast acrylic that makes it perfect for glowy projects, especially matricies or NeoPixels.

Unlike smoke or...

In Stock
[Buy Now](https://www.adafruit.com/product/4594)
[Related Guides to the Product](https://learn.adafruit.com/products/4594/guides)
### USB C to USB C Cable - USB 3.1 Gen 4 with E-Mark - 1 meter long

[USB C to USB C Cable - USB 3.1 Gen 4 with E-Mark - 1 meter long](https://www.adafruit.com/product/4199)
As technology changes and adapts, so does Adafruit! Rather than the regular USB A, this cable has&nbsp; **USB C to USB C** &nbsp;plugs!

USB C is the latest industry-standard connector for transmitting data&nbsp;_and_&nbsp;power. Like Lightning and MagSafe cables, USB C...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4199)
[Related Guides to the Product](https://learn.adafruit.com/products/4199/guides)

## Related Guides

- [RGB Matrix Portal Room CO2 Monitor](https://learn.adafruit.com/matrix-portal-room-co2-monitor.md)
- [Matrix Portal RGB Display Handbag](https://learn.adafruit.com/matrix-portal-rgb-display-handbag.md)
- [Stream Deck controlled RGB Message Panel using Adafruit IO](https://learn.adafruit.com/stream-deck-controlled-rgb-message-panel-using-adafruit-io.md)
- [RGB Matrix Dreidel Game](https://learn.adafruit.com/rgb-matrix-dreidel-game.md)
- [Raspberry Pi LED Matrix Display](https://learn.adafruit.com/raspberry-pi-led-matrix-display.md)
- [Adafruit RGB Matrix + Real Time Clock HAT for Raspberry Pi](https://learn.adafruit.com/adafruit-rgb-matrix-plus-real-time-clock-hat-for-raspberry-pi.md)
- [Custom Scrolling Quote Board Matrix Display](https://learn.adafruit.com/aio-quote-board-matrix-display.md)
- [Purple Air AQI Display](https://learn.adafruit.com/purple-air-aqi-display.md)
- [Image Correction for RGB LED Matrices](https://learn.adafruit.com/image-correction-for-rgb-led-matrices.md)
- [RGB LED Matrix Basics](https://learn.adafruit.com/32x16-32x32-rgb-led-matrix.md)
- [itsaSNAP Daily Weather Forecast Board](https://learn.adafruit.com/itsasnap-daily-weather-forecast-board.md)
- [LED Protest Sign](https://learn.adafruit.com/led-protest-sign.md)
- [Moon Phase Clock for Adafruit Matrix Portal](https://learn.adafruit.com/moon-phase-clock-for-adafruit-matrixportal.md)
- [Network Connected RGB Matrix Clock](https://learn.adafruit.com/network-connected-metro-rgb-matrix-clock.md)
- [RGB LED Matrices with CircuitPython](https://learn.adafruit.com/rgb-led-matrices-matrix-panels-with-circuitpython.md)
