To get you started with how to program your Pico in CircuitPython, especially for those who may have started out with the official MicroPython setup, we've 'ported' the Getting Started with MicroPython on Pico book examples to CircuitPython. The book is awesome, please download/purchase it to support Raspberry Pi Press!

Now that you've installed CircuitPython, it's time to begin your first program. If you haven't already, plug in your Raspberry Pi Pico to your computer via USB. Then, open your favorite Python editor.

Click the Serial button in Mu to open the serial console. Click anywhere in the serial output window at the bottom of Mu, and press CTRL+C on your keyboard. This will bring you to the REPL. At the REPL prompt (>>>), type the following code followed by the ENTER key:

print("Hello, world!")

Immediately upon pressing enter, the code is executed. Python responds by printing the message.

The REPL, or the Read-Evaluate-Print-Loop, allows you to run individual lines of code, one at a time. You can run multiple lines of code in sequence to execute a longer program. It's great for testing a program line by line to determine where an issue might be. It's interactive, so it's excellent for testing new ideas.

It is, however, important to remember that the REPL is ephemeral. Any code you write there is not saved anywhere. If you'd like to save your code, you can easily do so with CircuitPython and Mu.

Once installed, CircuitPython presents your Pico board as a USB drive called CIRCUITPY. Your code and any necessary libraries live on this drive. With a fresh CircuitPython install, you'll find a code.py file containing print("Hello World!") and an empty lib folder. If your CIRCUITPY drive does not contain a code.py file, you can easily create one and save it to the drive. CircuitPython looks for code.py and executes the code within the file automatically when the board starts up or resets. Following a change to the contents of CIRCUITPY, such as making a change to the code.py file, the board will reset, and the code will be run. You do not need to manually run the code. Note that all changes to the contents of CIRCUITPY, such as saving a new file, renaming a current file, or deleting an existing file will trigger a reset of the board.

In Mu, if the file currently open is not code.py, click Load in the Mu button bar, navigate to your CIRCUITPY drive, and open code.py. If there is no code.py file, create a new file by clicking New in the Mu button bar, then click Save, navigate to your CIRCUITPY drive, and save the file as code.py.

Note that the code in code.py is not running while you are actively in the REPL. To exit the REPL, simply type CTRL+D at the REPL prompt (>>>).

You must exit the REPL for the code found in code.py to be run.

In the code.py file, click in the Mu text editor, and add the same simple line of code as above (if it's not already there). Save the file. The code will run automatically, and the message will be printed in the serial console!

Indentation and Code Loops

CircuitPython runs the same as a standard Python program, typically running from top to bottom, executing each line. However, you can control the flow of a program using indentation. Delete the current contents of your code.py file and replace them with the following code:

"""Example of definite loop."""
print("Loop starting!")
for i in range(10):
    print("Loop number", i)
print("Loop finished!")

Loop is referring to a section of code that runs repeatedly - in this instance, the for i in range(10):. This is called a definite loop, a loop that runs a set number of times, in this case, 10.

Your code.py should look like this:

Save the file, and check out the serial output.

Indentation is crucial to flow control in code, but is also a very common cause of syntax errors, which causes the code to fail to run. If your code fails with a syntax error, be sure to check your indentation.

There are also indefinite loops in CircuitPython, that is, a loop that continues indefinitely. Update your code.py to the following. Be sure to delete the existing code! Your code.py file should only include the following code.

"""Example of infinite loop. Final print statement is never reached."""
print("Loop starting!")
while True:
    print("Loop running!")
print("Loop finished!")

Keep an eye on the serial console and click save. You should see the Loop Starting! message posted once initially, and then the Loop running! message repeated indefinitely.

The Loop Finished! message will never show up because it is not "inside" the loop. When there is a while True: in Python code, everything indented under it will run repeatedly - when the end of the loop is reached, it will begin again at the beginning of the loop.

Conditionals and Variables

In CircuitPython, like Python, you can create variables. You can think of variables as a name attached to a specific object. To create a variable, you simply assign it and start using it. You use = to assign a variable name to the desired object.

Update your code.py to the following.

"""Example of assigning a variable."""
user_name = input("What is your name? ")

Save the file.

Click into the serial output. Type your answer to the question and press ENTER on your keyboard.

You've saved your name to the user_name variable! Now you can do something with it.

Update code.py to the following. Note that when Mu sees that your code needs to be indented, it will do it automatically. Therefore, if your next line of code does not need to be indented, you'll need to backspace to remove the indentation.

"""Example of assigning a variable and comparing it to a value."""
user_name = input ("What is your name? ")

if user_name == "Clark Kent":
    print("You are Superman!")
else:
    print("You are not Superman!")

Save your code.py file. Now click in the serial console, type in your name, and press ENTER on your keyboard. Unless your name is "Clark Kent", you'll see the You are not Superman! message.

While still in the serial console, type CTRL+D to reload, and run the code again. This time, type in Clark Kent, and press ENTER on your keyboard. Make sure you have the capitalisation exactly as shown!

You are Superman!

The == symbol tells CircuitPython to directly compare the text entered at the prompt, also known as a string, with "Clark Kent" to see if they are the same. If they are, then it prints the first message, You are Superman!, found under the if statement. If they are not, it prints the second message, You are not Superman!, found under the else statement.

There are other symbols, such as > and >=, to use if you're working with numbers instead of strings. To check if a string or value is not the same as another string or value, you would use !=, which is essentially the opposite of ==. These symbols are collectively known as comparison operators.

Note that = sets a variable equal to the value following it, and == checks to see if the variable is equal to the value following it. Don't mix them up!

Comparison operators can be used in loops as well. Update your code.py to the following and save.

"""Example of assigning a variable, and comparing it to a value in a loop."""
user_name = input ("What is your name? ")

while user_name != "Clark Kent":
    print("You are not Superman - try again!")
    user_name = input ("What is your name? ")
print("You are Superman!")

This time, instead of the code ending following the comparison of the entered name to Clark Kent, it will keep asking for your name until it turns out that you're Superman, at which point it will stop running.

That's only the beginning of what you can do with variables and conditionals in CircuitPython!

This guide was first published on Jan 21, 2021. It was last updated on 2021-03-03 12:34:49 -0500.

This page (CircuitPython Programming Basics) was last updated on Apr 14, 2021.

Text editor powered by tinymce.