Overview

Open source software is awesome. It's a shared resource that we all work on to benefit ourselves and others all at once. CircuitPython is built on the open source code of MicroPython for example.

One challenge of open source software is making your code and documentation available in a way that makes it accessible to those that use it. Its not just a matter of writing code and posting it somewhere on the internet. For the core of CircuitPython we have existing source control on GitHub, low-level documentation on ReadTheDocs, continuous testing on TravisCI, tutorials on Adafruit Learn System, community support on the Adafruit Forums and live chat on Gitter and Discord.

However, there is much more to CircuitPython than just the core code. There are also additional libraries that expand what can be done on CircuitPython. They may add additional support for a particular FeatherWing or making simple tasks easier.

To make CircuitPython libraries easy to find and understand we've come up with a number of best practices when creating a new library. This guide is an overview of those practices with links to more information on specific topics.

Creating a library

Getting coding

Usually when creating a library to share with the world, the biggest issue isn't the code itself. Its common for a library to evolve naturally out of an existing project. It may have been a clock project where you switched the real-time clock partway through or a simple project which has grown in complexity demanding some code refactoring. The first challenge is identifying what can make up a library.

In CircuitPython (and Python in general) libraries are known as packages and modules. A module is a single python file that can be imported by another file by using the import statement. A package is a folder filled with modules and is used to group common modules together. The adafruit_rgb_display package is an example of this. Both packages and modules can be called libraries.

By importing libraries, code can gain functionality without the clutter of additional code within the same file. Instead, one only needs to understand the Application Programming Interface or API to use the power of the imported library. Its not important to read and understand the code that implements the API. Outside of software, you can think of the steering wheel in a car as the API to the turning functionality of the car. You don't need to understand how the car's wheels turn, you just know that when you turn the steering wheel, the car turns.

Hopefully, as your project has evolved, you've begun to use functions and classes to create APIs. Creating powerful, easy to understand APIs is a difficult thing to do and something a Google search can provide many resources on. Here is one Python specific talk from PyCon 2017: https://www.youtube.com/watch?v=4mkFfce46zE

Once you've got an API you are happy with, its time to make it available to the world.

Cookie cutter

One of the first helpful tools for creating a CircuitPython library is called CookieCutter. It is an open source project that was made to help manage common content between projects. This common content is also called a boiler plate. For CircuitPython libraries, this boiler plate includes ten files. Whoa! Thats a lot for a simple library. However, they are all useful. Only one will hold your code. Below is an overview. Don't worry too much about understanding it all because most relate to topics we'll discuss later.

  • .gitignore - Prevents autogenerated files from being shared publicly by git.
  • .travis.yml - Configures automated testing and release file generation.
  • CODE_OF_CONDUCT.md - Outlines expectations for behavior of contributors to ensure a friendly, welcoming environment. Source from Contributor Convenant.
  • LICENSE - Contains the legal text for the license which allows others to use and modify the code you've written. We default to MIT but others can be used. We recommend choosealicense.com by GitHub for an easy way to decide what is right for you. Typically a comment will be placed at the top of source code files to clarify their license if it gets copied away from the rest of the files.
  • README.rst - This is your most important documentation! It is the first thing people read when they unzip your source or pull it up on GitHub. It can be plain text, Markdown (.md) or reStructuredText (.rST). The latter two will be nicely rendered on GitHub. We prefer .rST for CircuitPython libraries because it makes it easy to integrate with Sphinx, ReadTheDocs and autogenerated documentation.
  • adafruit_{name}.py - Your code! This is the module you can use to organize your code. It automatically includes example license text and comments.
  • api.rst - Triggers the autogeneration of documentation for the above module.
  • conf.py - Configuration settings for Sphinx.
  • readthedocs.yml - Configuration settings for ReadTheDocs
  • requirements.txt - Lists other libraries that your depends on to work correctly. Typically things you import in your code that aren't provided by CircuitPython automatically.
  • setup.py - Required for PyPI deployment. File will be present even if library is not deployed to PyPI.

You may have noticed that the filename of your library is adafruit_{name}.py. The {name} portion will be replaced when the cookiecutter is actually run. We recommend removing the adafruit_ portion and replacing it with a prefix of your own. The adafruit_ prefix means that we fully support the library going forwards.

Installing cookiecutter

cookiecutter is itself a Python library so you'll need Python and pip installed first. Then run:

Download: file
pip install cookiecutter

Running cookiecutter

Running cookiecutter is equally easy. All it needs is a location of where to pull the template from. Everything else is done via prompt.

Download: file
cookiecutter gh:adafruit/cookiecutter-adafruit-circuitpython

Prompts

  • library_name - Shortest name for the library. Usually a chip name such as LIS3DH. THIS MUST BE ENTERED EXACTLY THE SAME WAY IT WILL LOOK IN THE GITHUB REPO URL (e.g. for github.com/adafruit/Adafruit_CircuitPython_CharLCD, you must enter CharLCD). Use all caps or camel case as necessary. If you enter this differently than the GitHub URL, you will need to fix a number of things in your library later.
  • library_prefix - Used to prefix the code to the organization creating the library. For example, Adafruit supported libraries should say Adafruit here. Do not add a - or _.
  • library_description - Write a sentence describing the purpose of this library (e.g. CircuitPython helper library for the DC & Stepper Motor FeatherWing, Shield and Pi Hat kits.).
  • library_keywords - Used to populate keywords for searching for the library on PyPi. Enter a string of lowercase keywords (e.g dht temp humidity) Please be thorough! The more search keywords you enter, the easier it is to find. This step should be completed even if you don't think the library will end up deployed on PyPI. NOTE: The following are included by default: adafruit, blinka, circuitpython, micropython, and library_name.
  • author - Who you are! Sets the copyright to you.
  • github_user - GitHub user or organization which will host this repo. For example, Adafruit funded libraries should say adafruit here.
  • company - Used to give Copyright credit to the company funding the library. For example, Adafruit funded libraries should say "Adafruit Industries" here.
  • depends_on_bus_device - Determines whether to add comments about a dependency on https://github.com/adafruit/Adafruit_CircuitPython_BusDevice. Leave empty if the library won't use BusDevice.
  • depends_on_register - Determines whether to add comments about a dependency on https://github.com/adafruit/Adafruit_CircuitPython_Register. Leave empty if the library won't use Register.
  • other_dependencies - Add any other module dependencies. Enter a comma separated string of modules, using the lowercase full name of the module, using - instead of _  (e.g. adafruit-circuitpython-pca9685, adafruit-circuitpython-motor, pyserial). This is used to for PyPI. This step should be completed even if you don't think the library will be deployed to PyPI.. NOTE: Adafruit-Blinka is always included, so no need to include it here.

At this point all the files you need should be in place. Now you'll need to migrate your code into the generated .py file. If you have a lot of code you can make a directory of the same name and have multiple modules within it. For now, we'll keep it simply a module.

MPY

Once your code is there, test it in CircuitPython by copying it over to your board. If you get a MemoryError on import you can create a smaller .mpy file thats easier to load in CircuitPython.

To do so, you'll need to download (or clone) the CircuitPython source, make mpy-cross and run it on your source file.

git clone https://github.com/adafruit/circuitpython.git
cd circuitpython/mpy-cross
make
./mpy-cross example/adafruit_example.py

Make sure example/adafruit_example.py is changed to your file. It will make a example/adafruit_example.mpy file that you can copy to CircuitPython just like a .py file.

Saving your work

At this point you've done a ton of work getting your library code going, initally tested and settings in place. Its time to commit your code and prep to publish this first version to the world.

Committing code is a way to keep track of how code changes over time. It also makes it possible to view what the files looked like previously. The simplest way to do this is to copy the whole folder to a new location. However, source control software is a much better way to organize it. Source control software makes it easy to view changes between versions (called diffs), back up the code to another computer and collaborate with others.

git is our and many others' preferred source control software. It was created by the same person as the Linux kernel and quickly grew in popularity due to its use there and its distributed nature. GitHub, a website for project hosting, grew up around git and is now the de facto place on the web to share your projects. Open source projects are hosted for free and private projects are hosted for a small fee.

Anyways, lets get git going to commit our code locally. See this guide for details on installing git. Consider this a quick start to initializing a repository (make sure you are in the library's directory).

The first command initializes a .git folder that stores the repository metadata. The second stages all of the files in the directory to be committed. Being more precise with individual files is recommended when changing your code for multiple reasons at once. Making two commits will make it easier to understand what changed and why. For now, we'll do one initial commit.

The final step will actually commit your code after prompting your for a commit message. In the message you should give a short one line summary followed by a detailed paragraph about the changes. The video below gives good tips on commit messages and code reviews.

Temporarily unable to load embedded content:
https://www.youtube.com/watch?v=iNG1a--SIlk
If you've used other source control theres an important distinction between commits in the subversion, cvs and perforce sense and the git sense. In those others, committing is the same as sharing with others. In git, a commit is for you alone until its shared or "pushed". That means you can change commits and revise the history of your code to better reflect your changes and motivations after committing it. This is known as "rewriting history" in git terminology and is super powerful. Its only when a commit is shared with others on a shared branch in a shared repo that it shouldn't be done because other's may have built on top of it already.

Sharing on GitHub

Now that we've got everything squared away on our own computer, its time to share it with the world. The main avenue we'll use to share the code is GitHub, a code hosting site that is very popular with open source projects and developers. Once that is setup, we'll set up ReadTheDocs integration so that our documentation is hosted and automatically updated. We'll set up Travis CI so that our code is automatically checked by mpy-cross and that releases have mpy files on them.

GitHub

GitHub is the bees knees. They offer free project hosting including code, issues, wiki and website for open source projects. It is extremely popular for good reason. They integrate with git to host your code.

So, the first step to sharing your project is creating the GitHub git repository.

The repository name can be anything but we're sticking to Adafruit_CircuitPython_{name} for official Adafruit libraries and suggest CircuitPython_{name} for community libraries. Fill in the description with a short, informative sentence about your library. DO NOT check the Initialize box. We'll do that with our existing files in the next step.

On the next page click SSH and copy the text to the right of it starting with [email protected]. We're going to follow the second set of instructions because we've already created our local git repository (repo for short). The first step makes our local repo aware of the GitHub repo and names it tannewt rather than origin because I find it clearer to match the GitHub repository name. The second step pushes the commit we made before to the GitHub repository and makes the code public.

git remote add <your username> <the repo url>
git push -u <your username> master
For others who have used another version control system, this is the point where you shouldn't change your commits. Before this they were private to you. At this point they are public and others may build on them.

At this point, you may have been prompted for your GitHub password. If you entered it correctly it should work. I use GitHub Desktop to manage my login and recommend it.

Now we can verify our code is live by refresh our browser tab.

Woohoo! We're live! While we're here. Lets add the circuitpython topic to our repo by clicking Add topics, typing in circuitpython and clicking Done.

Better README

Now if we scroll down, we'll see our README. This is the single most important document for the whole project. It should be concise but contain basic description of the library, what it depends on, how to use it, how to contribute and where to find more detailed documentation.

Since our README doesn't have that information we'll do a quick edit to add some more information. I use Atom (created by GitHub) for file editing. It has good git integration including highlighting edited lines and files in orange.

Now that the file is up to date, I do a quick commit and push to make it live.

And if we refresh the repo page we see our new and improved README.

Ok! We're up and rolling. The code we've written is public, we've learned how to update it further and have a good README. We can click Commits on the front page to see a list of all our public commits on the front page. Next up is getting our docs on ReadTheDocs.

Sharing docs on ReadTheDocs

Great documentation is a key component of a successful open source library. Luckily, after a little setup, its super easy to write and maintain great docs. ReadTheDocs is another free hosting service used by many open source projects. It integrates with GitHub so that every time new code or docs are pushed to your GitHub, the nicely formatted versions hosted by ReadTheDocs are also updated.

Lets get it setup! First, sign up and login if you don't already have an account. After signing in, your dashboard will be displayed.

On the dashboard click Import a Project and select Import Manually.

For the next page we'll need the https version of our GitHub repository so we go grab it by clicking Clone or Download on the repo front page and selecting Use HTTPS.

Then press the copy icon.

And paste it into the Repository URL field in ReadTheDocs. The name should be Adafruit CircuitPython Example. Then click next.

If you created your ReadTheDocs account and linked your GitHub (like I have below) then it should be able to automatically connect GitHub to itself by creating a Webhook. This Webhook is how ReadTheDocs gets updates from GitHub.

On the right hand side you should also see links to your documentation that you can use to link others to it.

If it didn't automatically create a webhook for you, then you'll need to add ReadTheDocs integration to your GitHub repo manually by going to Settings -> Integrations & Services from your repo. On the right there will be an Add service button that you click and select ReadTheDocs for a long list. Search for "read" to shorten the list.

Then its as simple as clicking Add service.

The next page confirms the service was added by confirming the webhook (aka hook) was created and also listing ReadTheDocs in the Services.

After that, we go back to ReadTheDocs and refresh. We see that its been built successfully on the right and at the top we can view the docs.

Now, as a last step, lets make sure our docs look as expected by clicking the View Docs button.

Awesome! By default it shows our README.rst (didn't I say it was important?). Furthermore, the lefthand side has a link with our module's name. Lets click it to see the module's documentation.

Yay! Everything looks good. This is exactly as we've defined in our Python file. For now, docs are done. :-)

Testing with Travis CI

One of the biggest challenges for software projects of all kinds is ensuring the software works as expected. This isn't as simple as it seems, particularly when multiple people are working on a project at once. Each person has different expectations about what the code should do and different testing setups.

Testing is used to make sure that each person's expectations are compatible and that the software still meets those expectations. Often testing is overlooked out of an urge for expediency. However, its well understood that, in the long term, good testing can help increase the development pace of a library. This is due to the confidence gained from tests that validate all expected functionality. It allows a maintainer to know immediately whether a requested change breaks any existing expectations or not. If it doesn't break anything, then its much easier to accept into the existing code.

Rust uses thorough testing as part of their "Not Rocket Science Rule" of software engineering. More info here: https://graydon2.dreamwidth.org/1597.html

Unfortunately, testing can be complicated and is worth covering in another full guide. This is especially true with CircuitPython where code is running on a microcontroller rather than a full operating system. For now, we'll just cover the basics of setting up Travis.

Travis CI

A cornerstone of good testing practice (and the Not Rocket Science Rule) is continuous integration (CI for short). CI is the process of automatically running tests on every change to a source code repository. In our case, we'll hook up Travis CI to our GitHub repo so that it tests each commit including proposed pull requests. Furthermore, it will automatically create an mpy file for each of our releases.

To get started with Travis, visit the website and sign up. Once signed in, you'll see a list of currently active repositories.

Once there, click the plus to activate your new repository.

Now scroll down the page until you see the new repo and click the switch on the left to activate it.

Now that its activated, click the repo name to see its status.

Now from that page click Build History. Nothing should appear yet, so do a small commit (Add more to your README for example) to test that its set up correctly. Refresh the build history tab and you should see a yellow pending build. Once it completes, it should be green.

Releasing mpys

mpy files are convenient, binary Python files that are easier to load when memory is tight. Travis can automatically build them and attach them to a release. The .travis.yml file already has everything configured except for permissions to attach files to releases. :-) (Shout out to TonyD for adding this support.)

This involves granting a third-party many rights to your public repositories. If that makes you uncomfortable, skip this step and manually attach mpy files to releases instead.

To give Travis rights to attach files to our releases we'll need to generate a personal access token for GitHub. Never ever share these tokens with anyone! They allow anyone to act as you on GitHub in limited scopes.

To generate a new one, head to your GitHub settings and select Personal Access Tokens.

Once there you will see everything that you've already generated an access token for. The tokens themselves aren't ever visible after they are generated. Instead, you can always generate a new token. Delete any tokens you aren't using currently or those that may have accidently been shared.

For now, we'll generate a new token.

Now fill out the description so that you know what the key was used for and can tell in the future if you still need it.

Also tick the box next to public_repo this gives anyone with the token access to all of your public repos so be very careful with the token. We trust Travis CI so its ok to give it to them.

Lastly, scroll down and click Generate Token.

This will take you back to the token list with a new entry in green with the token visible. Click the copy button to copy it to keyboard and switch back to the Travis tab. If you lose the token, you can regenerate a new one by clicking edit.

I've intentionally covered the code with the arrow because tokens should only be shared to those you trust. Never ever commit them to git for example because anyone can see that. If for any reason you believe someone you do not trust has it, either regenerate a new key through Edit or Delete it altogether. I'm regenerating this one after writing this guide even though I covered it. Its ok to be paranoid with these tokens.

Now that we have a code, lets set it up in Travis. Navigate to the build's settings by clicking Settings under More Options. Scroll down to the Environment Variables section and enter it with the name GITHUB_TOKEN and the copied token as the value. Leave Display value in build log OFF otherwise you'll share the token with the world. Lastly, click Add.

After clicking Add we should see a new entry for GITHUB_TOKEN with our token obscured. Don't worry, it saved ok. They are just doing their best to keep it secret too. Time to release!

Also, don't forget to close or refresh the GitHub tab with your token. You don't want to accidently share it in later screenshots. Refreshing will show our description rather than the token.

Releasing on GitHub

Phew, what a whirlwind. Now that we've got our code on GitHub, our docs on ReadTheDocs and Travis going we're ready to release!

A release is simply a point in the lifecycle of a software project where the maintainers believe the software is worth trying and using. Pre-release releases are used for cases where the code is in early preview and may still contain bugs. Stable releases typically aren't released with known bugs and are geared towards wide adoption.

Creating or "cutting" a new release is also the point where the maintainer typically provides pre-built or binary releases. In our case, we've setup Travis to automatically provide mpy binary files for every release.

To get started, pull up your repo and click the releases button.

Once there, click Create a new release.

Now, decide on a version number for this release. CircuitPython's tools require Semantic Versioning (shortened to SemVer) to work. SemVer is three numbers separated by periods. This is not the same as a decimal number since there are two periods. Anything less than 1.0.0 is typically pre-release and anything after marked alpha, beta or rc for release candidate is also. For example, 1.0.0-rc.1 would be the first release candidate for 1.0.0 and be pre-release. Normal releases would be something like 0.10.0. Do not start the version with a v.

The first number should be incremented and others reset to 0 when the library was changed in a way that may require old code to be rewritten. Changing public function names for example would cause 1.3.0 to become 2.0.0.

The second number should be incremented, leaving the first and setting the third to zero if new functionality was added but the existing code is compatible. For example add a new function would lead from 1.3.3 to 1.4.0.

Lastly, the third number should be incremented if existing functionality was fixed. For example a function released in 1.4.0 didn't always work as expected and it was fixe in 1.4.1.

Once you decide on a version number enter it into the top box. This will create a git tag that will mark when in the git history the release occurred. You can also do this from git and then refer to an existing tag here.

Next, fill in the title and give the release a description including pointers to other related resources.

The release description uses Markdown for formatting and you can preview what it would look like after the save using the Preview tab. Here is a copy of the release description so you can start with it!

Download: file
Adds basic `hello` functionality.

To use in CircuitPython, download the .mpy file and copy it to the `lib` folder on the `CIRCUITPY` drive. Or, simply install the [Community bundle](https://github.com/adafruit/CircuitPython_Community_Bundle).

Read the [docs](https://circuitpython-example.readthedocs.io/en/latest/) for info on how to use it.
If you chose not to set up Travis to build your release binaries, this is when you can upload them yourself.

Now that everything looks good, lets publish the release. Don't forget to tick the pre-release box (under the arrow) if you want this to be marked as such.

After you hit publish you'll be taken to the release page on GitHub. This is a great place to link folks to so they can get all of the latest information on the release. GitHub includes zip files of the full source code by default.

The release also triggers a build from Travis. Navigate to the Travis project to check on it. Everything should be green.

Once Travis is green, the release should be updated with the .mpy file for the release. This file can then be copied to the CIRCUITPY drive to be used.

The other way folks can use the library is by downloading it as a part of a larger bundle. We have the Adafruit bundle for officially supported libraries and the Community bundle for those created and maintained by the larger community.

Sharing in a Bundle

We've created a couple library bundles for CircuitPython. The idea is that one can have all available libraries stored on the CircuitPython drive at once and then import them as needed. (They won't all fit into memory though.) This makes experimentation super easy because you only need to load everything once.

Another advantage of the bundle is that it makes it easy to find a list of all libraries. Even if you can't store all of the libraries on the drive, for example the Gemma M0 is only 64kb, the bundle makes it easy to copy over what you need when you need it.

It also helps CircuitPython devs keep track of libraries and update them as things change.

So, lets get our example library into the community bundle. To do so, we'll make a pull request on GitHub. First, lets fork the community bundle.

After the fork is done, the repo will look the same except the repo name will be different at the top left.

Next we'll clone the repo to our computer. See this guide for detailed instructions on cloning and submitting a pull request. Consider this a quickstart.

When cloning, make sure that you add --recursive to get all of the submodules too.

Adding the submodule to the Library Bundle

Now to add our library to the bundle we'll do:

git submodule add URL_TO_LIBRARY_INCLUDING.git libraries/SUBFOLDER/lowercase_library_name

You'll change the following:

  • URL_TO_LIBRARY_INCLUDING.git  - This will be the full URL to the library including the .git on the end. To get this URL, click on "Clone" in the GitHub repo, choose HTTPS, and copy that URL. Or you can copy the URL from the repo and add the .git.
    • Example: https://github.com/adafruit/Adafruit_CircuitPython_PyPortal.git
  • SUBFOLDER - The subfolder will be helpers or drivers. Choose which based on your library. Is it a driver? Choose drivers. Is it a helper? Choose helpers.
    • Example:  libraries/helpers/ or libraries/drivers/
  • lowercase_library_name - This is the name of your library, minus the Adafruit_CircuitPython_, in lowercase letters.
    • Example: pyportal

FULL EXAMPLE:

  • git submodule add https://github.com/adafruit/Adafruit_CircuitPython_PyPortal.git libraries/drivers/pyportal

And then we'll verify it worked by looking at the build log and versions file.

Updating the drivers.rst Library List

Before we submit a pull request with our new library, lets update the bundle documentation to include a link to the documentation for our library. Use whichever method you wish to open /docs/drivers.rst.

In drivers.rst, choose one of the categories to place your documentation link. The current categories are: Board-specific Helpers, Helper, Blinky, Displays, Real-time Clocks, Motion Sensors, Environmental Sensors, Light Sensors, Distance Sensors, Radio, IO Expansion, and Miscellaneous. Or, you can create a new category if that best describes your library.

With your category chosen, simply add a new line to that section using the reStructuredText hyperlink format. Easiest way, is to copy an existing line and edit it to change both the link text and the URL.

The reST markup language is indent-sensitive. Make sure you are properly aligned under the '.. toctree::' directive.

Next, lets do our normal commit and push process for a new branch.

Going to GitHub will show an easy prompt to create the pull request.

Follow that to see a differences. Make sure that at the top you are comparing against adafruit/CircuitPython_Community_Bundle as the base fork and your branch as the head fork. Make sure at the bottom left that maintainers can edit it (for simple fixes before they submit). Then click Create pull request at the bottom right.

This is the last step you need to do. One of the maintainers will come and respond on the pull request. Once they are happy with the request, it will be merged into the bundle and go out with the next release. It'll show up as purple once accepted.

This guide was first published on Jul 31, 2017. It was last updated on Jul 31, 2017.