Adafruit Feather M0 Express - Designed for CircuitPython Created by lady ada Last updated on 2018-12-13 04:59:12 PM UTC
Guide Contents Guide Contents Overview Pinouts Power Pins Logic pins SPI Flash and NeoPixel Other Pins! Debug Interface Assembly Header Options! Soldering in Plain Headers Prepare the header strip: Add the breakout board: And Solder! Soldering on Female Header Tape In Place Flip & Tack Solder And Solder! 19 20 20 22 22 23 24 Power Management Battery + USB Power Power supplies Measuring Battery ENable pin Arduino IDE Setup https://adafruit.github.io/arduino-board-index/package_adafruit_index.
Missing header files Bootloader Launching Aligned Memory Access Floating Point Conversion How Much RAM Available? Storing data in FLASH Pretty-Printing out registers Using SPI Flash Read & Write CircuitPython Files Format Flash Memory Datalogging Example Reading and Printing Files Full Usage Example Accessing SPI Flash Feather HELP! 41 41 41 42 42 42 42 44 44 46 47 48 48 49 51 My ItsyBitsy/Feather stopped working when I unplugged the USB! 51 My Feather never shows up as a COM or Serial port in the Arduino
Exploring Your First CircuitPython Program 65 Imports & Libraries Setting Up The LED Loop-de-loops 66 66 66 More Changes Naming Your Program File Connecting to the Serial Console Are you using Mu? Using Something Else? Interacting with the Serial Console The REPL Returning to the serial console CircuitPython Libraries 67 67 68 68 69 70 73 76 78 Installing the CircuitPython Library Bundle Example Files Express Boards Non-Express Boards Example: ImportError Due to Missing Library Library Install on Non-
Backup Your Code 92 Moving to MakeCode Moving to Arduino Welcome to the Community! Adafruit Discord Adafruit Forums Adafruit Github ReadTheDocs 92 93 95 95 96 97 98 CircuitPython Essentials CircuitPython Built-Ins Thing That Are Built In and Work Flow Control Math Tuples, Lists, Arrays, and Dictionaries Classes, Objects and Functions Lambdas Random Numbers CircuitPython Digital In & Out Find the pins! Read the Docs 99 100 100 100 100 100 100 100 100 101 102 104 CircuitPython Analog In 105 Creating
Main Loop Making Rainbows (Because Who Doesn't Love 'Em!) Circuit Playground Express Rainbow CircuitPython NeoPixel Wiring It Up The Code Create the LED NeoPixel Helpers Main Loop NeoPixel RGBW Read the Docs 130 131 132 134 134 135 136 137 137 137 139 CircuitPython DotStar Wire It Up The Code Create the LED DotStar Helpers Main Loop Is it SPI? Read the Docs 140 140 141 143 144 144 144 145 CircuitPython UART Serial The Code Wire It Up Where's my UART? Trinket M0: Create UART before I2C 146 146 147 150
Differences Between CircuitPython and Python Python Libraries Integers in CircuitPython Floating Point Numbers and Digits of Precision for Floats in CircuitPython Differences between MicroPython and Python Frequently Asked Questions What is a MemoryError? What do I do when I encounter a MemoryError? How can I create my own .
Getting Rid of Windows Pop-ups Making your own UF2 Installing the bootloader on a fresh/bricked board Downloads Datasheets Firmware Schematic & Fabrication Print © Adafruit Industries https://learn.adafruit.
Overview We love all our Feathers equally, but this Feather is very special. It's our first Feather that is specifically designed for use with CircuitPython! CircuitPython is our beginner-oriented flavor of MicroPython - and as the name hints at, its a small but full-featured version of the popular Python programming language specifically for use with circuitry and electronics.
256KB of FLASH + 32KB of RAM No EEPROM 32.768 KHz crystal for clock generation & RTC 3.
Comes fully assembled and tested, with a USB bootloader that lets you quickly use it with the Arduino IDE or for loading Circuit Python. We also toss in some header so you can solder it in and plug into a solderless breadboard. Lipoly battery and USB cable not included (but we do have lots of options in the shop if you'd like!) © Adafruit Industries https://learn.adafruit.
Pinouts (There's a typo in the above, AREF Is PA03 not PA02) The Feather M0 is chock-full of microcontroller goodness. There's also a lot of pins and ports. We'll take you a tour of them now! Power Pins © Adafruit Industries https://learn.adafruit.
GND - this is the common ground for all power and logic BAT - this is the positive voltage to/from the JST jack for the optional Lipoly battery USB - this is the positive voltage to/from the micro USB jack if connected EN - this is the 3.3V regulator's enable pin. It's pulled up, so connect to ground to disable the 3.3V regulator 3V - this is the output from the 3.3V regulator, it can supply 500mA peak Logic pins This is the general purpose I/O pin set for the microcontroller. All logic is 3.
#10 - GPIO #10 #11 - GPIO #11 #12 - GPIO #12 #13 - GPIO #13 and is connected to the red LED next to the USB jack A0 - This pin is analog input A0 but is also an analog output due to having a DAC (digital-to-analog converter). You can set the raw voltage to anything from 0 to 3.3V, unlike PWM outputs this is a true analog output A1 thru A5 - These are each analog input as well as digital I/O pins.
RST - this is the Reset pin, tie to ground to manually reset the AVR, as well as launch the bootloader manually ARef - the analog reference pin. Normally the reference voltage is the same as the chip logic voltage (3.3V) but if you need an alternative analog reference, connect it to this pin and select the external AREF in your firmware. Can't go higher than 3.3V! Debug Interface SWCLK & SWDIO - These pads on the bottom are used to program the chip. They can also be connected to an SWD debugger.
Assembly We ship Feathers fully tested but without headers attached - this gives you the most flexibility on choosing how to use and configure your Feather Header Options! Before you go gung-ho on soldering, there's a few options to consider! The first option is soldering in plain male headers, this lets you plug in the Feather into a solderless breadboard © Adafruit Industries https://learn.adafruit.
Another option is to go with socket female headers. This won't let you plug the Feather into a breadboard but it will let you attach featherwings very easily © Adafruit Industries https://learn.adafruit.
We also have 'slim' versions of the female headers, that are a little shorter and give a more compact shape © Adafruit Industries https://learn.adafruit.
Finally, there's the "Stacking Header" option. This one is sort of the best-of-both-worlds. You get the ability to plug into a solderless breadboard and plug a featherwing on top. But its a little bulky Soldering in Plain Headers Prepare the header strip: Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - long pins down © Adafruit Industries https://learn.adafruit.
Add the breakout board: Place the breakout board over the pins so that the short pins poke through the breakout pads And Solder! Be sure to solder all pins for reliable electrical contact. (For tips on soldering, be sure to check out our Guide to Excellent Soldering (https://adafru.it/aTk)). © Adafruit Industries https://learn.adafruit.
Solder the other strip as well. © Adafruit Industries https://learn.adafruit.
You're done! Check your solder joints visually and continue onto the next steps Soldering on Female Header Tape In Place For sockets you'll want to tape them in place so when you flip over the board they don't fall out Flip & Tack Solder After flipping over, solder one or two points on each strip, to 'tack' the header in place © Adafruit Industries https://learn.adafruit.
© Adafruit Industries https://learn.adafruit.
And Solder! Be sure to solder all pins for reliable electrical contact. (For tips on soldering, be sure to check out our Guide to Excellent Soldering (https://adafru.it/aTk)). © Adafruit Industries https://learn.adafruit.
You're done! Check your solder joints visually and continue onto the next steps © Adafruit Industries https://learn.adafruit.
Power Management Battery + USB Power We wanted to make the Feather easy to power both when connected to a computer as well as via battery. There's two ways to power a Feather. You can connect with a MicroUSB cable (just plug into the jack) and the Feather will regulate the 5V USB down to 3.3V. You can also connect a 4.2/3.7V Lithium Polymer (Lipo/Lipoly) or Lithium Ion (LiIon) battery to the JST jack. This will let the Feather run on a rechargable battery.
The above shows the Micro USB jack (left), Lipoly JST jack (top left), as well as the 3.3V regulator and changeover diode (just to the right of the JST jack) and the Lipoly charging circuitry (to the right of the Reset button). There's also a CHG LED, which will light up while the battery is charging. This LED might also flicker if the battery is not connected.
// Arduino Example Code #define VBATPIN A7 float measuredvbat = analogRead(VBATPIN); measuredvbat *= 2; // we divided by 2, so multiply back measuredvbat *= 3.3; // Multiply by 3.3V, our reference voltage measuredvbat /= 1024; // convert to voltage Serial.print("VBat: " ); Serial.println(measuredvbat); For CircuitPython, we've written a get_voltage() helper function to do the math for you. All you have to do is call the function, provide the pin and print the results.
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 https://adafru.it/f1P https://adafru.it/f1P 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.
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.
Using with Arduino IDE The Feather/Metro/Gemma/Trinket M0 and M4 use an ATSAMD21 or ATSAMD51 chip, and 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 and M4, 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.
Next you can install the Adafruit SAMD package to add the board file definitions Make sure you have Type All selected to the left of the Filter your search... box You can type Adafruit SAMD in the top search bar, then when you see the entry, click Install 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.
Install Drivers (Windows 7 & 8 Only) When you plug in the board, you'll need to possibly install a driver Click below to download our Driver Installer https://adafru.it/AB0 https://adafru.it/AB0 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 © Adafruit Industries https://learn.adafruit.
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 M0 or M4 board, and wait for it to be recognized by the OS (just takes a few seconds). It will create a serial/COM port, you can now select it from the drop-down, it'll even be 'indicated' as Trinket/Gemma/Metro/Feather/ItsyBitsy/Trellis! © Adafruit Industries https://learn.adafruit.
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.
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.
Follow the steps for installing Adafruit's udev rules on this page. (https://adafru.it/iOE) © Adafruit Industries https://learn.adafruit.
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.
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.
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.
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 ...
There's a lot of registers on the SAMD21, and you often are going through ASF or another framework to get to them. So having a way to see exactly what's going on is handy. This library from drewfish will help a ton! https://github.com/drewfish/arduino-ZeroRegs (https://adafru.it/Bet) © Adafruit Industries https://learn.adafruit.
Using SPI Flash One of the best features of the M0 express board is a small SPI flash memory chip built into the board. This memory can be used for almost any purpose like storing data files, Python code, and more. Think of it like a little SD card that is always connected to the board, and in fact with Arduino you can access the memory using a library that is very similar to the Arduino SD card library (https://adafru.it/ucu).
#define FLASH_SS SS1 #define FLASH_SPI_PORT SPI1 // Flash chip SS pin. // What SPI port is Flash on? Adafruit_SPIFlash flash(FLASH_SS, &FLASH_SPI_PORT); // Use hardware SPI // Alternatively you can define and use non-SPI pins! //Adafruit_SPIFlash flash(SCK1, MISO1, MOSI1, FLASH_SS); // Finally create an Adafruit_M0_Express_CircuitPython object which gives // an SD card-like interface to interacting with files stored in CircuitPython's // flash filesystem.
// Create or append to a data.txt file and add a new line // to the end of it. CircuitPython code can later open and // see this file too! File data = pythonfs.open("data.txt", FILE_WRITE); if (data) { // Write a new line to the file: data.println("Hello CircuitPython from Arduino!"); data.close(); // See the other fatfs examples like fatfs_full_usage and fatfs_datalogging // for more examples of interacting with files. Serial.println("Wrote a new line to the end of data.txt!"); } else { Serial.
Type OK and press enter in the serial monitor input to confirm that you'd like to format the flash memory. You need to enter OK in all capital letters! Once confirmed the sketch will format the flash memory. The format process takes about a minute so be patient as the data is erased and formatted. You should see a message printed once the format process is complete. At this point the flash chip will be ready to use with a brand new empty filesystem.
however instead of calling open on a global SD card object you're calling it on a fatfs object created earlier in the sketch (look at the top after the #define configuration values). Once the file is opened it's simply a matter of calling print and println functions on the file object to write data inside of it. This is just like writing data to the serial monitor and you can print out text, numeric, and other types of data.
Accessing SPI Flash Arduino doesn't have the ability to show up as a 'mass storage' disk drive. So instead we must use CircuitPython to do that part for us. Here's the full technique: Start the bootloader on the Express board. Drag over the latest circuitpython uf2 file After a moment, you should see a CIRCUITPY drive appear on your hard drive with boot_out.txt on it Now go to Arduino and upload the fatfs_circuitpython example sketch from the Adafruit SPI library. Open the serial console.
© Adafruit Industries https://learn.adafruit.
Feather HELP! Even though this FAQ is labeled for Feather, the questions apply to ItsyBitsy's as well! My ItsyBitsy/Feather stopped working when I unplugged the USB! A lot of our example sketches have a while (!Serial); line in setup(), to keep the board waiting until the USB is opened. This makes it a lot easier to debug a program because you get to see all the USB data output.
I can't get the Itsy/Feather USB device to show up - I get "USB Device Malfunctioning" errors! This seems to happen when people select the wrong board from the Arduino Boards menu. If you have a Feather 32u4 (look on the board to read what it is you have) Make sure you select Feather 32u4 for ATMega32u4 based boards! Do not use anything else, do not use the 32u4 breakout board line.
When the user COM port disappears, Arduino will not be able to automatically start the bootloader and upload new software.
What is CircuitPython? CircuitPython is a programming language designed to simplify experimenting and learning to program on low-cost microcontroller boards. It makes getting started easier than ever with no upfront desktop downloads needed. Once you get your board set up, open any text editor, and get started editing code. It's that simple. CircuitPython is based on Python Python is the fastest growing programming language. It's taught in schools and universities.
You're new to programming. CircuitPython is designed with education in mind. It's easy to start learning how to program and you get immediate feedback from the board. Easily update your code. Since your code lives on the disk drive, you can edit it whenever you like, you can also keep multiple files around for easy experimentation. The serial console and REPL. These allow for live feedback from your code and interactive programming. File storage.
CircuitPython As we continue to develop CircuitPython and create new releases, we will stop supporting older releases. If you are running CircuitPython 2.x, you need to update to 3.x: https://learn.adafruit.com/welcome-tocircuitpython/installing-circuitpython CircuitPython (https://adafru.it/tB7) is a derivative of MicroPython (https://adafru.it/BeZ) designed to simplify experimentation and education on low-cost microcontrollers.
Plug your Feather M0 into your computer using a known-good USB cable. A lot of people end up using charge-only USB cables and it is very frustrating! So make sure you have a USB cable you know is good for data sync. Double-click the Reset button next to the USB connector on your board, and you will see the NeoPixel RGB LED turn green. If it turns red, check the USB cable, try another USB port, etc. Note: The little red LED next to the USB connector will pulse red.
The LED will flash. Then, the FEATHERBOOT drive will disappear and a new disk drive called CIRCUITPY will appear. That's it, you're done! :) Further Information For more detailed info on installing CircuitPython, check out Installing CircuitPython (https://adafru.it/Amd). © Adafruit Industries https://learn.adafruit.
Installing Mu Editor Mu is a simple code editor that works with the Adafruit CircuitPython boards. It's written in Python and works on Windows, MacOS, Linux and Raspberry Pi.
The first time you start Mu, you will be prompted to select your 'mode' - you can always change your mind later. For now please select Adafruit! The current mode is displayed in the lower right corner of the window, next to the "gear" icon. If the mode says "Microbit" or something else, click on that and then choose "Adafruit" in the dialog box that appears.
Mu Packages Mu is currently being developed. So there are lots of changes being made! Current versions are available from links at the bottom of this page (https://adafru.it/Be5). However, use at your own risk! These are not stable versions and come with no guarantees of working. © Adafruit Industries https://learn.adafruit.
Creating and Editing Code One of the best things about CircuitPython is how simple it is to get code up and running. In this section, we're going to cover how to create and edit your first CircuitPython program. To create and edit code, all you'll need is an editor. There are many options.
It will look like this - note that under the while True: line, the next four lines have spaces to indent them, but they're indented exactly the same amount. All other lines have no spaces before the text. Save this file as code.py on your CIRCUITPY drive. On each board you'll find a tiny red LED. It should now be blinking. Once per second © Adafruit Industries https://learn.adafruit.
Congratulations, you've just run your first CircuitPython program! Editing Code To edit code, open the code.py file on your CIRCUITPY drive into your editor. Make the desired changes to your code. Save the file. That's it! Your code changes are run as soon as the file is done saving. There's just one warning we have to give you before we continue... Don't Click Reset or Unplug! The CircuitPython code on your board detects when the files are changed or written and will automatically re-start your code.
Recommended only with particular settings or with add-ons: The PyCharm IDE (https://adafru.it/xNC) is safe if "Safe Write" is turned on in Settings->System Settings>Synchronization (true by default). If you are using Atom (https://adafru.it/fMG), install this package (https://adafru.it/Be8) so that it will always write out all changes to files on CIRCUITPY . SlickEdit (https://adafru.it/DdP) works only if you add a macro to flush the disk (https://adafru.it/ven).
import board import digitalio import time led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT while True: led.value = True time.sleep(0.5) led.value = False time.sleep(0.5) Imports & Libraries Each CircuitPython program you run needs to have a lot of information to work. The reason CircuitPython is so simple to use is that most of that information is stored in other files and works in the background. These files are called libraries. Some of them are built into CircuitPython.
while True: led.value = True time.sleep(0.5) led.value = False time.sleep(0.5) First, we have led.value = True . This line tells the LED to turn on. On the next line, we have time.sleep(0.5) . This line is telling CircuitPython to pause running code for 0.5 seconds. Since this is between turning the led on and off, the led will be on for 0.5 seconds. The next two lines are similar. led.value = False tells the LED to turn off, and time.sleep(0.5) tells CircuitPython to pause for another 0.5 seconds.
Connecting to the Serial Console One of the staples of CircuitPython (and programming in general!) is something called a "print statement". This is a line you include in your code that causes your code to output text. A print statement in CircuitPython looks like this: print("Hello, world!") This line would result in: Hello, world! However, these print statements need somewhere to display.
Once in Mu, look for the Serial button in the menu and click it. Using Something Else? If you're not using Mu to edit, are using ESP8266 or nRF52 CircuitPython, or if for some reason you are not a fan of the built in serial console, you can run the serial console as a separate program. Windows requires you to download a terminal program, check out this page for more details (https://adafru.
Interacting with the Serial Console Once you've successfully connected to the serial console, it's time to start using it. The code you wrote earlier has no output to the serial console. So, we're going to edit it to create some output. Open your code.py file into your editor, and include a print statement. You can print anything you like! Just include your phrase between the quotation marks inside the parentheses. For example: import board import digitalio import time led = digitalio.DigitalInOut(board.
The Traceback (most recent call last): is telling you the last thing your board was doing before you saved your file. This is normal behavior and will happen every time the board resets. This is really handy for troubleshooting. Let's introduce an error so we can see how it is used. Delete the e at the end of True from the line led.value = True so that it says led.value = Tru Save your file. You will notice that your red LED will stop blinking, and you may have a colored status LED blinking at you.
The Traceback (most recent call last): is telling you that the last thing it was able to run was line 10 in your code. The next line is your error: NameError: name 'Tru' is not defined . This error might not mean a lot to you, but combined with knowing the issue is on line 10, it gives you a great place to start! Go back to your code, and take a look at line 10. Obviously, you know what the problem is already. But if you didn't, you'd want to look at line 10 and see if you could figure it out.
The REPL The other feature of the serial connection is the Read-Evaluate-Print-Loop, or REPL. The REPL allows you to enter individual lines of code and have them run immediately. It's really handy if you're running into trouble with a particular program and can't figure out why. It's interactive so it's great for testing new ideas. To use the REPL, you first need to be connected to the serial console. Once that connection has been established, you'll want to press Ctrl + C.
If you have trouble getting to the >>> prompt, try pressing Ctrl + C a few more times. The first thing you get from the REPL is information about your board. This line tells you the version of CircuitPython you're using and when it was released. Next, it gives you the type of board you're using and the type of microcontroller the board uses. Each part of this may be different for your board depending on the versions you're working with. This is followed by the CircuitPython prompt.
Type help("modules") into the REPL next to the prompt, and press enter. This is a list of all the core libraries built into CircuitPython. We discussed how board contains all of the pins on the board that you can use in your code. From the REPL, you are able to see that list! Type import board into the REPL and press enter. It'll go to a new prompt.
This is a list of all of the pins on your board that are available for you to use in your code. Each board's list will differ slightly depending on the number of pins available. Do you see D13 ? That's the pin you used to blink the red LED! The REPL can also be used to run code. Be aware that any code you enter into the REPL isn't saved anywhere.
© Adafruit Industries https://learn.adafruit.
CircuitPython Libraries As we continue to develop CircuitPython and create new releases, we will stop supporting older releases. If you are running CircuitPython 2.x, you need to update to 3.x. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update to CircuitPython 3.x and then download the 3.x bundle. Each CircuitPython program you run needs to have a lot of information to work.
full library bundle. Instead, you can find example code in the guides for your board that depends on external libraries. Some of these libraries may be available from us at Adafruit, some may be written by community members! Either way, as you start to explore CircuitPython, you'll want to know how to get libraries on board. You can grab the latest Adafruit CircuitPython 3.x Bundle release by clicking this button: https://adafru.it/y8E https://adafru.
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 and examples directories can be copied directly to the CIRCUITPY drive.
Let's use a modified version of the blinky example. import board import time import simpleio led = simpleio.DigitalOut(board.D13) while True: led.value = True time.sleep(0.5) led.value = False time.sleep(0.5) Save this file. Nothing happens to your board. Let's check the serial console to see what's going on. We have an ImportError . It says there is no module named 'simpleio' . That's the one we just included in our code! Click the link above to download the correct bundle.
If you have a Trinket M0 or Gemma M0, you'll want to follow the same steps in the example above to install libraries as you need them. You don't always need to wait for an ImportError as you probably know what library you added to your code. Simply open the lib folder you downloaded, find the library you need, and drag it to the lib folder on your CIRCUITPY drive. For these boards, your internal storage is from the chip itself. So, these boards don't have enough space for all of the libraries.
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. As we continue to develop CircuitPython and create new releases, we will stop supporting older releases. If you are running CircuitPython 2.x, you need to update to 3.x. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update to CircuitPython 3.x and then download the 3.x bundle.
everything named "Windows Driver Package - Adafruit Industries LLC ...". Now install the new 2.3.0.0 (or higher) Adafruit Windows Drivers Package: https://adafru.it/AB0 https://adafru.it/AB0 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.
and released a beta version that fixes the problem. This may have been incorporated into the latest release. Please let us know in the forums if you test thi.s Hard Disk Sentinel Kaspersky anti-virus: To fix, you may need to disable Kaspersky completely. Disabling some aspects of Kaspersky does not always solve the problem. This problem has been reported to Kaspersky. CIRCUITPY Drive Does Not Appear Kaspersky anti-virus can block the appearance of the CIRCUITPY drive.
Circuit Playground Express does NOT have a status LED. The LEDs will pulse green when in the bootloader. They do NOT indicate any status while running 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.
You WILL lose everything on the board when you complete the following steps. If possible, make a copy of your code before continuing. Easiest Way: Use storage.erase_filesystem() Starting with version 2.3.0, CircuitPython includes a built-in function to erase and reformat the filesystem. If you have an older version of CircuitPython on your board, you can update to the newest version (https://adafru.it/Amd) to do this. 1. Connect to the CircuitPython REPL (https://adafru.
It should reboot automatically and you should see CIRCUITPY in your file explorer again. If the LED flashes red during step 5, it means the erase has failed. Repeat the steps starting with 2. If you haven't already downloaded the latest release of CircuitPython for your board, check out the installation page (https://adafru.it/Amd).
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 humanreadable 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.
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.
Whoa! We have 13Ki more than before! This space can now be used for libraries and code! © Adafruit Industries https://learn.adafruit.
Uninstalling CircuitPython A lot of our boards can be used with multiple programming languages. For example, the Circuit Playground Express can be used with MakeCode, Code.org CS Discoveries, CircuitPython and Arduino.
Your MakeCode is now running and CircuitPython has been removed. Going forward you only have to single click the reset button Moving to Arduino If you want to change your firmware to Arduino, it's also pretty easy. Start by plugging in your board, and double-clicking reset until you get the green onboard LED(s) - just like with MakeCode Within Arduino IDE, select the matching board, say Circuit Playground Express Select the correct matching Port: © Adafruit Industries https://learn.adafruit.
Create a new simple Blink sketch example: // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin 13 as an output.
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.
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.
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.
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.
CircuitPython Essentials You've gone through the Welcome to CircuitPython guide (https://adafru.it/cpy-welcome). You've already gotten everything setup, and you've gotten CircuitPython running. Great! Now what? CircuitPython Essentials! There are a number of core modules built into CircuitPython and commonly used libraries available. This guide will introduce you to these and show you an example of how to use each one.
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 simply some of the many features you can use. Thing That Are Built In and Work Flow Control All the usual if , elif , else , for , while work just as expected.
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 example shows how to use both a digital input and output. You can use a switch input with pullup resistor (built in) to control a digital output - the built in red LED. Copy and paste the code into code.py using your favorite editor, and save the file to run the demo.
and the onboard red LED will turn on and off. 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 switch.pull = None. Find the pins! The list below shows each board, explains the location of the Digital pin suggested for use as input, and the location of the D13 LED.
Gemma M0 D2 is an alligator-clip-friendly pad labeled both "D2" and "A1", shown connected to the blue wire, and is next to the USB micro port. D13 is located next to the "GND" label on the board, above the "On/Off" switch. Use alligator clips to connect your switch to your Gemma M0! Feather M0 Express and Feather M4 Express D5 is labeled "5" and connected to the blue wire on the board. D13 is labeled "#13" and is located next to the USB micro port.
Metro M0 Express and Metro M4 Express D2 is located near the top left corner, and is connected to the blue wire. D13 is labeled "L" and is located next to the USB micro port. Read the Docs For a more in-depth look at what digitalio can do, check out the DigitalInOut page in Read the Docs (https://adafru.it/C4c). © Adafruit Industries https://learn.adafruit.
CircuitPython Analog In This example shows you how you can read the analog voltage on the A1 pin on your board. Copy and paste the code into code.py using your favorite editor, and save the file to run the demo. # CircuitPython AnalogIn Demo import time import board from analogio import AnalogIn analog_in = AnalogIn(board.A1) def get_voltage(pin): return (pin.value * 3.3) / 65536 while True: print((get_voltage(analog_in),)) time.sleep(0.1) Creating the analog input analog1in = AnalogIn(board.
Changing It Up By default the pins are floating so the voltages will vary. While connected to the serial console, try touching a wire from A1 to the GND pin or 3Vo pin to see the voltage change. You can also add a potentiometer to control the voltage changes. From the potentiometer to the board, connect the left pin to ground, the middle pin to A1, and the right pin to 3V.
Circuit Playground Express A1 is located on the right side of the board. There are multiple ground and 3V pads (pins). Your board has 7 analog pins that can be used for this purpose. For the full list, see the pinout page (https://adafru.it/AM9) on the main guide. Trinket M0 A1 is labeled as 2! It's located between "1~" and "3V" on the same side of the board as the little red LED. Ground is located on the opposite side of the board.
Gemma M0 A1 is located near the top of the board of the board to the left side of the USB Micro port. Ground is on the other side of the USB port from A1. 3V is located to the left side of the battery connector on the bottom of the board. Your board has 3 analog pins. For the full list, see the pinout page (https://adafru.it/AMa) on the main guide. Feather M0 Express and Feather M4 Express A1 is located along the edge opposite the battery connector. There are multiple ground pins.
ItsyBitsy M0 Express and ItsyBitsy M4 Express A1 is located in the middle of the board, near the "A" in "Adafruit". Ground is labled "G" and is located next to "BAT", near the USB Micro port. 3V is found on the opposite side of the USB port from Ground, next to RST. You have 6 analog pins you can use. For a full list, see the pinouts page (https://adafru.it/BMg) on the main guide. Metro M0 Express and Metro M4 Express A1 is located on the same side of the board as the barrel jack.
CircuitPython Analog Out This example shows you how you can set the DAC (true analog output) on pin A0. A0 is the only true analog output on the M0 boards. No other pins do true analog output! Copy and paste the code into code.py using your favorite editor, and save the file. # CircuitPython IO demo - analog output import board from analogio import AnalogOut analog_out = AnalogOut(board.
Check out the Audio Out section of this guide (https://adafru.it/BRj) for examples! Find the pin Use the diagrams below to find the A0 pin marked with a magenta arrow! Circuit Playground Express A0 is located between VOUT and A1 near the battery port. Trinket M0 A0 is labeled "1~" on Trinket! A0 is located between "0" and "2" towards the middle of the board on the same side as the red LED. © Adafruit Industries https://learn.adafruit.
Gemma M0 A0 is located in the middle of the right side of the board next to the On/Off switch. Feather M0 Express A0 is located between GND and A1 on the opposite side of the board from the battery connector, towards the end with the Reset button.
ItsyBitsy M0 Express A0 is located between VHI and A1, near the "A" in "Adafruit", and the pin pad has left and right white parenthesis markings around it. ItsyBitsy M4 Express A0 is located between VHI and A1, and the pin pad has left and right white parenthesis markings around it. Metro M0 Express A0 is between VIN and A1, and is located along the same side of the board as the barrel jack adapter towards the middle of the headers found on that side of the board. © Adafruit Industries https://learn.
Metro M4 Express A0 is between VIN and A1, and is located along the same side of the board as the barrel jack adapter towards the middle of the headers found on that side of the board. On the Metro M4 Express, there are TWO true analog outputs: A0 and A1. © Adafruit Industries https://learn.adafruit.
CircuitPython PWM Your board has pulseio support, which means you can PWM LEDs, control servos, beep piezos, and manage "pulse train" type devices like DHT22 and Infrared. Nearly every pin has PWM support! For example, all ATSAMD21 board have an A0 pin which is 'true' analog out and does not have PWM support. PWM with Fixed Frequency This example will show you how to use PWM to fade the little red LED on your board. Copy and paste the code into code.py using your favorite editor, and save the file.
To use with the Metro M4 Express, ItsyBitsy M4 Express or the Feather M4 Express, you must comment out the piezo = pulseio.PWMOut(board.A2, duty_cycle=0, frequency=440, variable_frequency=True) line and uncomment the piezo = pulseio.PWMOut(board.A1, duty_cycle=0, frequency=440, variable_frequency=True) line. A2 is not a supported PWM pin on the M4 boards! Remember: To "comment out" a line, put a # and a space before it. To "uncomment" a line, remove the # + space from the beginning of the line.
Wire it up Use the diagrams below to help you wire up your piezo. Attach one leg of the piezo to pin A2 on the M0 boards or A1 on the M4 boards, and the other leg to ground. It doesn't matter which leg is connected to which pin. They're interchangeable! Circuit Playground Express Use alligator clips to attach A2 and any one of the GND to different legs of the piezo.
Gemma M0 Use alligator clips to attach A2 and GND to different legs on the piezo. Gemma has PWM available on the following pins: A1, D2, RX, SCL, A2, D0, TX, SDA, L, D13, APA102_MOSI, APA102_SCK. There is NO PWM on: A0, D1. Feather M0 Express Use jumper wires to attach A2 and one of the two GND to different legs of the piezo. Feather M0 Express has PWM on the following pins: A2, A3, A4, SCK, MOSI, MISO, D0, RX, D1, TX, SDA, SCL, D5, D6, D9, D10, D11, D12, D13, NEOPIXEL.
ItsyBitsy M0 Express Use jumper wires to attach A2 and G to different legs of the piezo. ItsyBitsy M0 Express has PWM on the following pins: D0, RX, D1, TX, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11, D12, D13, L, A2, A3, A4, MOSI, MISO, SCK, SCL, SDA, APA102_MOSI, APA102_SCK. There is NO PWM on: A0, A1, A5. ItsyBitsy M4 Express Use jumper wires to attach A1 and G to different legs of the piezo. To use A1, comment out the current pin setup line, and uncomment the line labeled for the M4 boards.
Metro M4 Express Use jumper wires to connect A1 and any one of the GND to different legs on the piezo. To use A1, comment out the current pin setup line, and uncomment the line labeled for the M4 boards. See the details above! Metro M4 Express has PWM on: A1, A5, D0, RX, D1, TX, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11, D12, D13, SDA, SCK, MOSI, MISO There is No PWM on: A0, A2, A3, A4, SCL, AREF, NEOPIXEL, LED_RX, LED_TX.
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 adafruit_motor which manages servos for you quite nicely! adafruit_motor is a library so be sure to grab it from the library bundle if you have not yet (https://adafru.
For Gemma, use jumper wire alligator clips to connect the ground wire to GND, the power wire to VOUT, and the signal wire to A2. For Circuit Playground Express, use jumper wire alligator clips to connect the ground wire to GND, the power wire to VOUT, and the signal wire to A2. For boards like Feather M0 Express, ItsyBitsy M0 Express and Metro M0 Express, connect the ground wire to any GND, the power wire to USB or 5V, and the signal wire to A2. © Adafruit Industries https://learn.adafruit.
For the Metro M4 Express, ItsyBitsy M4 Express and the Feather M4 Express, connect the ground wire to any G or GND, the power wire to USB or 5V, and the signal wire to A1. Servo Code Here's an example that will sweep a servo connected to pin A2 from 0 degrees to 180 degrees and back: import time import board import pulseio from adafruit_motor import servo # create a PWMOut object on Pin A2. pwm = pulseio.PWMOut(board.A2, duty_cycle=2 ** 15, frequency=50) # Create a servo object, my_servo. my_servo = servo.
CircuitPython Cap Touch Every CircuitPython designed M0 board has capacitive touch capabilities. This means each board has at least one pin that works as an input when you touch it! The capacitive touch is done completely in hardware, so no external resistors, capacitors or ICs required. Which is really nice! Capacitive touch is not supported on the M4 Express boards. This example will show you how to use a capacitive touch pin on your board. Copy and paste the code into code.
You may need to reload your code or restart your 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 responses or not enough, reload your code through the serial console or eject the board and tap the reset button! Find the Pin(s) Your board may have more touch capable pins beyond A0.
This example does NOT work for Trinket M0! You must change the pins to use with this board. This example only works with Gemma, Circuit Playground Express, Feather M0 Express, Metro M0 Express and ItsyBitsy M0 Express. Use the list below to find out what pins you can use with your board. Then, try adding them to your code and have fun! Trinket M0 There are three touch capable pins on Trinket: A0, A3, and A4.
Feather M0 Express There are 6 pins on the Feather that have touch capability: A0 - A5. ItsyBitsy M0 Express There are 6 pins on the ItsyBitsy that have touch capability: A0 - A5. Metro M0 Express There are 6 pins on the Metro that have touch capability: A0 - A5. © Adafruit Industries https://learn.adafruit.
Circuit Playground Express Circuit Playground Express has seven touch capable pins! You have A1 - A7 available, in the form of alligatorclip-friendly pads. See the CPX guide Cap Touch section (https://adafru.it/ANC) for more information on using these pads for touch! Remember: A0 does NOT have touch capabilities on CPX. © Adafruit Industries https://learn.adafruit.
CircuitPython Internal RGB LED Every board has a built in RGB LED. You can use CircuitPython to control the color and brightness of this LED. There are two different types of internal RGB LEDs: DotStar (https://adafru.it/kDg) and NeoPixel (https://adafru.it/Bej). This section covers both and explains which boards have which LED. The first example will show you how to change the color and brightness of the internal RGB LED. Copy and paste the code into code.py using your favorite editor, and save the file.
Trinket M0, Gemma M0, ItsyBitsy M0 Express, and ItsyBitsy M4 Express each have an onboard Dotstar LED, so no changes are needed to the initial version of the example. Feather M0 Express, Feather M4 Express, Metro M0 Express, Metro M4 Express, and Circuit Playground Express each have an onboard NeoPixel LED, so you must comment out import adafruit_dotstar and led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) , and uncomment import neopixel and led = neopixel.NeoPixel(board.NEOPIXEL, 1) .
Try changing the numbers in the tuples to change your LED to any color of the rainbow. Or, you can add more lines with different color tuples to add more colors to the sequence. Always add the time.sleep() , but try changing the amount of time to create different cycle animations! Making Rainbows (Because Who Doesn't Love 'Em!) Coding a rainbow effect involves a little math and a helper function called wheel . For details about how wheel works, see this explanation here (https://adafru.
The last example shows how to do a rainbow animation on the internal RGB LED. Copy and paste the code into code.py using your favorite editor, and save the file. Remember to comment and uncomment the right lines for the board you're using, as explained above (https://adafru.it/Bel). import time import board # For Trinket M0, Gemma M0, ItsyBitsy M0 Express and ItsyBitsy M4 Express import adafruit_dotstar led = adafruit_dotstar.DotStar(board.APA102_SCK, board.
led = neopixel.NeoPixel(board.NEOPIXEL, 1) to 10 so it reads: led = neopixel.NeoPixel(board.NEOPIXEL, 10) . This tells the code to look for 10 LEDs instead of only 1. Now save the code and watch the rainbow go! You can make the same 1 to 10 change to the previous examples as well, and use led.fill to light up all the LEDs in the colors you chose! For more details, check out the NeoPixel section of the CPX guide (https://adafru.it/Bem)! © Adafruit Industries https://learn.adafruit.
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 NeoPixel LEDs with brightness control (set brightness=1.0 in object creation) and 1000 LEDs without. That's because to adjust the brightness we have to dynamically recreate the data-stream each write.
If the power to the NeoPixels is greater than 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. Do not use the VIN pin directly on Metro M0 Express or Metro M4 Express! The voltage can reach 9V and this can destroy your NeoPixels! Note that the wire ordering on your NeoPixel strip or shape may not exactly match the diagram above.
time.sleep(wait) pixels.show() time.sleep(0.5) def rainbow_cycle(wait): for j in range(255): for i in range(num_pixels): rc_index = (i * 256 // num_pixels) + j pixels[i] = wheel(rc_index & 255) pixels.show() time.sleep(wait) RED = (255, 0, 0) YELLOW = (255, 150, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255) while True: pixels.fill(RED) pixels.show() # Increase or decrease to change the speed of the solid color change. time.sleep(1) pixels.fill(GREEN) pixels.
By default, auto_write=True , meaning any changes you make to your pixels will be sent automatically. Since True is the default, if you use that setting, you don't need to include it in your LED object at all. We've chosen to set auto_write=False . If you set auto_write=False , you must include pixels.show() each time you'd like to send data to your pixels.
pixel_pin = board.A1 num_pixels = 8 pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.3, auto_write=False, pixel_order=(1, 0, 2, 3)) 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.
color_chase(CYAN, 0.1) color_chase(BLUE, 0.1) color_chase(PURPLE, 0.1) rainbow_cycle(0) # Increase the number to slow down the rainbow Read the Docs For a more in depth look at what neopixel can do, check out NeoPixel on Read the Docs (https://adafru.it/C5m). © Adafruit Industries https://learn.adafruit.
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. 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).
Note that the wire ordering on your DotStar strip or shape may not exactly match the diagram above. Check the markings to verify which pin is DIN, CIN, 5V and GND The Code This example includes multiple visual effects. Copy and paste the code into code.py using your favorite editor, and save the file. # CircuitPython demo - Dotstar import time import adafruit_dotstar import board num_pixels = 30 pixels = adafruit_dotstar.DotStar(board.A1, board.A2, num_pixels, brightness=0.
time.sleep(wait) pixels[::2] = [YELLOW] * (num_pixels // 2) pixels.show() time.sleep(wait) pixels[1::2] = [GREEN] * (num_pixels // 2) pixels.show() time.sleep(wait) pixels[::2] = [TEAL] * (num_pixels // 2) pixels.show() time.sleep(wait) pixels[1::2] = [CYAN] * (num_pixels // 2) pixels.show() time.sleep(wait) pixels[::2] = [BLUE] * (num_pixels // 2) pixels.show() time.sleep(wait) pixels[1::2] = [PURPLE] * (num_pixels // 2) pixels.show() time.sleep(wait) pixels[::2] = [MAGENTA] * (num_pixels // 2) pixels.
ORANGE = (255, 40, 0) GREEN = (0, 255, 0) TEAL = (0, 255, 120) CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255) MAGENTA = (255, 0, 20) WHITE = (255, 255, 255) while True: # Change this number to change how long it stays on each solid color. color_fill(RED, 0.5) color_fill(YELLOW, 0.5) color_fill(ORANGE, 0.5) color_fill(GREEN, 0.5) color_fill(TEAL, 0.5) color_fill(CYAN, 0.5) color_fill(BLUE, 0.5) color_fill(PURPLE, 0.5) color_fill(MAGENTA, 0.5) color_fill(WHITE, 0.
your pixels. This makes your code more complicated, but it can make your LED animations faster! DotStar Helpers We've included a few helper functions to create the super fun visual effects found in this code. First is wheel() which we just learned with the Internal RGB LED (https://adafru.it/Bel). Then we have color_fill() which requires you to provide a color and the length of time you'd like it to be displayed.
import board import busio def is_hardware_spi(clock_pin, data_pin): try: p = busio.SPI(clock_pin, data_pin) p.deinit() return True except ValueError: return False # Provide the two pins you intend to use. if is_hardware_spi(board.A1, board.A2): print("This pin combination is hardware SPI!") else: print("This pin combination isn't hardware SPI.") Read the Docs For a more in depth look at what dotstar can do, check out DotStar on Read the Docs (https://adafru.it/C4d). © Adafruit Industries https://learn.
CircuitPython UART Serial 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 GPSs, some sensors, or other microcontrollers! This quick-start example shows how you can create a UART device for communicating with hardware serial devices. To use this example, you'll need something to generate the UART data. We've used a GPS! Note that the GPS will give you UART data without getting a fix on your location.
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 Your results will look something like this: For more information about the data you're reading and the Ultimate GPS, check out the Ultimate GPS guide: https://learn.adafruit.com/adafruit-ultimate-gps Wire It Up You'll need a couple of things to connect the GPS to your board.
Check out the list below for a diagram of your specific board! Watch out! A common mixup with UART serial is that RX on one board connects to TX on the other! However, sometimes boards have RX labeled TX and vice versa. So, you'll want to start with RX connected to TX, but if that doesn't work, try the other way around! Circuit Playground Express Connect 3.3v on your CPX to 3.3v on your GPS. Connect GND on your CPX to GND on your GPS. Connect RX/A6 on your CPX to TX on your GPS.
Gemma M0 Connect 3vo on the Gemma to 3.3v on the GPS. Connect GND on the Gemma to GND on the GPS. Connect A1/D2 on the Gemma to TX on the GPS. Connect A2/D0 on the Gemma to RX on the GPS. Feather M0 Express and Feather M4 Express Connect USB on the Feather to VIN on the GPS. Connect GND on the Feather to GND on the GPS. Connect RX on the Feather to TX on the GPS. Connect TX on the Feather to RX on the GPS. © Adafruit Industries https://learn.adafruit.
ItsyBitsy M0 Express and ItsyBitsy M4 Express Connect USB on the ItsyBitsy to VIN on the GPS Connect G on the ItsyBitsy to GND on the GPS. Connect RX/0 on the ItsyBitsy to TX on the GPS. Connect TX/1 on the ItsyBitsy to RX on the GPS. Metro M0 Express and Metro M4 Express Connect 5V on the Metro to VIN on the GPS. Connect GND on the Metro to GND on the GPS. Connect RX/D0 on the Metro to TX on the GPS. Connect TX/D1 on the Metro to RX on the GPS.
import board import busio from microcontroller import Pin def is_hardware_uart(tx, rx): try: p = busio.UART(tx, rx) p.deinit() return True except ValueError: return False def get_unique_pins(): exclude = ['NEOPIXEL', 'APA102_MOSI', 'APA102_SCK'] pins = [pin for pin in [ getattr(board, p) for p in dir(board) if p not in exclude] if isinstance(pin, Pin)] unique = [] for p in pins: if p not in unique: unique.
>>> import board,busio >>> i2c = busio.I2C(board.SCL, board.SDA) >>> uart = busio.UART(board.TX, board.RX) Traceback (most recent call last): File "", line 1, in ValueError: Invalid pins © Adafruit Industries https://learn.adafruit.
CircuitPython I2C I2C is a 2-wire protocol for communicating with simple sensors and devices, meaning it uses two connections for transmitting and receiving data. There are many I2C devices available and they're really easy to use with CircuitPython. We have libraries available for many I2C devices in the library bundle (https://adafru.it/uap).
Circuit Playground Express Connect 3.3v on your CPX to 3.3v on your TSL2561. Connect GND on your CPX to GND on your TSL2561. Connect SCL/A4 on your CPX to SCL on your TSL2561. Connect SDL/A5 on your CPX to SDA on your TSL2561. Trinket M0 Connect USB on the Trinket to VIN on the TSL2561. Connect Gnd on the Trinket to GND on the TSL2561. Connect D2 on the Trinket to SCL on the TSL2561. Connect D0 on the Trinket to SDA on the TSL2561. Gemma M0 Connect 3vo on the Gemma to 3V on the TSL2561.
Feather M0 Express and Feather M4 Express Connect USB on the Feather to VIN on the TSL2561. Connect GND on the Feather to GND on the TSL2561. Connect SCL on the Feather to SCL on the TSL2561. Connect SDA on the Feather to SDA on the TSL2561. ItsyBitsy M0 Express and ItsyBitsy M4 Express Connect USB on the ItsyBitsy to VIN on the TSL2561 Connect G on the ItsyBitsy to GND on the TSL2561. Connect SCL on the ItsyBitsy to SCL on the TSL2561. Connect SDA on the ItsyBitsy to SDA on the TSL2561.
Metro M0 Express and Metro M4 Express Connect 5V on the Metro to VIN on the TSL2561. Connect GND on the Metro to GND on the TSL2561. Connect SCL on the Metro to SCL on the TSL2561. Connect SDA on the Metro to SDA on the TSL2561. Find Your Sensor The first thing you'll want to do after getting the sensor wired up, is make sure it's wired correctly. We're going to do an I2C scan to see if the board is detected, and if it is, print out its I2C address. Copy and paste the code into code.
i2c.scan()] . Open the serial console to see the results! The code prints out an array of addresses. We've connected the TSL2561 which has a 7-bit I2C address of 0x39. The result for this sensor is I2C addresses found: ['0x39'] . If no addresses are returned, refer back to the wiring diagrams to make sure you've wired up your sensor correctly. I2C Sensor Data Now we know for certain that our sensor is connected and ready to go.
Where's my I2C? On the SAMD21, we have the flexibility of using a wide range of pins for I2C. Some chips, like the ESP8266 can use any pins for I2C, using bitbangio. There's some other chips that may have fixed I2C pin. The good news is you can use many but not all pins. Given the large number of SAMD boards we have, its impossible to guarantee anything other than the labeled 'SDA' and 'SCL'.
import board import busio from microcontroller import Pin def is_hardware_I2C(scl, sda): try: p = busio.I2C(scl, sda) p.deinit() return True except ValueError: return False except RuntimeError: return True def get_unique_pins(): exclude = ['NEOPIXEL', 'APA102_MOSI', 'APA102_SCK'] pins = [pin for pin in [ getattr(board, p) for p in dir(board) if p not in exclude] if isinstance(pin, Pin)] unique = [] for p in pins: if p not in unique: unique.
CircuitPython HID Keyboard and Mouse One of the things we baked into CircuitPython is 'HID' (Human Interface Device) control - that means keyboard and mouse capabilities. This means your CircuitPython board can act like a keyboard device and press key commands, or a mouse and have it move the mouse pointer around and press buttons.
while True: # Check each pin for key_pin in key_pin_array: if not key_pin.value: # Is it grounded? i = key_pin_array.index(key_pin) print("Pin #%d is grounded." % i) # Turn on the red LED led.value = True while not key_pin.value: pass # Wait for it to be ungrounded! # "Type" the Keycode or string key = keys_pressed[i] # Get the corresponding Keycode or string if isinstance(key, str): # If it's a string... keyboard_layout.write(key) # ...Print the string else: # If it's not a string... keyboard.
submit a GitHub pull request!). The time.sleep(1) avoids an error that can happen if the program gets run as soon as the board gets plugged in, before the host computer finishes connecting to the board. Then we take the pins we chose above, and create the pin objects, set the direction and give them each a pullup. Then we apply the pin objects to key_pin_array so we can use them later. Next we set up the little red LED to so we can use it as a status light.
def steps(axis): """ Maps the potentiometer voltage range to 0-20 """ return round((axis - pot_min) / step) while True: x = get_voltage(x_axis) y = get_voltage(y_axis) if select.value is False: mouse.click(Mouse.LEFT_BUTTON) time.sleep(0.2) # Debounce delay if steps(x) > 11.0: # print(steps(x)) mouse.move(x=1) if steps(x) < 9.0: # print(steps(x)) mouse.move(x=-1) if steps(x) > 19.0: # print(steps(x)) mouse.move(x=8) if steps(x) < 1.0: # print(steps(x)) mouse.move(x=-8) if steps(y) > 11.
To use this demo, simply move the joystick around. The mouse will move slowly if you move the joystick a little off center, and more quickly if you move it as far as it goes. Press down on the joystick to click the mouse. Awesome! Now let's take a look at the code. Create the Objects and Variables First we create the mouse object. Next, we set x_axis and y_axis to pins A0 and A1 . Then we set select to A2 , set it as input and give it a pullup. The x and y axis on the joystick act like 2 potentiometers.
Next, we check to see when the state of the select button is False . It defaults to True when it is not pressed, so if the state is False , the button has been pressed. When it's pressed, it sends the command to click the left mouse button. The time.sleep(0.2) prevents it from reading multiple clicks when you've only clicked once. Then we use the steps() function to set our mouse movement. There are two sets of two if statements for each axis.
CircuitPython CPU Temp There is a CPU temperature sensor built into every ATSAMD21 chip. CircuitPython makes it really simple to read the data from this sensor. This works on the M0, M0 Express and Circuit Playground Express boards, because it's built into the microcontroller used for these boards. It does not work on the ESP8266 as this uses a different chip. The data is read using two simple commands. We're going to enter them in the REPL. Plug in your board, connect to the serial console (https://adafru.
CircuitPython Storage CircuitPython boards show up as as USB drive, allowing you to edit code directly on the board. You've been doing this for a while. By now, maybe you've wondered, "Can I write data from CircuitPython to the storage drive to act as a datalogger?" The answer is yes! However, it is a little tricky. You need to add some special code to boot.py, not just code.py.
import time import board import digitalio import microcontroller 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.
boot.py only runs on first boot of the device, not if you re-load the serial console with ctrl+D or if you save a file. You must EJECT the USB drive, then physically press the reset button! Once you copied the files to your board, eject it and unplug it from your computer. If you're using your Circuit Playground Express, all you have to do is make sure the switch is to the right. Otherwise, use alligator clips or jumper wires to connect the chosen pin to ground.
This file gets updated once per second, but you won't see data come in live. Instead, when you're ready to grab the data, eject and unplug your board. For CPX, move the switch to the left, otherwise remove the wire connecting the pin to ground. 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: CPU Temperature Logging with CircuitPython. (https://adafru.
CircuitPython Expectations As we continue to develop CircuitPython and create new releases, we will stop supporting older releases. If you are running CircuitPython 2.x, you need to update to 3.x. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update to CircuitPython 3.x and then download the 3.x bundle.
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. 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'. Modules audioio and bitbangio are not included. For that support, check out the Circuit Playground Express or other Express boards.
Frequently Asked Questions These are some of the common questions regarding CircuitPython and CircuitPython microcontrollers. What is a MemoryError ? Memory allocation errors happen when you're trying to store too much on the board. The CircuitPython microcontroller boards have a limited amount of memory available. You can have about 250 lines of code on the M0 Express boards.
Does Feather M0 support WINC1500? No, WINC1500 will not fit into the M0 flash space. Can AVRs such as ATmega328 or ATmega2560 run CircuitPython? No. Commonly Used Acronyms CP or CPy = CircuitPython (https://adafru.it/cpy-welcome) CPC = Circuit Playground Classic (https://adafru.it/ncE) CPX = Circuit Playground Express (https://adafru.it/wpF) © Adafruit Industries https://learn.adafruit.
MakeCode Microsoft MakeCode has been augmented to support more than the Adafruit Circuit Playground Express. Using maker.makecode.com (https://adafru.it/C9N), you can use other Adafruit microcontrollers, breadboards and other components! See the following pages for more information. © Adafruit Industries https://learn.adafruit.
What is MakeCode Maker? MakeCode Maker, https://maker.makecode.com, is a web-based code editor for physical computing. It provides a block editor, similar to Scratch or Code.org, and also a JavaScript editor for more advanced users.
Adafruit METRO M0 Express - designed for CircuitPython $24.95 IN STOCK ADD TO CART Adafruit Feather M0 Express - Designed for CircuitPython $19.95 IN STOCK ADD TO CART Your browser does not support the video tag. Adafruit GEMMA M0 - Miniature wearable electronic platform $9.95 IN STOCK ADD TO CART Adafruit Trinket M0 - for use with CircuitPython & Arduino IDE $8.95 IN STOCK ADD TO CART © Adafruit Industries https://learn.adafruit.
© Adafruit Industries https://learn.adafruit.
Editing Blocks The block editor is the easiest way to get started with MakeCode Maker. You can drag and drop blocks from the category list. Each time you make a change to the blocks, the simulator will automatically restart and run the code. You can test your program in the browser! The simulator will also generate the wiring for your breadboard for simple programs. On the maker home screen, click on "New Project", then select which board you want to use (you can change board later too).
© Adafruit Industries https://learn.adafruit.
Editing JavaScript MakeCode allows you to author your programs in a flavor of JavaScript optimized for micro-controllers. The code editor comes with error highlighting, auto-completion and other goodies. It is the same code editor that powers Visual Studio Code. Blocks to JavaScript Click on the "Blocks / JavaScript" toggle on top of the editor to enter the JavaScript mode. Your blocks will automatically be converted to JavaScript. © Adafruit Industries https://learn.adafruit.
Downloading and Flashing Getting your code into your device is very easy with MakeCode. You do not need to install any software on your machine and the process takes two steps: Step 1: Connect your board via USB Step 2: Compile and Download the .uf2 file into your board drive We are going to go through these two steps in detail. Step 1: Connect your board via USB Connect your board to your computer via a USB cable. You should see a MAKECODE drive appear in your file explorer/finder.
If you receive a "we could not run this project" error, please check over your code for errors. Step 3: Download and flash your code If your board is working in the simulator, it's time to download it to your actual board! Click the Download button. It will generate a .uf2 file and download it to your computer. UF2 (https://adafru.it/vPE) is a file format designed by Microsoft to flash microcontrollers over USB.
Saving and Sharing Extracting your code from the board The .uf2 file you created by clicking on the Compile button in MakeCode also contains the source code of your program! You can open this file in MakeCode by dragging and dropping it into the browser to edit it. You can also find the current .uf2 file running on the MAKECODE or boardnameBOOT drive. Sharing You can share your code by clicking on the share button. After confirmation, MakeCode will create a short unique URL for your code.
Custom Extensions MakeCode allows to package and share code as Extensions. Extensions are stored as GitHub repositories and can be edited directly from the MakeCode editor. Account setup First, you need a GitHub account if you don't have one yet. GitHub is the largest host of source code in the world, with over 30 million users. Once you have your account, you'll need to tie the MakeCode web app to your account. To do that, open any project in https://maker.makecode.
Commit and push Once you have your repo set up, edit files as usual. Whenever you get to a stable state, or just every now and then to keep history and insure against losing your work, push the changes to GitHub. This is done with a little GitHub sync button on top of the Explorer. The button will check if there are any pending changes to check in. If there are, it will create a commit, pull the latest changes from GitHub, merge or fast-forward the commit if needed, and push the results to GitHub.
There is also another button next to the GitHub sync - you can use it to add new files to the project. This is mostly to help keep the project organized. For our TypeScript compiler it doesn't matter if you use one big file or a bunch of smaller ones. Conflicts It's possible that multiple people are editing the same package at the same time causing edit conflicts. This is similar to the situation where the same person edits the package using several computers, browsers, or web sites.
© Adafruit Industries https://learn.adafruit.
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 SAMD21 (M0) and SAMD51 (M4) 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.
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... © Adafruit Industries https://learn.adafruit.
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.
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.
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.
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 (https://adafru.it/vQb). You can download the latest builds here. (https://adafru.it/s1B) The mingw32 version is for Windows, apple-darwin for Mac OSX and various linux options for Linux.
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. In general, you shouldn't have to update the bootloader! If you do think you're having bootloader related issues, please post in the forums or discord.
https://adafru.it/Bml https://adafru.it/Bml https://adafru.it/Bml https://adafru.it/Bml https://adafru.it/Bmo https://adafru.it/Bmo 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 © Adafruit Industries https://learn.adafruit.
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 (https://adafru.it/vZb). Make sure that your program was compiled to start at 0x2000 (8k) for M0 boards or 0x4000 (16kB) for M4 boards. The bootloader takes up the first 8kB (M0) or 16kB (M4). CircuitPython's linker script (https://adafru.it/CXh) is an example on how to do that. Once you have a .
Downloads https://adafru.it/B48 https://adafru.it/B48 Datasheets ATSAMD21 Datasheet (https://adafru.it/kUf) (the main chip on the Feather M0) Fritzing object in the Adafruit Fritzing Library (https://adafru.it/aP3) EagleCAD PCB files in GitHub (https://adafru.it/vfS) https://adafru.it/z3F https://adafru.it/z3F Note AREF in the diagram should be marked PA03 not PA02 Firmware 'Classic' Feather M0 Bootloader - You'll need to program it in using an ST-Link, JLink or other SWD-capable programmer.
© Adafruit Industries Last Updated: 2018-12-13 04:59:07 PM UTC Page 199 of 199