Overview

The Gemma M0 is a super small microcontroller board, with just enough to build many simple projects. It may look small and cute: round, about the size of a quarter, with friendly alligator-clip sew pads. But do not be fooled! The Gemma M0 is incredibly powerful! We've taken the same form factor we used for the original ATtiny85-based Gemma and gave it a power up. The Gemma M0 has swapped out the lightweight ATtiny85 for a ATSAMD21E18 powerhouse.

It will super-charge your wearables! It's just as small, and it's easier to use, so you can do more.

The most exciting part of the Gemma M0 is that while you can use it with the Arduino IDE, we are shipping it with CircuitPython on board. When you plug it in, it will show up as a very small disk drive with main.py on it. Edit main.py with your favorite text editor to build your project using Python, the most popular programming language. No installs, IDE or compiler needed, so you can use it on any computer, even ChromeBooks or computers you can't install software on. When you're done, unplug the Gemma M0 and your code will go with you.

Here are some of the updates you can look forward to when using Gemma M0:

  • Same size, form-factor, and pinout as classic Gemma
  • Updating ATtiny85 8-bit AVR for ATSAMD21E18 32-bit Cortex M0+
  • 256KB Flash - 8x as much as 8 KB on ATtiny85
  • 32 KB RAM - 64x as much as 512 bytes on ATtiny85
  • 48 MHz 32 bit processor - 6x as fast as ATtiny85 (not even taking into account 32-bit speedups)
  • Native USB supported by every OS - can be used in Arduino or CircuitPython as USB serial console, Keyboard/Mouse HID, even a little disk drive for storing Python scripts. (ATtiny85 does not have native USB)
  • Can be used with Arduino IDE or CircuitPython
  • Built in RGB DotStar LED
  • Three big-hole sew-pads can be used for conductive thread or alligator-clips for fast prototyping
    • Each I/O pad can be used for 12-bit analog input, or digital input/output with internally connected pullups or pulldowns
    • We gave the M0 pads the exact same names as the original Gemma so all your existing Arduino code will work exactly the same as-is without changes
    • True analog output on one I/O pad - can be used to play 10-bit quality audio clips
    • Two high speed PWM outputs on other two I/O Pads - for servos, LEDs, etc
    • All three pads can also be used as hardware capacitive touch sensors with no additional components required
    • Can drive NeoPixels or DotStars on any pins, with enough memory to drive 8000+ pixels. DMA-NeoPixel support on one pin so you can drive pixels without having to spend any processor time on it.
    • Native hardware I2C or Serial available on two pads so you can connect to any I2C or Serial device with true hardware support (no annoying bit-banging)
  • Same Reset switch for starting your project code over
  • On/Off switch built in
  • JST battery connector for plugging in AAA's or LiPoly battery (no built-in LiPoly charging so it is safe to use with NiMH/Alkalines)

Each order comes with one fully assembled and tested Gemma M0 with CircuitPython & example code programmed in.

So what are you waiting for? Pick up a Gemma M0 today and be amazed at how easy and fast it is to get started with Gemma and CircuitPython!

Guided Tour

Let me take you on a tour of your Gemma M0! Each Gemma M0 is assembled here at Adafruit and comes chock-full of good design to make it a joy to use.

  • Micro B USB connector - We went with the tried and true micro-B USB connector for power and/or USB communication (bootloader, serial, HID, etc). Use with any computer with a standard data/sync cable.
  • RGB DotStar LED - Instead of an always-on green LED we provide a full RGB LED. You can set it to any color in the rainbow. It will also help you know when the bootloader is running (it will turn green) or if it failed to initialize USB when connected to a computer (it will turn red). By default after you boot up the Gemma M0 it will turn a lovely violet color.
  • Red #13 LED - this LED does double duty. Its connected with a series resistor to the digital #13 GPIO pin. It pulses nicely when the Gemma is in bootloader mode, and its also handy for when you want an indicator LED.
  • JST Battery Input - take your Gemma anywhere and power it from an external battery. This pin can take up 6V DC input, and has reverse-polarity, over-current and thermal protections. The circuitry inside will use either the battery or USB power, safely switching from one to the other. If both are connected, it will use whichever has the higher voltage. Works great with a Lithium Polymer battery or our 3xAAA battery packs with a JST connector on the end. There is no built in battery charging (so that you can use Alkaline or Lithium batteries safely)
  • Vout (Voltage Output) - This pin will give you either the battery power or USB power, whichever has a higher voltage. Its great when you want to power something like NeoPixels, that might use more than the 500mA available from the onboard regulator
  • 3V Regulator - The on-board voltage regulator can supply up to 500mA at a steady 3.3V from up to 6VDC
  • Sewing and Alligator clip friendly pads - You can easily sew to these pads, and they're gold plated so they wont corrode (oxidize). You can also use alligator clips or solder directly to them.
  • 3 General Purpose I/O (GPIO) Pads! - 3 GPIO pins, at 3V logic, check the next section for a detailed pinout guide
  • Reset Button - an onboard reset button will launch the bootloader when pressed and the Gemma is plugged into a computer. If it is not connected to a computer, it's smart enough to go straight to the program.
  • On/Off switch - Lets you turn on/off your project, it will control both the Gemma and the Vout pad. This switch can switch up to about 500mA of current, so if you are driving a huge number of servos or NeoPixels, connect power to those power-greedy parts externally.

Pinouts

JST Battery Input

There is no battery INPUT pin on the Gemma. You can connect a battery via the JST jack. We have found that Lipoly batteries, coin-cells, and AAA's work great. You can also make your own battery input pack using a plain JST cable. And use a JST extension cable if necessary.

You can plug anything from around 4 VDC up to 6 VDC. That means any single-cell LiPoly, or 3-4 AAA or AA batteries. This input is polarity protected. Gemma and DotStar LED light up, you're good to go. You can turn off the battery with the on/off switch, which will completely disconnect power on the Gemma M0.

Power Pads

Half of the pads on the Gemma M0 are related to power in and out: 3Vo , Vout and GND

  • Vout - This is a voltage OUTPUT pin, it will be connected to either the USB power or the battery input, whichever has the higher voltage. This output does not connect to the regulator so you can draw as much current as your USB port / Battery can provide (in general, thats about 500mA)
  • 3Vo - This is the 3.3V OUTPUT pad from the voltage regulator. It can provide up to 500mA at a steady 3.3V. Good for sensors or small LEDs or other 3V devices.
  • GND is the common ground pin, used for logic and power. It is connected to the USB ground and the power regulator, etc. This is the pin you'll want to use for any and all ground connections

Input/Output Pads

Next we will cover the 3 GPIO (General Purpose Input Ouput) pins! For reference you may want to also check out the datasheet-reference in the downloads section for the core ATSAMD21E18 pin. We picked pins that have a lot of capabilities.

Common to all pads

All the GPIO pads can be used as digital inputs, digital outputs, for LEDs, buttons and switches. In additon, all can be used as analog inputs (12-bit ADC) or hardware capacitive touch. All pads can also be used as hardware interrupts inputs.

Each pad can provide up to ~20mA of current. Don't connect a motor or other high-power component directly to the pins! Instead, use a transistor to power the DC motor on/off

On a Gemma M0, the GPIO are 3.3V output level, and should not be used with 5V inputs. In general, most 5V devices are OK with 3.3V output though.

The three pads are completely 'free' pins, they are not used by the USB connection, LEDs, DotStar, etc so you never have to worry about the USB interface interfering with them when programming

Unique pad capabilities

  • Pad #0 / A2  - this is connected to PA04 on the ATSAMD21. This pin can be used as a digital I/O with selectable pullup or pulldown, capacitive touch, analog input (use 'A2'),  PWM output, and is also used for I2C data (SDA), and hardware Serial RX.
  • Pad #1 / A0  - this is connected to PA02 on the ATSAMD21. This pin can be used as a digital I/O with selectable pullup or pulldown, capacitive touch, analog input (use 'A0'),  and true analog (10-bit DAC) output. It cannot be used as PWM output.
  • Pad #2 / A1  - this is connected to PA05 on the ATSAMD21. This pin can be used as a digital I/O with selectable pullup or pulldown, capacitive touch, analog input (use 'A1'),  PWM output, and is also used for I2C clock (SCL), and hardware Serial TX.

Secret SWD and Reset Pads

On the bottom of the Gemma M0 you will see three small pads. These are used for our programming/test but you can use them too.

Starting from the pad closest to the edge there is:

  • SWDIO
  • SWCLK
  • Reset

On the off chance you want to reprogram your Gemma M0 or debug it using a Cortex M0 debug/programmer, you will need to solder/connect to these pads. We use them for testing and you will likely never need it but they are there if you do!

Windows Driver Installation

Mac and Linux do not require drivers, only Windows folks need to do this step

Before you plug in your board, you'll need to possibly install a driver!

Click below to download our Driver Installer.

Download and run the installer.

Run the installer! Since we bundle the SiLabs and FTDI drivers as well, you'll need to click through the license

Select which drivers you want to install, we suggest selecting all of them so you don't have to do this again!

On Windows 7, by default, we install a single driver for most of Adafruit's boards, including the Feather 32u4, the Feather M0, Feather M0, Express, Circuit Playground, Circuit Playground Express, Gemma M0, Trinket M0, Metro M0 Express. On Windows 10 that driver is not necessary (it's built in to Windows) and it will not be listed.

The Trinket / Pro Trinket / Gemma / USBtinyISP drivers are also installed by default.

You can also, optionally, install the Arduino Gemma (different than the Adafruit Gemma!), Huzzah and Metro 328 drivers.

Click Install to do the installin'.

Note that on Windows 10, support for many boards is built in. If you end up not checking any boxes, you don't need to run the installer at all!

Manual Driver Installation

If windows needs the driver files (inf/cat) for some reason you can get all the drivers in a zip by clicking below:

And point windows to the Drivers folder when it asks for the driver location

CircuitPython

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

Your Gemma M0 already comes with CircuitPython but maybe there's a new version, or you overwrote your Gemma M0 with Arduino code! In that case, see the below for how to reinstall or update CircuitPython. Otherwise you can skip this and go straight to the next page

Reinstalling and Updating CircuitPython

The latest builds of CircuitPython are available from the GitHub release page. Binaries for different boards are listed under the Downloads section. Pick the one that matches your board such as adafruit-circuitpython-gemma_m0-1.0.0.bin for the Gemma M0.

Files ending in .uf2 can be flashed onto a virtual drive when in bootloader mode. Files that end with .bin can be flashed with esptool.py or bossac.

You will see a list of all available flavors of CircuitPython. Since we support a lot of different hardware, we have a long list of available downloads!

See below for which file to download!

Flashing

Flashing is the process of updating the CircuitPython core. It isn't needed for updating your own code. There are two available methods: UF2 and bossac

Flashing is only available on newer boards including the Gemma M0. Flashing via bossac is possible with both the UF2 bootloader and the original "Arduino" one. We recommend using UF2 if you can, its the easiest! If UF2 fails, or is not available, try bossac.

Entering Bootloader Mode

Regardless of what method you use, you must first get the board into the bootloader mode. This is done by double clicking the reset button. The board is in bootloader mode when the red led fades in and out. Boards with the status neopixel will also show USB status while the red led fades. Green means USB worked while red means the board couldn't talk to the computer. The first step to troubleshooting a red neopixel is trying a different USB cable to make sure its not a charge-only cable.

Flashing UF2

The Gemma M0 comes with a new bootloader called UF2 (Usb Flasher version 2) that makes flashing CircuitPython even easier than before. This beta bootloader allows you to drag so-called ".uf2" type files onto the BOOT drive. For more information, check out our UF2 bootloader page.

Start by ejecting or "safely remove" the CIRCUITPY drive if its present, then double-clicking the reset button while it is plugged into your computer. You should see a new disk drive 'pop up' called GEMMABOOT or similar, and the DotStar on your board glow green.

The drive will contain a few files. If you want to make a 'backup' of the current firmware on the device, drag-off and save the CURRENT.UF2 file. Other that that you can ignore the index.htm and info_uf2.txt files. They cannot be deleted and are only for informational purposes.

Next up, find the Gemma M0 UF2 file in the github downloads list:

Click to download and save the file onto your Desktop or somewhere else you can find it

Then drag the uf2 file into the GEMMABOOT drive.

Once the full file has been received, the board will automatically restart into CircuitPython. Your computer may warn about ejecting the drive early, if it does, simply ignore it because the board made sure the file was received ok.

Flashing with BOSSAC

This method is only recommended if you can't use UF2 for some reason!

To flash with bossac (BOSSA's command line tool) first download the latest version from here. The mingw32 version is for Windows, apple-darwin for Mac OSX and various linux options for Linux. Once downloaded, extract the files from the zip and open the command line to the directory with bossac.

bossac -e -w -v -R ~/Downloads/adafruit-circuitpython-gemma_m0-1.0.0.bin

This will erase the chip, write the given file, verify the write and Reset the board. After reset, CircuitPython should be running. Newer boards with the UF2 bootloader may cause a warning of an early eject of a USB drive but just ignore it. Nothing important was being written to the drive.

After flashing

After a successful flash by bossac or UF2 you should see a CIRCUITPY drive appear.

Welcome to the Community!

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

Everyone is welcome! CircuitPython is Open Source. This means it's available for anyone to use, edit, copy and improve upon. This also means CircuitPython becomes better because of you being a part of it. It doesn't matter whether this is your first microcontroller board or you're a computer engineer, you have something important to offer the Adafruit CircuitPython community. We're going to highlight some of the many ways you can be a part of it!

Adafruit Discord

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

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

The CircuitPython channel is where to go with your CircuitPython questions. #circuitpython is there for new users and developers alike so feel free to ask a question or post a comment! Everyone of any experience level is welcome to join in on the conversation. We'd love to hear what you have to say!

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

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

Visit https://adafru.it/discord to sign up for Discord. We're looking forward to meeting you!

Adafruit Forums

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

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

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

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

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

Adafruit Github

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

If you're new to GitHub or programming in general, there are great opportunities for you. Head over to adafruit/circuitpython on GitHub, click on "Issues", and you'll find a list that includes issues labeled "good first issue". These are things we've identified as something that someone with any level of experience can help with. These issues include options like updating documentation, providing feedback, and fixing simple bugs.

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

When working with CircuitPython, you may find problems. If you find a bug, that's great! We love bugs! Posting a detailed issue to GitHub is an invaluable way to contribute to improving CircuitPython. Be sure to include the steps to replicate the issue as well as any other information you think is relevant. The more detail, the better!

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

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

ReadTheDocs

ReadTheDocs is a an excellent resource for a more in depth look at CircuitPython. This is where you'll find things like API documentation and details about core modules. There is also a Design Guide that includes contribution guidelines for CircuitPython.

RTD gives you access to a low level look at CircuitPython. There are details about each of the core modules. Each module lists the available libraries. Each module library page lists the available parameters and an explanation for each. In many cases, you'll find quick code examples to help you understand how the modules and parameters work, however it won't have detailed explanations like the Learn Guides. If you want help understanding what's going on behind the scenes in any CircuitPython code you're writing, ReadTheDocs is there to help!

CircuitPython Blinky

Let's get blinky going with CircuitPython to explore the way we can write code and confirm everything is working as expected.

code.py

After plugging in a board with CircuitPython into your computer a CIRCUITPY drive will appear. At first, the drive may be empty but you can create and edit files on it just like you would on a USB drive. On here, you can save a code.py (code.txt and main.py also work) file to run every time the board resets. This is the CircuitPython equivalent of an Arduino sketch. However, all of the compiling is done on the board itself. All you need to do is edit the file.

So, fire up your favorite text editor, such as Notepad on Windows, TextEdit on Mac or download Atom (my favorite), and create a new file. In the file copy this:

import digitalio
import board
import time

led = digitalio.DigitalInOut(board.D13)
led.direction = digitalio.Direction.OUTPUT
while True:
    led.value = not led.value
    time.sleep(0.5)

Now, save the file to the drive as code.py (main.py or code.txt also works). After a brief time, the board's red LED should begin to flash every second.

Do not click the RESET button after saving your code file! It could cause the computer to not-finish writing your code to disk. Just wait a few seconds and it should automatically restart the python code for you!

Status LED (Gemma/Trinket/Metro/Feather)

If you have a Gemma, Trinket, Metro or Feather running CircuitPython, there's a single RGB LED on the board to help you know what's up. While code.py is running the status neopixel will be solid green. After it is finished, the neopixel will fade green on success or flash an error code on failure. Red flashes happen when data is written to the drive.

Circuit Playground Express does not have this status LED

Debugging

Did the status LED flash a bunch of colors at you? You may have an error in your code. Don't worry it happens to everyone. Python code is checked when you run it rather than before like Arduino does when it compiles. To see the CircuitPython error you'll need to connect to the serial output (like Arduino's serial monitor).

See this guide for detailed instructions.

If you are new to Python try googling the error first, if that doesn't find an answer feel free to drop by the support forum.

Libraries

Using libraries with CircuitPython is also super easy. Simply drag and drop libraries onto the CIRCUITPY drive or into a lib folder on the drive to keep it tidy.

Find CircuitPython libraries on GitHub using the topic and through our tutorials.

Make sure the libraries are for CircuitPython and not MicroPython. There are some differences that may cause it to not work as expected.

More info

Serial Console (REPL)

CircuitPython sends the output of the .py files it runs to the connected computer over USB serial. So, to view the output of your code from print statements and any errors that occur you'll need to connect to the serial console.

Also, because CircuitPython is a variant of Python, it too has a read-evaluate-print-loop or  'REPL' for short. The REPL lets you run individual commands and load up code interactively and is therefore great for testing a new idea. However, the code typed into the REPL isn't saved anywhere so make sure and save it elsewhere (like code.py for example.)

Windows

Serial Drivers (for Windows 7)

If you are using Windows 7 you will need to install drivers. Click below to download the driver package and install it! This is not necessary for Mac, Linux or Windows 10+.

Determine Your Serial Port

Next you must determine the name of the serial port for your board.  It's easiest to look at the serial ports with the board disconnected (on Windows check Device Manager under the Ports (COM/LPT) node

It will be named something like Adafruit Circuit Playground, Adafruit Gemma M0, Adafruit Trinket M0 or Adafruit Feather M0

Install Serial Port Terminal Software

On Windows you'll want to use a tool like PuTTY to connect to the serial port.  Download and run PuTTY, then configure it to use a serial connection to the board's COM port at 115200 baud similar to as shown below:

After clicking Open you should see a new window pop up with the current output from the running code. If no code is running, it may be blank so hit Ctrl - C to get to the REPL prompt.

Mac OSX and Linux

Connecting to the serial terminal on is more straightforward than on Windows. Neither OS requires additional drivers.

First open a terminal program. On Mac OSX, Terminal comes installed and iTerm2 can be downloaded. On Linux there are a variety available such as gnome-terminal (called Terminal) and Konsole on KDE.

Now before plugging in the board, type ls /dev/tty.* to view existing serial connections.

Next, plug in the board. There should be one new serial connection that is for your board. Typically on Mac OSX its something like /dev/tty.usbmodem* and on Linux its /dev/ttyACM*.

Now that we know the device name, the screen command can be used to connect to the serial port. Its installed on Mac OSX by default but Linux users may need to install it using their package manager. Run the following command to connect at 115200 baud:

screen /dev/tty.board_name 115200

Where /dev/tty.board_name is the name of the board's serial port.

When you're done using screen most versions of it allow you to exit by pressing Ctrl-a then k then y or pressing Ctrl-a then typing :quit and pressing enter.

Using the REPL

After you're connected to the serial REPL try pressing enter to confirm you see the >>> prompt.  You can also type help() and press enter on most boards to see basic usage information.

If you can't get a >>> prompt to appear try pressing Ctrl-c a couple times to interrupt any running program on the board.

You might get a Traceback and KeyboardInterrupt that lets you know the current Python program has stopped, and you'll get a prompt:

That's all there is to connecting to the board's serial REPL, you're ready to start typing in and running CircuitPython code!

About CircuitPython Libraries

Part of what makes CircuitPython so awesome is its ability to store code separately from the firmware itself. Storing code separately from the firmware makes it easier to update both the code you write and the libraries you depend. So, instead of compiling libraries in, you simply place them into your lib directory on the CIRCUITPY drive.

Your board may ship with a lib folder already, its in the base directory of the drive. If not, simply create the folder yourself.

CircuitPython libraries work in the same was as regular Python modules so the Python docs are a great reference for how it all should work. (In Python terms, we can place our library files in the lib directory because its part of the Python path by default.)

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

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

Installing the bundle

We're constantly updating and improving our libraries, so we don't (at this time) ship our CircuitPython boards with the full library bundle. Instead, you may find example code that depends on libraries - you can tell because they have an importline, often at the top of the code. Some of these libraries may be available from us at Adafruit, some may be written by community members!

Go to the latest Adafruit CircuitPython Bundle release by clicking this button:

Visiting the bundle release page will show us information on the latest release including a list of all the versions of the included drivers. Scrolling to the bottom of the page will reveal the downloads. There may be a few different versions, usually the current version and maybe a beta.

Download the version that matches your CircuitPython runtime For example, if you're running v2.2 download the v2 bundle. If you're running 3.0, download the v3 bundle. There's also a py bundle which contains the uncompressed python files, you probably don't want that!

After downloading the zip, extract its contents. This is usually done by double clicking on the zip. On Mac OSX as I'm using, it places the file in the same directory as the zip. I usually sort my Downloads by file data so the lib directory that was contained in the zip ends up next to the zip file.

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

Express Boards

If you are using a Feather M0 Express, Metro M0 Express or Circuit Playground Express (or any other "Express" board) your CircuitPython board comes with at least 2 MB of Flash storage. This is plenty of space for all of our library files so we recommend you just install them all! (If you have a Gemma M0 or Trinket M0 or other non-Express board, skip down to the next section)

On Express boards, the lib directory can be copied directly to the CIRCUITPY drive.

Just drag the entire lib folder into the CIRCUITPY drive, and 'replace' any old files if your operating system prompts you

You're done! You can go back to coding your project :)

Non-Express Boards

If you have a Gemma M0 or Trinket M0, your internal storage is from the chip itself. So, this board doesn't have enough space for all of the libraries. If you try to copy over the entire lib folder you'll overwhelm your storage.

Instead, we'll copy over just what we need as we need it.

Let's take a look at a real example. Say you have your Trinket wired up to a Si7021 sensor

And you want this sensor to print out the temperature & humidity. From looking at our Si7021 guide you decide to run this very simple example:

import adafruit_si7021
import busio
import board

i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_si7021.SI7021(i2c)
print("Temperature:", sensor.temperature)
print("Humidity:", sensor.relative_humidity)
Note: If you don't have an external SI7201 connected to your board, you'll get a different error ("ValueError: No I2C device at address: 40"), showing that the library is present but can't find the device. This example is just an illustration of how to add and import libaries!

After saving that as code.py on the drive we see the status NeoPixel flashes that an error has occurred. Opening up the serial console we see that an ImportError has occurred.

Looks like we need a adafruit_si7021 library. After downloading the latest Adafruit bundle, we look and see that in the lib folder there is an adafruit_si7021.mpy file. That matches the missing module! Python imports modules based on the filename so they will always match up. Lets drag it over.

Woohoo! Everything copied over just fine. Lets check the serial terminal to see how things are going.

Oops! Another ImportError! Libraries can depend on other libraries so copying one file over may not be enough.

Looking in the bundle, there is an adafruit_bus_device directory. In Python terms this is a package. It contains module files. Lets copy the folder over to make sure we get everything.

Lets check the serial connection again. Looks like it worked! We don't have any more ImportErrors and we can see the temperature (in Celsius) and the relative humidity.

Non-Express boards - Out of space?

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

Step 1) Delete something!

The simplest way of freeing up space is to delete files from the drive.

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

Perhaps there are libraries in the lib that you aren't using anymore or test code that isn't in use.

Step 2) Use tabs

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

Step 3) On Mac OSX? OSX loves to add extra files!

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

Prevent & Remove Mac OSX Hidden Files

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

ls -l /Volumes

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

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

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

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

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

Copy Files on Mac OSX Without Creating Hidden Files

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

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

cp -X foo.mpy /Volumes/CIRCUITPY

Or to copy a folder and all of its child files/folders use a command like:

cp -rX folder_to_copy /Volumes/CIRCUITPY

Other Mac OSX Tips

If you'd like to see the amount of space used on the drive and manually delete hidden files here's how to do so.  First list the amount of space used on the CIRCUITPY drive with the df command:

Lets remove the ._ files first.

Whoa! We have 13Ki more than before!

CircuitPython Built-Ins

CircuitPython comes 'with the kitchen sink' - a lot of the things you know and love about classic Python 3 (sometimes called CPython) already work. There are a few things that don't but we'll try to keep this list updated as we add more capabilities!

This is not an exhaustive list! It's just some of the many featuers you can use

Things that are Built In and Work

flow control

All the usual if, elif, else, for, while... work just as expected

math

import math will give you a range of handy mathematical functions

>>> dir(math)
['__name__', 'e', 'pi', 'sqrt', 'pow', 'exp', 'log', 'cos', 'sin', 'tan', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'copysign', 'fabs', 'floor', 'fmod', 'frexp', 'ldexp', 'modf', 'isfinite', 'isinf', 'isnan', 'trunc', 'radians', 'degrees']

CircuitPython supports 30-bit wide floating point values so you can use int's and float's whenever you expect

tuples, lists, arrays, and dictionaries

You can organize data in ()',  []'s , and {}'s including strings, objects, floats, etc

classes/objects and functions

We use objects and functions extensively in our libraries so check out one of our many examples like this MCP9808 library for class examples

lambdas

Yep! You can create function-functions with lambda just the way you like em:

>>> g = lambda x: x**2
>>> g(8)
64

 

Things to watch out for!

  • The wide body of python libraries have not been ported over, so while we wish you could import numpy, numpy isn't available. So you may have to port some code over yourself!
  • For the ATSAMD21 based boards (Feather M0, Metro M0, Trinket M0, Gemma M0, Circuit PlayGround Express) there's a limited amount of RAM, we've found you can have about 250-ish lines of python (that's with various libraries) before you hit MemoryErrors. The upcoming SAMD51 chipset will help with that a ton but its not yet available)
  • Non-Express boards like Trinket M0 and Gemma M0 and non-Express Feathers do not include all of the hardware support. For example, audioio and bitbangio are not included.
  • Integers can only be up to 31 bits. Integers of unlimited size are not supported.
  • We keep up with MicroPython stable releases, so check out the core 'differences' they document here.

CircuitPython Expectations

CircuitPython runs nicely on the Gemma or Trinket M0 but there are some constraints

Small Disk Space

Since we use the internal flash for disk, and that's shared with runtime code, its limited! Only about 50KB of space. Our Express line of boards have a whopping 2 MB of external Flash, if you need more space

No PWM & PulseIO

As of CircuitPython 2.1 we have added PulseIO support to Trinket & Gemma M0. That means PWM, piezo, servo, DHT22 and Infrared support!

No Audio or NVM

Part of giving up that FLASH for disk means we couldn't fit everything in. There is, at this time, no support for hardware audio playpack or NVM 'eeprom'. For that support, check out the Circuit Playground Express or other Express boards

However, I2C, UART, capacitive touch, NeoPixel, PWM, analog in and out, digital IO, logging storage, and HID do work! Check below for quick starts on all these.

CircuitPython Digital In & Out

The first part of interfacing with hardware is being able to manage digital inputs and outputs. With Circuitpython it's super easy!

This quick-start example shows how you can turn one of the Gemma pads into a button input with pullup resistor (built in) and then use that to control another digital output - the built in LED

Copy and paste the code block into main.py using your favorite text editor, and save the file, to run the demo

# CircuitPython IO demo #1 - General Purpose I/O

from digitalio import DigitalInOut, Direction, Pull
import board
import time

led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT

button = DigitalInOut(board.D2)
button.direction = Direction.INPUT
button.pull = Pull.UP

while True:
    # we could also just do "led.value = not button.value" !
    if button.value:
		led.value = False
    else:
		led.value = True

    time.sleep(0.01) # debounce delay

Note that we made the code a little less 'pythonic' than necessary, the if/then could be replaced with a simple led.value = not button.value but I wanted to make it super clear how to test the inputs. When the interpreter gets to evaluating button.value that is when it will read the digital input.

Find the pin or pad labeled D2 (sometimes just 2) and use a wire to touch it to GND, the onboard red LED will turn on!

Note that on the M0/SAMD based CircuitPython boards, at least, you can also have internal pulldowns with Pull.DOWN and if you want to turn off the pullup/pulldown just assign button.pull = None

CircuitPython Analog In

This quick-start example shows how you can read the analog voltages on all three Gemma M0 pads.

Copy and paste the code block into main.py using your favorite text editor, and save the file, to run the demo

# Gemma IO demo - analog inputs

from digitalio import DigitalInOut, Direction
from analogio import AnalogIn
import board
import time

led = DigitalInOut(board.L)
led.direction = Direction.OUTPUT

analog0in = AnalogIn(board.A0)
analog1in = AnalogIn(board.A1)
analog2in = AnalogIn(board.A2)

def getVoltage(pin):
    return (pin.value * 3.3) / 65536

while True:
    print("A0: %f \t\t A1: %f \t\t A2: %f" %
          (getVoltage(analog0in),
           getVoltage(analog1in),
           getVoltage(analog2in)))

    time.sleep(0.1)

Creating analog inputs

analog0in = AnalogIn(A0)
analog1in = AnalogIn(A1)
analog2in = AnalogIn(A2)

Creates three objects, one for each pad, and connects the objects to A0, A1 and A2 as analog inputs.

GetVoltage Helper

getVoltage(pin) is our little helper program. By default, analog readings will range from 0 (minimum) to 65535 (maximum). This helper will convert the 0-65535 reading from pin.value and convert it a 0-3.3V voltage reading.

Main Loop

The main loop is simple, it will just print out the three voltages as floating point values (the %f indicates to print as floating point) by calling getVoltage on each of our analog objects.

If you connect to the serial port REPL, you'll see the voltages printed out. By default the pins are floating so the voltages will vary. Try touching a wire from A0 to the GND or 3Vo pad to see the voltage change!

CircuitPython Analog Out

This quick-start example shows how you can set the DAC (true analog voltage output) on pad A0 (no other pins do analog out)

Copy and paste the code block into main.py using your favorite text editor, and save the file, to run the demo

# CircuitPython IO demo - analog output
     
from analogio import AnalogOut
import board
import time
    
aout = AnalogOut(board.A0)
     
while True:
  # Count up from 0 to 65535, with 64 increment
  # which ends up corresponding to the DAC's 10-bit range
  for i in range (0,65535,64):
    aout.value = i

Creating an analog output

aout = AnalogOut(A0)

Creates an object aout that is connected to the only DAC pin available - A0.

Setting the analog output

The DAC on the SAMD21 is a 10-bit output, from 0-3.3V. So in theory you will have a resolution of 0.0032 Volts per bit. To allow CircuitPython to be general-purpose enough that it can be used with chips with anything from 8 to 16-bit DACs, the DAC takes a 16-bit value and divides it down internally.

E.g. writing 0 will be the same as setting it to 0 - 0 Volts out

Writing 5000 is the same as setting it to 5000 / 64 = 78
And 78 / 1024 * 3.3V = 0.25V output

Writing 65535 is the same as 1023 which is the top range and you'll get 3.3V output

Main Loop

The main loop is fairly simple, it just goes through the entire range of the DAC, from 0 to 65535, but increments 64 at a time so it ends up clicking up one bit for each of the 10-bits of range available.

CircuitPython is not terribly fast, so at the fastest update loop you'll get 4 Hz. The DAC isn't good for audio outputs as-is.

If you have an 'Express' board like the Circuit Playground Express, Metro M0 or Feather M0, these have more code space and can perform audio playback capabilities via the DAC. Gemma/Trinket M0 cannot!

CircuitPython PWM

As of CircuitPython 2.1 we have pulseio support for Gemma, so you can PWM LEDs, control servos, beep piezos, and manage 'pulse train' type devices like DHT22 and Infrared.

On Gemma, you get two PWMs, D0 and D2. Actually, you get a third, but that's on the L LED). D1/A0 has true analog out but does not have PWM!

Don't forget you have to update your CircuitPython firmware to 2.1 to get this support!

Timer mapping

There's a limited number of timers available. But timers have many outputs. You have have two PWM outputs that share a timer but they must have the same frequency (they can vary the duty cycle just not frequency)

When you create an pulseio object, the lowest # Timer that is not already being used, will be used.

So, LED can use timer 0 or timer 4, but will default to the lowest timer. If you want to use all three, define D0's and D2's PWM objects first! Then you can change the LED pin's frequency

Pin name

Timers Available

D0

Timer #0

D2

Timer #0

L (LED)

Timer #0 and Timer #4

Both D0 and D2 are on the same timer so if you want to use both at the same time, they MUST be the same frequency!

PWM Output with Fixed Frequency

This sketch demonstrates how to create two PWM outputs on each pin.

The frequency for D2 and D0 must be the same (1000 hz) but you can vary the duty cycle between the two!

import pulseio
import time
import board

pwm0 = pulseio.PWMOut(board.D0, frequency=1000, duty_cycle=0)
pwm2 = pulseio.PWMOut(board.D2, frequency=1000, duty_cycle=0)

led = pulseio.PWMOut(board.L, frequency=5000, duty_cycle=0)

while True:
    for i in range(100):
        # PWM D0 from low to high duty cycle
        pwm0.duty_cycle = int(i * 65535 / 100)
        # PWM D2 from high to low
        pwm2.duty_cycle = 65535 - pwm0.duty_cycle
        time.sleep(0.01)
	# PWM LED up and down
	if i < 50:
	    led.duty_cycle = int(i * 2 * 65535 / 100) # up
	else:
	    led.duty_cycle = 65535 - int((i-50) * 2 * 65535 / 100) # down

Create a PWM output with pulseio.PWMOut and pass in the pin to use, then you can set the initial frequency and also initial duty_cycle!

PWM Output with Variable Frequency

Fixed frequency outputs are great for pulsing LEDs or controlling servos. But if you want to make some beeps with a piezo, you'll need to vary the frequency.

Remember that on the Gemma, both PWM outputs are on a single timer, so you can only have one variable frequency output - but it can be on either pin

import pulseio
import time
import board

piezo = pulseio.PWMOut(board.D2, duty_cycle=0, frequency=440, variable_frequency=True)

while True:
    for f in (262, 294, 330, 349, 392, 440, 494, 523):
	piezo.frequency = f
	piezo.duty_cycle =65536//2    # on 50%
	time.sleep(0.25)              # on for 1/4 second
	piezo.duty_cycle = 0          # off
	time.sleep(0.05)              # pause between notes
    time.sleep(0.5)

If you have simpleio library installed we have a nice little helper that makes a tone for you on a piezo with a single command:

import pulseio
import time
import board
import simpleio

while True:
    for f in (262, 294, 330, 349, 392, 440, 494, 523):
	simpleio.tone(board.D2, f, 0.25)  # on for 1/4 second
	time.sleep(0.05)                  # pause between notes
    time.sleep(0.5)

As you can tell, its a lot prettier!

CircuitPython Servo

In order to use servos, we take advantage of pulseio. Now, in theory, you could just use the raw pulseio calls to set the frequency to 50 Hz and then set the pulse widths. But we would rather make it a little more elegant and easy!

So, instead we will use simpleio which manages servos for you quite nicely! simpleio is a library so be sure to grab it from the library bundle if you have not yet!

If you are using a non-Express (Gemma, Trinket, Adalogger...) you must be running CircuitPython 2.1+ to get PWM support

Wiring

Servos will only work on PWM-capable pins! Check your board details to verify which pins have PWM/Timer outputs

Connect the servo's brown or black ground wire to ground on the CircuitPython board.

Connect the servo's red power wire to 5V power, USB power is good for a servo or two. For more than that, you'll need an external battery back. Do not use 3.3V for powering a servo!

Connect the servo's yellow or white signal wire to the control/data pin, in this case D2 but you can pin any PWM-capable pin.

Here's an example that will sweep a servo connected to pin D2 from 0 degrees to 180 degrees and back

import time
import board
import simpleio

servo = simpleio.Servo(board.D2)

# sweep back and forth!
while True:
    for angle in range (0, 180, 5): # 0-180 degrees, 5 degrees at a time
	servo.angle = angle
	time.sleep(0.05)
    for angle in range (180, 0, -5): # 180-0 degrees, 5 degrees at a time
	servo.angle = angle
	time.sleep(0.05)

Pretty simple!

Note that we assume that 0 degrees is 0.5ms and 180 degrees is a pulse width of 2.5ms. That's a bit wider than the official 1-2ms pulse widths. If you have a servo that has a different range you can just initialize the Servo object with a different min/max pulse:

servo = simpleio.Servo(board.D2, min_pulse = 0.5, max_pulse = 2.5):

You can have a servo on each pin that has a timer. Note that the timer gets set to 50 Hz so if you want a PWM with a different frequency have it on a pin that isn't the same timer (check the CircuitPython PWM page for more details on timers)

CircuitPython Cap Touch

This quick-start example shows how you can read the capacitive touch sensors built into on all three Gemma M0 pads.

Copy and paste the code block into main.py using your favorite text editor, and save the file, to run the demo

# Gemma IO demo - captouch

import touchio
import board
import time

touch0 = touchio.TouchIn(board.A0)
touch1 = touchio.TouchIn(board.A1)
touch2 = touchio.TouchIn(board.A2)

while True:
    if touch0.value:
        print("A0 touched!")
    if touch1.value:
        print("A1 touched!")
    if touch2.value:
        print("A2 touched!")
    time.sleep(0.01)

You can open up the serial console to see the touches detected and printed out.

Creating an capacitive touch input

All three pads can be used as capacitive TouchIn devices:

touch0 = touchio.TouchIn(A0)
touch1 = touchio.TouchIn(A1)
touch2 = touchio.TouchIn(A2)

Creates three objects, one connected to each of the Gemma M0 pads.

Main Loop

The main loop checks each sensor one after the other, to determine if it has been touched. If touch0.value returns True, that means that that pad, A0, detected a touch. For each pad, if it has been touched, a message will print.

A small sleep delay is added at the end so the loop doesn't run too fast. You may want to change the delay from 0.1 seconds to 0 seconds to slow it down or speed it up.

Note that no extra hardware is required, you can touch the pads directly, but you may want to attach alligator clips or foil tape to metallic or conductive objects. Try silverware, fruit or other food, liquid, aluminum foil, and items around your desk!

You may need to restart your code/board after changing the attached item because the capacitive touch code 'calibrates' based on what it sees when it first starts up. So if you get too many touch-signals or not enough, hit that reset button!

Copper Foil Tape with Conductive Adhesive - 6mm x 15 meter roll

PRODUCT ID: 1128
Copper tape can be an interesting addition to your toolbox. The tape itself is made of thin pure copper so its extremely flexible and can take on nearly any shape. You can easily solder...
$5.95
IN STOCK

Copper Foil Tape with Conductive Adhesive - 25mm x 15 meter roll

PRODUCT ID: 1127
Copper tape can be an interesting addition to your toolbox. The tape itself is made of thin pure copper so its extremely flexible and can take on nearly any shape. You can easily solder...
$19.95
IN STOCK

Small Alligator Clip Test Lead (set of 12)

PRODUCT ID: 1008
Connect this to that without soldering using these handy mini alligator clip test leads. 15" cables with alligator clip on each end, color coded. You get 12 pieces in 6 colors....
$3.95
IN STOCK

CircuitPython Internal DotStar

This quick-start example builds upon the previous example, but shows how you can create interactivity using capacitive touch. It also demonstrates the built in DotStar LED and how you can change the color on your own.

Copy and paste the code block into main.py using your favorite text editor, and save the file, to run the demo

# Gemma IO demo - captouch to dotstar

import touchio
import busio
import board
import time

dotstar = busio.SPI(board.APA102_SCK, board.APA102_MOSI)
touch0 = touchio.TouchIn(board.A0)
touch1 = touchio.TouchIn(board.A1)
touch2 = touchio.TouchIn(board.A2)

r = g = b = 0

def setPixel(red, green, blue):
    if not dotstar.try_lock():
        return
    print("setting pixel to: %d %d %d" % (red, green, blue))

    data = bytearray([0x00, 0x00, 0x00, 0x00,
                      0xff, blue, green, red,
                      0xff, 0xff, 0xff, 0xff])
    dotstar.write(data)
    dotstar.unlock()
    time.sleep(0.01)

while True:
    if touch0.value:
        r = (r+1) % 256
    if touch1.value:
        g = (g+1) % 256
    if touch2.value:
        b = (b+1) % 256

    setPixel(r, g, b)

Each of the three pads will change the color of the built in mini DotStar LED. You can touch each pad in order to see the LED change colors, or you can open up the serial console to see the touches detected and the pixel color printed out.

CircuitPython UART Serial

This quick-start example shows how you can create a UART device for communicating with hardware serial devices

Copy and paste the code block into main.py using your favorite text editor, and save the file, to run the demo

# Gemma IO demo - USB/Serial echo

from digitalio import *
from board import *
import busio
import time

led = DigitalInOut(D13)
led.direction = Direction.OUTPUT

uart = busio.UART(D0, D2, baudrate=9600)

while True:
    data = uart.read(32)  # read up to 32 bytes
    #print(data)          # this is a bytearray type

    if data != None:
        led.value = True

	datastr = ''.join([chr(b) for b in data]) # convert bytearray to string
	print(datastr, end="")

        led.value = False

In addition to the USB-serial connection you use for the REPL, there is also a hardware UART you can use. This is handy to talk to UART devices like GPS's, some sensors, or other microcontrollers!

You can create a new UART object with uart = busio.UART(D0, D2, baudrate=9600) You can use only D0 and D2 as the transmitting and receiving pins on the Gemma M0. Set the baudrate to whatever you like.

Once the object is created you read data in with read(numbytes) where you can specify the max number of bytes. It will return a bytearray type object if anything was received already. Note it will always return immediately because there is an internal buffer! So read as much data as you can 'digest'.

If there is no data available, read() will return None, so check for that before continuing.

The data that is returned is in a byte array, if you want to convert it to a string, you can use this handy line of code which will run chr() on each byte:

datastr = ''.join([chr(b) for b in data]) # convert bytearray to string

To run this demo, you'll need something to generate UART data. We connected up a GPS!

CircuitPython I2C Scan

This quick-start example shows how you can use CircuitPython to scan the I2C bus for all connected devices

Copy and paste the code block into main.py using your favorite text editor, and save the file, to run the demo

# Gemma/Trinket IO demo - I2C scan

import board
import busio
import time

# can also use board.SDA and board.SCL for neater looking code!
i2c = busio.I2C(board.D2, board.D0)

while not i2c.try_lock():
    pass

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

You can also use the Gemma to chat with I2C sensors and devices. Before you start, we recommend connecting it up and doing an I2C scan so you can tell if it was detected.

You can create the I2C devices on the Gemma M0's D2 (SCL) and D0 (SDA) pins.

Then run a scan with i2c.scan() It will return an array of addresses, but since usually they are referred to in hex format, you may want to convert the array to hexadecimals with [hex(i) for i in i2c.scan()])

Don't forget that the Gemma M0 does not have I2C pullup resistors built in, you must add 2.2-10K ohm pullups on both SDA and SCL to 3.3V (our breakouts come with them already)

We wired up a Flora TSL2561 breakout with address 0x39 to test it!

CircuitPython I2C Sensor

We have drivers for many popular I2C sensors in our driver bundle (and more being written all the time!)

I2C is a 2-wire protocol for communicating with simple sensors and devices and its really easy to use with CircuitPython

Remember that the Gemma & Trinket M0 does not have the required i2c pull-up resistors on SDA or SCL! You must have those on the sensor board (all of ours do) or add them yourself. 10K ohm pullups to 3.3V work well, you cannot use the 'internal' pullups.

Lets try wiring up to a nice Si7021 temperature & humidity sensor:

# I2C sensor demo

import board
import busio
import adafruit_si7021
import time

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

# lock the I2C device before we try to scan
while not i2c.try_lock():
    pass
print("I2C addresses found:", [hex(i) for i in i2c.scan()])

# unlock I2C now that we're done scanning.
i2c.unlock()

# Create library object on our I2C port
si7021 = adafruit_si7021.SI7021(i2c)


# Use library to read the data!
while True:
    print("Temp: %0.2F *C   Humidity: %0.1F %%" % (si7021.temperature, si7021.relative_humidity))
    time.sleep(1)

We used our Alligator-to-breadboard wires to connect up the Gemma to a Si7021 breakout

  • Vin connects to 3.3V
  • GND connects to GND
  • SDA connects to D0
  • SCL connects to D2

With a Trinket M0, a small breadboard fits both pieces, just wire it up so

  • Vin connects to 3.3V
  • GND connects to GND
  • SDA connects to D0
  • SCL connects to D2

Adafruit Si7021 Temperature & Humidity Sensor Breakout Board

PRODUCT ID: 3251
It's summer and you're sweating and your hair's all frizzy and all you really want to know is why the weatherman said this morning that today's relative humidity would max...
$6.95
IN STOCK

Small Alligator Clip to Male Jumper Wire Bundle - 12 Pieces

PRODUCT ID: 3255
For bread-boarding with unusual non-header-friendly surfaces, these cables will be your best friends! No longer will you have long strands of alligator clips that are grabbing little...
$7.95
IN STOCK

Then check the REPL. If you have not yet used this chip you may get an ImportError: no module named 'adafruit_si7021'

That means you need to install the Adafruit_Si7021 library that gives you the friendly interface we use above.

Check out our page on Installing Libraries to learn how to download the driver bundle and drag the driver you need to the lib folder

You will also need the adafruit_bus_device library folder - that will give you I2C access in a nice manner!

Once you're done you'll see you have the libraries installed:

Finally if you re-run you will be able to see the temperature and humidity data from the sensor:

CircuitPython NeoPixel

NeoPixels are a revolutionary and ultra-popular way to add lights and color to your project. These stranded RGB lights have the controller inside the LED, so you just push the RGB data and the LEDs do all the work for you! They're a perfect match for CircuitPython

You can drive 300 pixels with brightness control and 1000 pixels without (set brightness=1.0 in object creation). That's because to adjust the brighness we have to dynamically re-create the datastream each write.

Here's an example with a lot of different visual effects you can check out. You'll need the neopixel.mpy library file if you don't have it yet!

# CircuitPython demo - NeoPixel

import board
import neopixel
import time

pixpin = board.D1
numpix = 10

strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.3, auto_write=False)


def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    # The colours are a transition r - g - b - back to r.
    if (pos < 0) or (pos > 255):
        return (0, 0, 0)
    if (pos < 85):
        return (int(pos * 3), int(255 - (pos*3)), 0)
    elif (pos < 170):
        pos -= 85
        return (int(255 - pos*3), 0, int(pos*3))
    else:
        pos -= 170
        return (0, int(pos*3), int(255 - pos*3))

def rainbow_cycle(wait):
    for j in range(255):
        for i in range(len(strip)):
            idx = int ((i * 256 / len(strip)) + j)
            strip[i] = wheel(idx & 255)
        strip.write()
        time.sleep(wait)

while True:
    strip.fill((255, 0, 0))
    strip.write()
    time.sleep(1)

    strip.fill((0, 255, 0))
    strip.write()
    time.sleep(1)

    strip.fill((0, 0, 255))
    strip.write()
    time.sleep(1)

    rainbow_cycle(0.001)    # rainbowcycle with 1ms delay per step

This code will work with any NeoPixel-compatible.

NeoPixels can be driven by any pin.

For powering the pixels from the board, the 3.3V regulator output from the Trinket/Gemma M0 can handle about 500mA peak which is about 50 pixels with 'average' use. If you want really bright lights and a lot of pixels, we recommend powering direct from the power source. On the Gemma M0 this is the Vout pad - that pad has direct power from USB or BAT, depending on which is higher voltage. On the Trinket M0 the USB or BAT pins will give you direct power from the USB port or battery.

The NeoPixel object's argument list requires the pin you'll use (any pin can be used) and the number of pixels. There's two optional arguments, brightness (range from 0 off to 1.0 full brightness) and auto_write. When auto_write default is set to True, every change is immediately written to the strip of pixels, this is easier to use but way slower. if you set auto_write=False then you will  have to call strip.show() when you want to actually write color data out.

You can easily set colors by indexing into the location strip[n] = (red, green, blue). For example, strip[0] = (100, 0, 0) will set the first pixel to a medium-brightness red, and strip[2] = (0, 255, 0) will set the third pixel to bright green. Then, if you have auto_write=Falsedon't forget to call strip.show() 

Verify the wiring on your strip or device - plugging into the 'DOUT' side is a common mistake! Wire up NeoPixels only while the Trinket or Gemma is not on, to avoid possible damage!

If the power to the NeoPixels is > 5.5V you may have some difficulty driving some strips, in which case you may need to lower the voltage to 4.5-5V or use a level shifter

We have a ton more information on general purpose NeoPixel know-how at our NeoPixel UberGuide https://learn.adafruit.com/adafruit-neopixel-uberguide

CircuitPython DotStar

DotStars use two wires, unlike NeoPixel's one wire. They're very similar but you can write to DotStars much faster with hardware SPI and they have a faster PWM cycle so they are better for light painting.

You can drive 300 pixels with brightness control and 1000 pixels without (set brightness=1.0 in object creation). That's because to adjust the brighness we have to dynamically re-create the datastream each write.

Here's an example with a lot of different visual effects you can check out. You'll need the adafruit_dotstar.mpy library file if you don't have it yet!

The DotStar object's argument list requires the two pins you'll use and the number of pixels. Any pins can be used but if the two pins can form a hardware SPI port, the library will automatically switch over to hardware SPI. If you use hardware SPI then you'll get 4 MHz clock rate (that would mean updating a 64 pixel strand in about 500uS - that's 0.0005 seconds). If you use non-hardware SPI pins you'll drop down to about 3KHz, 1000 times as slow!

On the Gemma M0, if you use adafruit_dotstar.DotStar(board.D2, board.D0...) you'll get hardware SPI

On the Trinket M0, you can use D2 & D0, D2 & D3, D3 & D0,  or D3 & D4

There's two optional arguments, brightness (range from 0 off to 1.0 full brightness) and auto_write. When auto_write default is set to True, where every change is immediately written to the strip of pixels, this is easier to use but way slower. if you set auto_write=False then you will  have to call strip.show() when you want to actually write color data out.

# CircuitPython demo - Dotstar

import board
import adafruit_dotstar
import time

numpix = 64
strip = adafruit_dotstar.DotStar(board.D2, board.D0, numpix, brightness=0.2)

def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    # The colours are a transition r - g - b - back to r.
    if (pos < 0) or (pos > 255):
        return (0, 0, 0)
    if (pos < 85):
        return (int(pos * 3), int(255 - (pos*3)), 0)
    elif (pos < 170):
        pos -= 85
        return (int(255 - pos*3), 0, int(pos*3))
    else:
        pos -= 170
        return (0, int(pos*3), int(255 - pos*3))

def rainbow_cycle(wait):
    for j in range(255):
        for i in range(len(strip)):
            idx = int ((i * 256 / len(strip)) + j)
            strip[i] = wheel(idx & 255)
        strip.show()
        time.sleep(wait)

while True:
    strip.fill((255, 0, 0))
    strip.show()
    time.sleep(1)

    strip.fill((0, 255, 0))
    strip.show()
    time.sleep(1)

    strip.fill((0, 0, 255))
    strip.show()
    time.sleep(1)

    rainbow_cycle(0.001) # high speed rainbow cycle w/1ms delay per sweep

This code will work with any DotStar-compatible.

DotStars can be driven by any two pins (just slower if they are not hardware pins)

For powering the pixels from the board, the 3.3V regulator output from the Trinket/Gemma M0 can handle about 500mA peak which is about 50 pixels with 'average' use. If you want really bright lights and a lot of pixels, we recommend powering direct from the power source. On the Gemma M0 this is the Vout pad - that pad has direct power from USB or BAT, depending on which is higher voltage. On the Trinket M0 the USB or BAT pins will give you direct power from the USB port or battery.

The DotStar object's argument list requires the 2 pins you'll use and the number of pixels. There's two optional arguments, brightness (range from 0 off to 1.0 full brightness) and auto_write. When auto_write default is set to True, where every change is immediately written to the strip of pixels, this is easier to use but way slower. if you set auto_write=False then you will  have to call strip.show() when you want to actually write color data out.

You can easily set colors by indexing into the location strip[n] = (red, green, blue). For example, strip[0] = (100, 0, 0) will set the first pixel to a medium-brightness red, and strip[2] = (0, 255, 0) will set the third pixel to bright green. Then, if you have auto_write=Falsedon't forget to call strip.show() 

Verify the wiring on your strip or device - plugging into the 'DOUT' side is a common mistake! Wire up DotStars only while the Trinket/Gemma is not on, to avoid possible damage!

If the power to the pixels is > 5.5V you may have some difficulty driving some strips, in which case you may need to lower the voltage to 4.5-5V or use a level shifter

We have a ton more information on general purpose DotStar know-how at our DotStar UberGuide https://learn.adafruit.com/adafruit-dotstar-leds

CircuitPython HID Keyboard

One of the things we baked into CircuitPython is 'HID' control - Keyboard and Mouse capabilities. This means a Trinket or Gemma can act like a keyboard device and press keys, or a mouse and have it move the mouse around and press buttons. This is really handy because even if you cannot adapt your software to work with hardware, there's almost always a keyboard interface - so if you want to have a capacitive touch interface for a game, say, then keyboard emulation can often get you going really fast!

You'll need to install the adafruit_hid bundle which comes with Keyboard, Keycode and Mouse support

Then try running this example code which will create 3 'buttons' on three Trinket or Gemma pins

# CircuitPlayground demo - Keyboard emu

from digitalio import DigitalInOut, Direction, Pull
import touchio
import board
import time
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

# A simple neat keyboard demo in circuitpython

# The button pins we'll use, each will have an internal pullup
buttonpins = [board.D2, board.D1, board.D0]
# our array of button objects
buttons = []
# The keycode sent for each button, will be paired with a control key
buttonkeys = [Keycode.A, Keycode.B, "Hello World!\n"]
controlkey = Keycode.SHIFT

# the keyboard object!
kbd = Keyboard()
# we're americans :)
layout = KeyboardLayoutUS(kbd)

# make all pin objects, make them inputs w/pullups
for pin in buttonpins:
    button = DigitalInOut(pin)
    button.direction = Direction.INPUT
    button.pull = Pull.UP   
    buttons.append(button)

led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT
 
print("Waiting for button presses")

while True:
    # check each button
    for button in buttons:
        if not button.value:   # pressed?
            i = buttons.index(button)
            print("Button #%d Pressed" % i)

            # turn on the LED
            led.value = True

            while not button.value:
                pass  # wait for it to be released!
            # type the keycode or string
            k = buttonkeys[i]    # get the corresp. keycode/str
            if type(k) is str:
                layout.write(k)
            else:
                kbd.press(controlkey, k) # press...
                kbd.release_all()        # release!

            # turn off the LED
            led.value = False
    
    time.sleep(0.01)

Touch any of the digital IO pads to ground using a wire to have the keypresses sent.

The Keyboard and Layout object are created, we only have US right now (if you make other layouts please submit a GitHub pull request!)

# the keyboard object!
kbd = Keyboard()
# we're americans :)
layout = KeyboardLayoutUS(kbd)

Then you can send key-down's with kbd.press(keycode, ...) You can have up to 6 keycode presses at once. Note that these are keycodes so if you want to send a capital A, you need both SHIFT and A. Don't forget to call kbd.release_all() soon after or you'll have a stuck key which is really annoying!

You can also send full strings, with layout.write("Hello World!\n") - it will use the layout to determine the keycodes to press.

For more detail check out the documentation at https://circuitpython.readthedocs.io/projects/hid/en/latest/

CircuitPython DHT Sensor

DHT sensors are low cost humidity and temperature sensors with maker/beginner-level quality. Their simplicity makes them popular for many DIY projects. And you can use them with CircuitPython!

Wiring

DHT wiring is very simple:

  • The left-most pin is power. We recommend powering from 5V (sometimes 3V is not enough) - this is OK even if you are using 3.3V logic
  • The second pin is data. Connect a 10K pullup resistor from this pin to 3.3V. If you are using a DHT11 it's required. If you're using a DHT22 or AM2302 you can sometimes leave this off
  • Skip the third pin
  • The right-most pin is ground
For the DATA pin you must pick a pin that has PWM support (pulseio) - Check the board's guide for what pins have timers available

Here's an example using a Trinket M0 - you can use any CircuitPython board, just check that the Data pin is pulseio-capable.

You'll need the adafruit_dht library from the bundle so be sure that's installed, then you can run this code:

import board
import time
import adafruit_dht


dht  = adafruit_dht.DHT22(board.D2)

while True:
    try:
        temperature = dht.temperature
        humidity = dht.humidity
        # Print what we got to the REPL
        print("Temp: {:.1f} *C \t Humidity: {}% ".format(temperature, humidity))
    except RuntimeError as e:
        # Reading doesn't always work! Just print error and we'll try again
        print("Reading from DHT failure: ",e.args)

    time.sleep(1)

If you are using a DHT11, change the code to use a adafruit_dht.DHT11(board.D2) object.

Open the REPL to see the output! Breathe on the sensor to see it move temperature and humidity up (unless you are a White Walker in which case the temperature will go down)

Don't be concerned if once in a while you get an error, these sensors are pretty basic and sometimes the data transfer fails. The code will just try again!

CircuitPython CPU Temp

This little built in sensor comes with all ATSAMD21 chips, and its really nice to have a temperature sensor so we let you read it via CircuitPython, its new since 2.0.0 and only available on the ATSAMD21-based boards (e.g. not ESP8266)

It's so easy, we'll just give you the two REPL commands

>>> import microcontroller
>>> microcontroller.cpu.temperature

That's it! You'll have the temperature in Centigrade printed out. Note it is not exactly the same as ambient temperature, and its not super precise. But it's kinda close!

CircuitPython Storage

You have been using that little USB drive to put code on, but maybe you've wondered "Hey can I write data from Python to the storage drive to act as a datalogger?" The answer is yes (as of CircuitPython 2.0.0)!

But it is a little bit tricky - you need to add some special code to boot.py not just main.py. That's because you have to set the filesystem to be read-only when you need to edit code to the disk from your computer, and set it to be write-able when you want the CircuitPython core to be able to write.

You can only have either your computer edit the CIRCUITPY drive files, or CircuitPython. You cannot have both write to the drive (Bad Things Will Happen so we do not allow you to do it!)

Here is your new boot.py:

import digitalio
import board
import storage

switch = digitalio.DigitalInOut(board.D0)
switch.direction = digitalio.Direction.INPUT
switch.pull = digitalio.Pull.UP

# If the D0 is connected to ground with a wire
# CircuitPython can write to the drive
storage.remount("/", switch.value)

And here is the main.py

import board
import digitalio
import microcontroller
import time

led = digitalio.DigitalInOut(board.D13)
led.switch_to_output()

try:
    with open("/temperature.txt", "a") as fp:
        while True:
            temp = microcontroller.cpu.temperature
            # do the C-to-F conversion here if you would like
            fp.write('{0:f}\n'.format(temp))
            fp.flush()
            led.value = not led.value
            time.sleep(1)
except OSError as e:
    delay = 0.5
    if e.args[0] == 28:
        delay = 0.25
    while True:
        led.value = not led.value
        time.sleep(delay)
boot.py only runs on first boot of the device, not if you re-start the REPL with ^D or if you save the file, so you must EJECT the USB drive, then physically press the reset button!

Eject & unplug the Trinket or Gemma once you have written these files. Then connect a wire from D0 to ground. This will enable the internal filesystem writing. Now power up the board again.

You will not be able to edit code on the CIRCUITPY drive anymore!

The red LED should blink once a second and you will see a new temperature.txt file.

This file gets updated once a second but you wont see data come in live. Instead, when you're ready to grab the data, remove the D0 wire and re-plug-in the Trinket/Gemma (or press the reset button). Now it will be possible for you to write to the filesystem from your computer again, but it will not be logging data.

We have a more detailed guide on this project available here https://learn.adafruit.com/cpu-temperature-logging-with-circuit-python

Handy Tips

Check Heap Memory Usage

import gc

gc.mem_free()

Will give you the number of bytes available for use.

Random Numbers

import random

random.random() will give a floating point number from 0 to 1.0

random.randint(min, max) will give you an integer number between min and max

Troubleshooting

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

CPLAYBOOT, TRINKETBOOT, FEATHERBOOT, or GEMMABOOT Drive Not Present

You may have a different board.

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

MakeCode

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

Windows 10

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

Windows 7

The latest version of the Adafruit Windows Drivers (version 2.0.0.0 or later) will fix the missing boardnameBOOT drive problem on Windows 7. To resolve this, first uninstall the old versions of the drivers:

  • Unplug any boards. In Uninstall or Change a Program (Control Panel->Programs->Uninstall a program), uninstall everything named "Windows Driver Package - Adafruit Industries LLC ...".
  • Now install the new 2.0.0.0 (or higher) Adafruit Windows Drivers Package:
  • When running the installer, you'll be shown a list of drivers to choose from. You can check and uncheck the boxes to choose which drivers to install.

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

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

CircuitPython RGB Status Light

The Feather M0 Express, Metro M0 Express, Gemma M0, and Trinket M0 all have a single NeoPixel or DotStar RGB LED on the board that indicates the status of CircuitPython. Here's what the colors and blinking mean:

  • steady GREEN: code.py (or code.txt, main.py, or main.txt) is running
  • pulsing GREEN: code.py (etc.) has finished or does not exist
  • YELLOW: Circuit Python is in safe mode: it crashed and restarted
  • WHITE: REPL is running
  • BLUE: Circuit Python is starting up

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

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

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

CIRCUITPY Drive Issues

You may find that you can no longer save files to your CIRCUITPY drive. You may find that your CIRCUITPY stops showing up in your file explorer, or shows up as NO_NAME. These are indicators that your filesystem has become corrupted.

This happens most often when the CIRCUITPY disk is not safely ejected before being reset by the button or being disconnected from USB. It can happen on Windows, Mac or Linux.

In this situation, the board must be completely erased and CircuitPython must be reloaded onto the board.

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

For the Circuit Playground Express, Feather M0 Express, and Metro M0 Express:

       1.  Download the correct erase file:

       2.  Double-click the reset button on the board to bring up the boardnameBOOT drive.
       3.  Drag the erase .uf2 file to the boardnameBOOT drive.
       4.  The onboard NeoPixel will turn blue, indicating the erase has started.
       5.  After approximately 15 seconds, the NeoPixel will start flashing green.
       6.  Double-click the reset button on the board to bring up the boardnameBOOT drive.
       7.  Drag the appropriate latest release of CircuitPython .uf2 file to the boardnameBOOT drive.

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

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

If you haven't already downloaded the latest release of CircuitPython for your board, you can find it here.

For the Gemma M0, Trinket M0, Feather M0: Basic (Proto) and Feather Adalogger:

       1.  Download the erase file:

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

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

If you haven't already downloaded the latest version of CircuitPython for your board, you can find it here.

Running Out of File Space on Non-Express Boards

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

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

Delete something!

The simplest way of freeing up space is to delete files from the drive. Perhaps there are libraries in the lib folder that you aren't using anymore or test code that isn't in use.

Use tabs

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

Mac OSX loves to add extra files.

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

Prevent & Remove Mac OSX Hidden Files

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

ls -l /Volumes

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

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

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

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

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

Copy Files on Mac OSX Without Creating Hidden Files

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

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

cp -X foo.mpy /Volumes/CIRCUITPY

Or to copy a folder and all of its child files/folders use a command like:

cp -rX folder_to_copy /Volumes/CIRCUITPY

Other Mac OSX Space-Saving Tips

If you'd like to see the amount of space used on the drive and manually delete hidden files here's how to do so.  First list the amount of space used on the CIRCUITPY drive with the df command:

Lets remove the ._ files first.

Whoa! We have 13Ki more than before! This space can now be used for libraries and code!

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 be using version 1.8 or higher for this guide

After you have downloaded and installed the latest version of Arduino IDE, you will need to start the IDE and navigate to the Preferences menu. You can access it from the File menu in Windows or Linux, or the Arduino menu on OS X.

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

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 URL once. New Adafruit boards and updates to existing boards will automatically be picked up by the Board Manager each time 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 add, you can visit the list of third party board URLs on the Arduino IDE wiki. 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 Additional Boards Manager URLs option in the Arduino IDE preferences.

https://adafruit.github.io/arduino-board-index/package_adafruit_index.json

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, Trinket, & Trinket Pro.
  • Adafruit SAMD Boards - Includes support for Feather M0, Metro M0, 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.

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!

Using with Arduino IDE

Since the Feather/Metro/Gemma/Trinket M0 use an ATSAMD21 chip running at 48 MHz, you can pretty easily get it working with the Arduino IDE. Most libraries (including the popular ones like NeoPixels and display) will work with the M0, 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 menu.

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

Install SAMD Support

First up, install the Arduino SAMD Boards version 1.6.15 or later

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

Install Adafruit SAMD

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

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

Even though in theory you don't need to - I recommend rebooting the IDE

Quit and reopen 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

Install Drivers (Windows 7 Only)

When you plug in the board, you'll need to possibly install a driver

Click below to download our Driver Installer

Download and run the installer

Run the installer! Since we bundle the SiLabs and FTDI drivers as well, you'll need to click through the license

Select which drivers you want to install, the defaults will set you up with just about every Adafruit board!

Click Install to do the installin'

Blink

Now you can upload your first blink sketch!

Plug in the Gemma M0, Trinket M0, Metro M0 or Feather M0 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 dropdown, it'll even be 'indicated' as Trinket/Gemma/Metro/Feather M0!

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.

If you are having issues, make sure you selected the matching Board in the menu that matches the hardware you have in your hand.

Sucessful 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

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

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, 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.

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

Ubuntu & Linux Issue Fix

Note if you're using Ubuntu 15.04 (or perhaps other more recent Linux distributions) there is an issue with the modem manager service which causes the Bluefruit LE micro to be difficult to program.  If you run into errors like "device or resource busy", "bad file descriptor", or "port is busy" when attempting to program then you are hitting this issue.

The fix for this issue is to make sure Adafruit's custom udev rules are applied to your system.  One of these rules is made to configure modem manager not to touch the Feather board and will fix the programming difficulty issue.  Follow the steps for installing Adafruit's udev rules on this page.

Adapting Sketches to M0

The ATSAMD21 is a very nice little chip but its fairly new as Arduino-compatible cores go. Most sketches & libraries will work but here's a few things we noticed!

The below note are for all M0 boards, but not all may apply (e.g. Trinket and Gemma M0 do not have ARef so you can skip the Analog References note!)

Analog References

If you'd like to use the ARef pin for a non-3.3V analog reference, the code to use is analogReference(AR_EXTERNAL) (it's AR_EXTERNAL not EXTERNAL)

Pin Outputs & Pullups

The old-style way of turning on a pin as an input with a pullup is to use

pinMode(pin, INPUT)
digitalWrite(pin, HIGH)

This is because the pullup-selection register is the same as the output-selection register.

For the M0, you can't do this anymore! Instead, use

pinMode(pin, INPUT_PULLUP)

which has the benefit of being backwards compatible with AVR.

Serial vs SerialUSB

99.9% of your existing Arduino sketches use Serial.print to debug and give output. For the Official Arduino SAMD/M0 core, this goes to the Serial5 port, which isn't exposed on the Feather. The USB port for the Official Arduino M0 core, is called SerialUSB instead.

In the Adafruit M0 Core, we fixed it so that Serial goes to USB when you use a Feather M0 so it will automatically work just fine.

However, on the off chance you are using the official Arduino SAMD core not the Adafruit version (which really, we recommend you use our version because as you can see it can vary) & you want your Serial prints and reads to use the USB port, use SerialUSB instead of Serial in your sketch

If you have existing sketches and code and you want them to work with the M0 without a huge find-replace, put

#if defined(ARDUINO_SAMD_ZERO) && defined(SERIAL_PORT_USBVIRTUAL)
  // Required for Serial on Zero based boards
  #define Serial SERIAL_PORT_USBVIRTUAL
#endif

right above the first function definition in your code. For example:

AnalogWrite / PWM on Feather/Metro M0

After looking through the SAMD21 datasheet, we've found that some of the options listed in the multiplexer table don't exist on the specific chip used in the Feather M0.

For all SAMD21 chips, there are two peripherals that can generate PWM signals: The Timer/Counter (TC) and Timer/Counter for Control Applications (TCC). Each SAMD21 has multiple copies of each, called 'instances'.

Each TC instance has one count register, one control register, and two output channels. Either channel can be enabled and disabled, and either channel can be inverted. The pins connected to a TC instance can output identical versions of the same PWM waveform, or complementary waveforms.

Each TCC instance has a single count register, but multiple compare registers and output channels. There are options for different kinds of waveform, interleaved switching, programmable dead time, and so on.

The biggest members of the SAMD21 family have five TC instances with two 'waveform output' (WO) channels, and three TCC instances with eight WO channels:

  • TC[0-4],WO[0-1]
  • TCC[0-2],WO[0-7]

And those are the ones shown in the datasheet's multiplexer tables.

The SAMD21G used in the Feather M0 only has three TC instances with two output channels, and three TCC instances with eight output channels:

  • TC[3-5],WO[0-1]
  • TCC[0-2],WO[0-7]

Tracing the signals to the pins broken out on the Feather M0, the following pins can't do PWM at all:

  • Analog pin A5

The following pins can be configured for PWM without any signal conflicts as long as the SPI, I2C, and UART pins keep their protocol functions:

  • Digital pins 5, 6, 9, 10, 11, 12, and 13
  • Analog pins A3 and A4

If only the SPI pins keep their protocol functions, you can also do PWM on the following pins:

  • TX and SDA (Digital pins 1 and 20)

analogWrite() PWM range

On AVR, if you set a pin's PWM with analogWrite(pin, 255) it will turn the pin fully HIGH. On the ARM cortex, it will set it to be 255/256 so there will be very slim but still-existing pulses-to-0V. If you need the pin to be fully on, add test code that checks if you are trying to analogWrite(pin, 255) and, instead, does a digitalWrite(pin, HIGH)

Missing header files

there might be code that uses libraries that are not supported by the M0 core. For example if you have a line with

#include <util/delay.h>

you'll get an error that says

fatal error: util/delay.h: No such file or directory
  #include <util/delay.h>
                         ^
compilation terminated.
Error compiling.

In which case you can simply locate where the line is (the error will give you the file name and line number) and 'wrap it' with #ifdef's so it looks like:

#if !defined(ARDUINO_ARCH_SAM) && !defined(ARDUINO_ARCH_SAMD) && !defined(ESP8266) && !defined(ARDUINO_ARCH_STM32F2)
 #include <util/delay.h>
#endif

The above will also make sure that header file isn't included for other architectures

If the #include is in the arduino sketch itself, you can try just removing the line.

Bootloader Launching

For most other AVRs, clicking reset while plugged into USB will launch the bootloader manually, the bootloader will time out after a few seconds. For the M0, you'll need to double click the button. You will see a pulsing red LED to let you know you're in bootloader mode. Once in that mode, it wont time out! Click reset again if you want to go back to launching code

Aligned Memory Access

This is a little less likely to happen to you but it happened to me! If you're used to 8-bit platforms, you can do this nice thing where you can typecast variables around. e.g.

uint8_t mybuffer[4];
float f = (float)mybuffer;

You can't be guaranteed that this will work on a 32-bit platform because mybuffer might not be aligned to a 2 or 4-byte boundary. The ARM Cortex-M0 can only directly access data on 16-bit boundaries (every 2 or 4 bytes). Trying to access an odd-boundary byte (on a 1 or 3 byte location) will cause a Hard Fault and stop the MCU. Thankfully, there's an easy work around ... just use memcpy!

uint8_t mybuffer[4];
float f;
memcpy(f, mybuffer, 4)

Floating Point Conversion

Like the AVR Arduinos, the M0 library does not have full support for converting floating point numbers to ASCII strings. Functions like sprintf will not convert floating point.  Fortunately, the standard AVR-LIBC library includes the dtostrf function which can handle the conversion for you.

Unfortunately, the M0 run-time library does not have dtostrf.  You may see some references to using #include <avr/dtostrf.h> to get dtostrf in your code.  And while it will compile, it does not work.

Instead, check out this thread to find a working dtostrf function you can include in your code:

http://forum.arduino.cc/index.php?topic=368720.0

How Much RAM Available?

The ATSAMD21G18 has 32K of RAM, but you still might need to track it for some reason. You can do so with this handy function:

extern "C" char *sbrk(int i);

int FreeRam () {
  char stack_dummy = 0;
  return &stack_dummy - sbrk(0);
}

Storing data in FLASH

If you're used to AVR, you've probably used PROGMEM to let the compiler know you'd like to put a variable or string in flash memory to save on RAM. On the ARM, its a little easier, simply add const before the variable name:

const char str[] = "My very long string";

That string is now in FLASH. You can manipulate the string just like RAM data, the compiler will automatically read from FLASH so you dont need special progmem-knowledgeable functions.

You can verify where data is stored by printing out the address:
Serial.print("Address of str $"); Serial.println((int)&str, HEX);

If the address is $2000000 or larger, its in SRAM. If the address is between $0000 and $3FFFF Then it is in FLASH

UF2 Bootloader Details

This is an information page for advanced users who are curious how we get code from your computer into your Express board!

Adafruit Express and Gemma/Trinket M0 boards feature an improved bootloader that makes it easier than ever to flash different code onto the microcontroller. This bootloader makes it easy to switch between Microsoft MakeCode, CircuitPython and Arduino.

Instead of needing drivers or a separate program for flashing (say, bossac, jlink or avrdude), one can simply drag a file onto a removable drive.

The format of the file is a little special. Due to 'operating system woes' you cannot just drag a binary or hex file (trust us, we tried it, it isn't cross-platform compatible). Instead, the format of the file has extra information to help the bootloader know where the data goes. The format is called UF2 (USB Flashing Format). Microsoft MakeCode generates UF2s for flashing and CircuitPython releases are also available as UF2. You can also create your own UF2s from binary files using uf2tool, available here.

The bootloader is also BOSSA compatible, so it can be used with the Arduino IDE which expects a BOSSA bootloader on ATSAMD-based boards

For more information about UF2, you can read a bunch more at the MakeCode blog, then check out the UF2 file format specification and to build your own bootloader for ATSAMD-based boards, visit Microsoft UF2-SAMD github repository.

The bootloader is not needed when changing your CircuitPython code. Its only needed when upgrading the CircuitPython core or changing between CircuitPython, Arduino and Microsoft MakeCode.

Entering Bootloader Mode

The first step to loading new code onto your board is triggering the bootloader. It is easily done by double tapping the reset button. Once the bootloader is active you will see the small red LED fade in and out and a new drive will appear on your computer with a name ending in BOOT. For example, feathers show up as FEATHERBOOT, while the new CircuitPlayground shows up as CPLAYBOOT, Trinket M0 will show up as TRINKETBOOT, and Gemma M0 will show up as GEMMABOOT

Furthermore, when the bootloader is active, it will change the color of one or more onboard neopixels to indicate the connection status, red for disconnected and green for connected. If the board is plugged in but still showing that its disconnected, try a different USB cable. Some cables only provide power with no communication.

For example, here is a Feather M0 Express running a colorful Neopixel swirl. When the reset button is double clicked (about half second between each click) the NeoPixel will stay green to let you know the bootloader is active. When the reset button is clicked once, the 'user program' (NeoPixel color swirl) restarts.

If the bootloader couldn't start, you will get a red NeoPixel LED.

That could mean that your USB cable is no good, it isn't connected to a computer, or maybe the drivers could not enumerate. Try a new USB cable first. Then try another port on your computer!

Once the bootloader is running, check your computer. You should see a USB Disk drive...

Once the bootloader is successfully connected you can open the drive and browse the virtual filesystem. This isn't the same filesystem as you use with CircuitPython or Arduino. It should have three files:

  •  CURRENT.UF2 - The current contents of the microcontroller flash.
  •  INDEX.HTM - Links to Microsoft MakeCode.
  •  INFO_UF2.TXT - Includes bootloader version info. Please include it on bug reports.

Using the Mass Storage Bootloader

To flash something new, simply drag any UF2 onto the drive. After the file is finished copying, the bootloader will automatically restart. This usually causes a warning about an unsafe eject of the drive. However, its not a problem. The bootloader knows when everything is copied successfully.

You may get an alert from the OS that the file is being copied without it's properties. You can just click Yes

You may also get get a complaint that the drive was ejected without warning. Don't worry about this. The drive only ejects once the bootloader has verified and completed the process of writing the new code

Using the BOSSA Bootloader

As mentioned before, the bootloader is also compatible with BOSSA, which is the standard method of updating boards when in the Arduino IDE. It is a command-line tool that can be used in any operating system. We won't cover the full use of the bossac tool, suffice to say it can do quite a bit! More information is available at ShumaTech.

Windows 7 Drivers

If you are running Windows 7 (or, goodness, something earlier?) You will need a Serial Port driver file. Windows 10 users do not need this so skip this step.

You can download our full driver package here:

Download and run the installer. We recommend just selecting all the serial port drivers available (no harm to do so) and installing them.

Verifying Serial Port in Device Manager

If you're running Windows, its a good idea to verify the device showed up. Open your Device Manager from the control panel and look under Ports (COM & LPT) for a device called Feather M0 or Circuit Playground or whatever!

If you see something like this, it means you did not install the drivers. Go back and try again, then remove and re-plug the USB cable for your board

Running bossac on the command line

If you are using the Arduino IDE, this step is not required. But sometimes you want to read/write custom binary files, say for loading CircuitPython or your own code. We recommend using bossac v 1.7.0 (or greater), which has been tested. The Arduino branch is most recommended.

You can download the latest builds here. The mingw32 version is for Windows, apple-darwin for Mac OSX and various linux options for Linux. Once downloaded, extract the files from the zip and open the command line to the directory with bossac

For example here's the command line you probably want to run:

bossac -e -w -v -R ~/Downloads/adafruit-circuitpython-feather_m0_express-0.9.3.bin

This will -erase the chip, -write the given file, -verify the write and -Reset the board. After reset, CircuitPython should be running. Express boards may cause a warning of an early eject of a USB drive but just ignore it. Nothing important was being written to the drive. A hard power-reset is also  recommended after bossac, just in case.

Updating the bootloader

The UF2 bootloader is a new bootloader, and while we've done a ton of testing, it may contain bugs. Usually these bugs effect reliability rather than fully preventing the bootloader from working. If the bootloader is flaky then you can try updating the bootloader itself to potentially improve reliability.

Updating the bootloader is as easy as flashing CircuitPython, Arduino or MakeCode. Simply enter the bootloader as above and then drag the update bootloader uf2 file below. This uf2 contains a program which will unlock the bootloader section, update the bootloader, and re-lock it. It will overwrite your existing code such as CircuitPython or Arduino so make sure everything is backed up!

After the file is copied over, the bootloader will be updated and appear again. The INFO_UF2.TXT file should show the newer version number inside.

For example:

UF2 Bootloader v1.20.0 SFHR
Model: Adafruit Feather M0
Board-ID: SAMD21G18A-Feather-v0

Lastly, reload your code from Arduino or MakeCode or flash the latest CircuitPython core.

The latest updaters for various boards:

Getting Rid of Windows Pop-ups

If you do a lot of development on Windows with the UF2 bootloader, you may get annoyed by the constant "Hey you inserted a drive what do you want to do" pop-ups.

Go to the Control Panel. Click on the Hardware and Sound header

Click on the Autoplay header

Uncheck the box at the top, labeled Use Autoplay for all devices

Making your own UF2

Making your own UF2 is easy! All you need is a .bin file of a program you wish to flash and the Python conversion script. Make sure that your program was compiled to start at 0x2000 (8k) because the bootloader takes the first 8k. CircuitPython's linker script is an example on how to do that.

Once you have a .bin file, you simply need to run the Python conversion script over it. Here is an example from the directory with uf2conv.py:

uf2conv.py -c -o build-circuitplayground_express/revg.uf2 build-circuitplayground_express/revg.bin

This will produce a revg.uf2 file in the same directory as the source revg.bin. The uf2 can then be flashed in the same way as above.

Downloads