Adafruit Metro M4 Express featuring ATSAMD51 Created by lady ada Last updated on 2019-09-11 10:25:53 PM UTC
Overview Are you ready? Really ready? Cause here comes the fastest, most powerful Metro ever. The Adafruit Metro M4 featuring the Microchip ATSAMD51. This Metro is like a bullet train, with it's 120MHz Cortex M4 with floating point support. Your code will zig and zag and zoom, and with a bunch of extra peripherals for support, this will for sure be your favorite new chipset.
know and love. This Metro is the same size as the others, and is compatible with all our shields. It's got analog pins where you expect, and SPI/UART/I2C hardware support in the same spot as the Metro 328 and M0. But! It's powered with an ATSAMD51J19: Cortex M4 core running at 120 MHz Hardware DSP and floating point support 512 KB flash, 192 KB RAM 32-bit, 3.
RGB NeoPixel that can be used for any purpose. 2 MB QSPI Flash storage chip is included on board. You can use the SPI Flash storage like a very tiny hard drive. When used in Circuit Python, the 2 MB flash acts as storage for all your scripts, libraries and files. When used in Arduino, you can read/write files to it, like a little datalogger or SD card, and then with our helper program, access the files over USB. Easy reprogramming, comes pre-loaded with the UF2 bootloader (https://adafru.
Pinouts The Metro M4 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 Connections There's a lot of ways to power the Metro M4 Express, and a lot of ways to get power out as well. © Adafruit Industries https://learn.adafruit.
There are two primary ways to power the Metro: Through the Micro USB port up at the top left Through the DC jack at the bottom left The MicroUSB jack provides 5V at 500mA or so, there is a fuse that will shut off temporarily when more than 1000mA is drawn, this is to protect a computer USB port. You can plug this into any computer or USB charger with a USB cable. You can draw up to 500mA between the Vin, 5V and 3.3V supplies (combined). The DC Jack is a 5.5mm/2.
Top Row #0 / RX - GPIO #0, also receive (input) pin for Serial1 (hardware UART) #1 / TX - GPIO #1, also transmit (output) pin for Serial1 #2 through #12 - These are general purpose GPIO. If there's a dot next to the pad it can act as a PWM output. #13 - GPIO #13 and is connected to the red LED marked L next to the USB jack. Also PWM output. SDA - the I2C (Wire) data pin. There's no pull up on this pin by default so when using with I2C, you may need a 2.2K-10K pullup. SCL - the I2C (Wire) clock pin.
thought this was neat so we made sure all those pins were available. Here are the PCC pins (left) and the Metro M4 pins it's mapped to. Unlike other peripherals, you cannot mux these signals to other pins! DEN1: MOSI DEN2: SCK CLK: MISO D0: D13 D1: D12 D2: D10 D3: D11 D4: D9 D5: D8 D6: D1 D7: D0 D8: D5 D9: D6 QSPI Flash and NeoPixel As part of the 'Express' series of boards, the Metro M4 Express is designed for use with CircuitPython.
The QSPI Flash is connected to 6 pins that are not brought out on the GPIO pads. This way you don't have to worry about the SPI flash colliding with other devices on the main SPI connection. QSPI is neat because it allows you to have 4 data in/out lines instead of just SPI's single line in and single line out. This means that QSPI is at least 4 times faster.
SEGGER J-Link EDU - JTAG/SWD Debugger $69.95 IN STOCK Add To Cart SEGGER J-Link BASE - JTAG/SWD Debugger $399.95 IN STOCK Add To Cart SEGGER J-Link EDU Mini - JTAG/SWD Debugger $19.95 IN STOCK Add To Cart You'll need an adapter and cable to convert the 2x10 JTAG cable to SWD © Adafruit Industries https://learn.adafruit.
10-pin 2x5 Socket-Socket 1.27mm IDC (SWD) Cable - 150mm long $2.95 IN STOCK Add To Cart JTAG (2x10 2.54mm) to SWD (2x5 1.27mm) Cable Adapter Board $4.95 IN STOCK Add To Cart If you want to use the J-Link with Segger Ozone, check out this handy informative post on the forums (https://adafru.it/Cuk) © 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.
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.
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.
For example, bossac -p=/dev/cu.usbmodem14301 -e -w -v -R adafruit-circuitpython-feather_m0_express-3.0.0.bin Using bossac Versions 1.9 or Later For M0 boards, which have an 8kB bootloader, you must specify -offset=0x2000 , for example: bossac -p=/dev/cu.usbmodem14301 -e -w -v -R --offset=0x2000 adafruit-circuitpython-feather_m0_express-3.0.0.bin For M4 boards, which have a 16kB bootloader, you must specify -offset=0x4000 , for example: bossac -p=/dev/cu.
UF2 Bootloader v2.0.0-adafruit.5 SFHWRO Model: Metro M0 Board-ID: SAMD21G18A-Metro-v0 Lastly, reload your code from Arduino or MakeCode or flash the latest CircuitPython core (https://adafru.it/Em8). Below are the latest updaters for various boards. The latest versions can always be found here (https://adafru.it/Bmg). Look for the update-bootloader... files, not the bootloader... files. https://adafru.it/ECV https://adafru.it/ECV https://adafru.it/ECW https://adafru.it/ECW https://adafru.
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 © Adafruit Industries https://learn.adafruit.
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 .bin file, you simply need to run the Python conversion script over it.
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.
Install Adafruit SAMD Next you can install the Adafruit SAMD package to add the board file definitions Make sure you have Type All selected to the left of the Filter your search... box You can type Adafruit SAMD in the top search bar, then when you see the entry, click Install 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.
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/EC0 https://adafru.it/EC0 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.
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.
Adapting Sketches to M0 & M4 The ATSAMD21 and 51 are very nice little chips, but fairly new as Arduino-compatible cores go. Most sketches & libraries will work but here’s a collection of things we noticed. The notes below cover a range of Adafruit M0 and M4 boards, but not every rule will apply to every board (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.
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 ...
Pretty-Printing out registers 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) M4 Performance Options As of version 1.4.0 of the Adafruit SAMD Boards package in the Arduino Boards Manager, some options are available to wring extra performance out of M4-based devices.
There’s usually more than one way to solve a problem, some more resource-intensive than others. Since Arduino got its start on resource-limited AVR microcontrollers, the C++ compiler has always aimed for the smallest compiled program size. The “Optimize” menu gives some choices for the compiler to take different and often faster approaches, at the expense of slightly larger program size…with the huge flash memory capacity of M4 devices, that’s rarely a problem now.
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 CircuitPython (https://adafru.it/tB7) is a derivative of MicroPython (https://adafru.it/BeZ) designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the CIRCUITPY drive to iterate. Set up CircuitPython Quick Start! Follow this quick step-by-step for super-fast Python power :) https://adafru.it/Emf https://adafru.
If double-clicking doesn't work the first time, try again. Sometimes it can take a few tries to get the rhythm right! You will see a new disk drive appear called METROM4BOOT. Drag the adafruit_circuitpython_etc.uf2 file to METROM4BOOT. The LED will flash. Then, the METROm4BOOT drive will disappear and a new disk drive called CIRCUITPY will appear. That's it, you're done! :) © Adafruit Industries https://learn.adafruit.
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.
Downloads Files ATSAMD51J19 Product page w/datasheets (https://adafru.it/Bf8) (the main chip on the Metro M4) Fritzing object in the Adafruit Fritzing Library (https://adafru.it/aP3) EagleCAD files on GitHub (https://adafru.it/BBh) UF2 Bootloader updater (only needed for Metro M4's shipped before May 8, 2018) (https://adafru.it/B3H) Schematic & Fabrication Print © Adafruit Industries https://learn.adafruit.
© 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 serial console is built right in so you get immediate feedback from your board's serial output! Mu is our recommended editor - please use it (unless you are an experienced coder with a favorite editor already!) Download and Install Mu Download Mu from https://codewith.mu (https://adafru.it/Be6).
Mu attempts to auto-detect your board, so please plug in your CircuitPython device and make sure it shows up as a CIRCUITPY drive before starting Mu Now you're ready to code! Lets keep going.... © 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.
vim (https://adafru.it/ek9) / vi safely writes all changes. But set up vim to not write swapfiles (https://adafru.it/ELO) (.swp files: temporary records of your edits) to CIRCUITPY. Run vim with vim -n , set the no swapfile option, or set the directory option to write swapfiles elsewhere. Otherwise the swapfile writes trigger restarts of your program. The PyCharm IDE (https://adafru.it/xNC) is safe if "Safe Write" is turned on in Settings->System Settings>Synchronization (true by default).
Back to Editing Code... Now! Let's try editing the program you added to your board. Open your code.py file into your editor. We'll make a simple change. Change the first 0.5 to 0.1 . The code should look like this: import board import digitalio import time led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT while True: led.value = True time.sleep(0.1) led.value = False time.sleep(0.5) Leave the rest of the code as-is. Save your file.
Here is the original code again: 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.
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.
More Changes We don't have to stop there! Let's keep going. Change the second 0.5 to 0.1 so it looks like this: while True: led.value = True time.sleep(0.1) led.value = False time.sleep(0.1) Now it blinks really fast! You decreased the both time that the code leaves the LED on and off! Now try increasing both of the 0.1 to 1 . Your LED will blink much more slowly because you've increased the amount of time that the LED is turned on and off.
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. Setting Permissions on Linux On Linux, if you see an error box something like the one below when you press the Serial button, you need to add yourself to a user group to have permission to connect to the serial console. On Ubuntu and Debian, add yourself to the dialout group by doing: sudo adduser $USER dialout After running the command above, reboot your machine to gain access to the group.
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 board reboots. Then you'll see your new change! The Traceback (most recent call last): is telling you the last thing your board was doing before you saved your file. This is normal behavior and will happen every time the board resets. This is really handy for troubleshooting. Let's introduce an error so 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.
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. Visit https://circuitpython.org/downloads to download the latest version of CircuitPython for your board. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update CircuitPython and then visit https://circuitpython.org/libraries to download the latest Library Bundle.
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 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.
Now open the lib folder. When you open the folder, you'll see a large number of mpy files and folders Example Files All example files from each library are now included in the bundles, as well as an examples-only bundle. These are included for two main reasons: Allow for quick testing of devices. Provide an example base of code, that is easily built upon for individualized purposes. Copying Libraries to Your Board First you'll want to create a lib folder on your CIRCUITPY drive.
This demonstration will only return an error if you do not have the required library loaded into the lib folder on your CIRCUITPY drive. Let's use a modified version of the 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 .
Library Install on Non-Express Boards 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.
Frequently Asked Questions These are some of the common questions regarding CircuitPython and CircuitPython microcontrollers. As we continue to develop CircuitPython and create new releases, we will stop supporting older releases. Visit https://circuitpython.org/downloads to download the latest version of CircuitPython for your board. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update CircuitPython and then visit https://circuitpython.
How do I connect to the Internet with CircuitPython? If you'd like to add WiFi support, check out our guide on ESP32/ESP8266 as a co-processor. © Adafruit Industries https://learn.adafruit.
Is there asyncio support in CircuitPython We do not have asyncio support in CircuitPython at this time © Adafruit Industries https://learn.adafruit.
My RGB NeoPixel/DotStar LED is blinking funny colors - what does it mean? The status LED can tell you what's going on with your CircuitPython board. Read more here for what the colors mean! © Adafruit Industries https://learn.adafruit.
What is a MemoryError ? Memory allocation errors happen when you're trying to store too much on the board. The CircuitPython microcontroller boards have a limited amount of memory available. You can have about 250 lines of code on the M0 Express boards. If you try to import too many libraries, a combination of large libraries, or run a program with too many lines of code, your code will fail to run and you will receive a MemoryError in the serial console (REPL).
It can because the memory gets fragmented differently depending on allocation order and the size of objects. Loading .mpy files uses less memory so its recommended to do that for files you aren't editing. How can I create my own .mpy files? You can make your own .mpy versions of files with mpy-cross . You can download the CircuitPython 2.x version of mpy-cross for your operating system from the CircuitPython Releases page (https://adafru.it/tBa) under the latest 2.x version.
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.
Advanced Serial Console on Windows Windows 7 Driver If you're using Windows 7, use the link below to download the driver package. You will not need to install drivers on Mac, Linux or Windows 10. https://adafru.it/AB0 https://adafru.it/AB0 What's the COM? First, you'll want to find out which serial port your board is using. When you plug your board in to USB on your computer, it connects to a serial port. The port is like a door through which your board can communicate with your computer using USB.
Sometimes the item will refer to the name of the board. Other times it may be called something like USB Serial Device, as seen in the image above. Either way, there is a new (COM#) following the name. This is the port your board is using. Install Putty If you're using Windows, you'll need to download a terminal program. We're going to use PuTTY. The first thing to do is download the latest version of PuTTY (https://adafru.it/Bf1). You'll want to download the Windows installer file.
Once your settings are entered, you're ready to connect to the serial console. Click "Open" at the bottom of the window. A new window will open. If no code is running, the window will either be blank or will look like the window above. Now you're ready to see the results of your code. Great job! You've connected to the serial console! © Adafruit Industries https://learn.adafruit.
Advanced Serial Console on Mac and Linux Connecting to the serial console on Mac and Linux uses essentially the same process. Neither operating system needs drivers installed. On MacOSX, Terminal comes installed. On Linux, there are a variety such as gnome-terminal (called Terminal) or Konsole on KDE. What's the Port? First you'll want to find out which serial port your board is using. When you plug your board in to USB on your computer, it connects to a serial port.
Now, plug your board. Using Mac, type: ls /dev/tty.* This will show you the current serial connections, which will now include your board. Using Mac, a new listing has appeared called /dev/tty.usbmodem141441 . The tty.usbmodem141441 part of this listing is the name the example board is using. Yours will be called something similar. Using Linux, type: ls /dev/ttyACM* This will show you the current serial connections, which will now include your board. © Adafruit Industries https://learn.adafruit.
Using Linux, a new listing has appeared called /dev/ttyACM0 . The ttyACM0 part of this listing is the name the example board is using. Yours will be called something similar. Connect with screen Now that you know the name your board is using, you're ready connect to the serial console. We're going to use a command called screen . The screen command is included with MacOS. Linux users may need to install it using their package manager. To connect to the serial console, use Terminal.
Press enter to run the command. It will open in the same window. If no code is running, the window will be blank. Otherwise, you'll see the output of your code. Great job! You've connected to the serial console! Permissions on Linux If you try to run screen and it doesn't work, then you may be running into an issue with permissions. Linux keeps track of users and groups and what they are allowed to do and not do, like access the hardware associated with the serial connection for running screen .
The second way is to add yourself to the group associated with the hardware. To figure out what that group is, use the command ls -l as shown below. The group name is circled in red. Then use the command adduser to add yourself to that group. You need elevated privileges to do this, so you'll need to use sudo . In the example below, the group is adm and the user is ackbar. After you add yourself to the group, you'll need to logout and log back in, or in some cases, reboot your machine.
The examples above use screen , but you can also use other programs, such as putty or picocom , if you prefer. © 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.
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. Visit https://circuitpython.org/downloads to download the latest version of CircuitPython for your board. You must download the CircuitPython Library Bundle that matches your version of CircuitPython.
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.3.0.
Windows Explorer Locks Up When Accessing boardnameBOOT Drive On Windows, several third-party programs we know of can cause issues. The symptom is that you try to access the boardnameBOOT drive, and Windows or Windows Explorer seems to lock up. These programs are known to cause trouble: AIDA64: to fix, stop the program. This problem has been reported to AIDA64. They acquired hardware to test, and released a beta version that fixes the problem. This may have been incorporated into the latest release.
This applies to any kind of serial output whether it be error messages or print statements. So before you start trying to debug your problem on the hardware side, be sure to check that you haven't simply missed the serial messages due to serial output panel height.
Make sure to download a version with 2.0.0 or higher in the filename if you're using CircuitPython version 2.2.4, and the version with 3.0.0 or higher in the filename if you're using CircuitPython version 3.0. CIRCUITPY Drive Issues You may find that you can no longer save files to your CIRCUITPY drive. You may find that your CIRCUITPY stops showing up in your file explorer, or shows up as NO_NAME . These are indicators that your filesystem has issues.
https://adafru.it/EVK https://adafru.it/AdK https://adafru.it/AdK https://adafru.it/EoM https://adafru.it/EoM https://adafru.it/DjD https://adafru.it/DjD https://adafru.it/DBA https://adafru.it/DBA https://adafru.it/Eca https://adafru.it/Eca 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 yellow or blue, indicating the erase has started. 5.
5. Drag the appropriate latest release CircuitPython (https://adafru.it/Amd) .uf2 file to the boardnameBOOT drive. It should reboot automatically and you should see CIRCUITPY in your file explorer again. If you haven't already downloaded the latest release of CircuitPython for your board, check out the installation page (https://adafru.
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 (https://adafru.it/u1c) 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 .{,_.
# if lib does not exist, you'll create a file named lib ! cp -X foo.mpy /Volumes/CIRCUITPY/lib # This is safer, and will complain if a lib folder does not exist. cp -X foo.mpy /Volumes/CIRCUITPY/lib/ 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.
CircuitPython BuiltIns 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.
DigitalInOut(board.D7) . To find the pin or pad suggested in the code, see the list below. For the boards that require wiring, wire up a switch (also known as a tactile switch, button or push-button), following the diagram for guidance. Press or slide the switch, 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.
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.
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.
import time import board from analogio import AnalogIn analog_in = AnalogIn(board.A1) while True: print(analog_in.value) time.sleep(0.1) This works with any analog pin or input. Use the .value to read the raw value and utilise it in your code. © Adafruit Industries https://learn.adafruit.
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.
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. There is NO PWM on: A0, A1, A5.
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 and Circuit Playground Bluefruit, 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.
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. Standard Servo Code Here's an example that will sweep a servo connected to pin A2 from 0 degrees to 180 degrees (-90 to 90 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.
# Continuous Servo Test Program for CircuitPython import time import board import pulseio from adafruit_motor import servo # create a PWMOut object on Pin A2. pwm = pulseio.PWMOut(board.A2, frequency=50) # Create a servo object, my_servo. my_servo = servo.ContinuousServo(pwm) while True: print("forward") my_servo.throttle time.sleep(2.0) print("stop") my_servo.throttle time.sleep(2.0) print("reverse") my_servo.throttle time.sleep(2.0) print("stop") my_servo.throttle time.sleep(4.0) = 1.0 = 0.0 = -1.
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.
single onboard LED, the last thing we do is tell it that there's only 1 LED! 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.
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.
pixels[i] = color 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.
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(GREEN, 0.1) 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.
pixels.show() 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.
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.
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. 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).
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 and Circuit Playground Bluefruit Connect 3.3v on your CPX to 3.3v on your GPS. Connect GND on your CPX to GND 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.
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. Where's my UART? On the SAMD21, we have the flexibility of using a wide range of pins for UART. Compare this to some chips like the ESP8266 with fixed UART pins. The good news is you can use many but not all pins.
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.
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 and Circuit Playground Bluefruit 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.
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, SAMD51 and nRF52840, we have the flexibility of using a wide range of pins for I2C. On the nRF52840, any pin can be used for I2C! Some chips, like the ESP8266, require using bitbangio, but can also use any pins for I2C. 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.
print("Waiting for key pin...") 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) # ...
Next keyboard and keyboard_layout objects are created. We only have US right now (if you make other layouts please 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.
def get_voltage(pin): return (pin.value * 3.3) / 65536 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.
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 Expectations As we continue to develop CircuitPython and create new releases, we will stop supporting older releases. Visit https://circuitpython.org/downloads to download the latest version of CircuitPython for your board. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update CircuitPython and then visit https://circuitpython.org/libraries to download the latest Library Bundle.
CircuitPython and your code. This means that we're able to include more functionality in CircuitPython and you're able to do more with your code on an Express board than you would on a non-Express board. Express boards include Circuit Playground Express, ItsyBitsy M0 Express, Feather M0 Express, Metro M0 Express and Metro M4 Express. Non-Express boards include Trinket M0, Gemma M0, Feather M0 Basic, and other non-Express Feather M0 variants.
accuracy is about +/-1.7e-38, though numbers as small as +/-5.6e-45 can be represented with reduced accuracy. CircuitPython's floats have 8 bits of exponent and 22 bits of mantissa (not 24 like regular single precision floating point), which is about five or six decimal digits of precision. Differences between MicroPython and Python For a more detailed list of the differences between CircuitPython and Python, you can look at the MicroPython documentation.
© Adafruit Industries Last Updated: 2019-09-11 10:25:53 PM UTC Page 172 of 172