Circuit Python tutorials in Robotics II
View the Project on GitHub MrPrattASH/Robotics-II-Circuit-Python
Let’s get into our first physical component. We’re going to make our onboard LED blink on the M4 board.
The onboard LED is a red LED with the “L” next to it. By the end of this tutorial, you’ll be able to turn this on and off.
The rest of this tutorial is borrowed/modified from this AdaFruit Tutorial and has been modified to suit the needs of this course.
copy and paste the following code into your code.py and run it on your board
import board
import digitalio
import time
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
while True:
led.value = True
time.sleep(0.5)
led.value = False
time.sleep(0.5)
The little LED should now be blinking. Once per half-second.
Congratulations, you’ve just run your first CircuitPython program to make physical hardware function!
At the top of the code, you see 3 import statements
import board
import digitalio
import time
CircuitPython is designed to run on microcontrollers and allows you to interface with all kinds of sensors, inputs and other hardware peripherals. Unlike standard Python, most CircuitPython code includes hardware setup which requires various modules, such as board
or digitalio
. You import these modules and then use them in your code.
digitalio
adds the ability to use digital sensors (INputs) or devices (OUTputs), hence, digitalio (digital in/out)below our import statements, we have 2 lines
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
led = digitalio.DigitalInOut(board.LED)
creates a digital object variable called led and assigns it a digital in/out (io) pin. Looking at the board below, we have:
led.direction = digitalio.Direction.OUTPUT
sets the direction of our digital object.
Now we start our main loop. Note the indentation of the while True loop, similar to a list in a word doc:
while True:
led.value = True
time.sleep(0.5)
led.value = False
time.sleep(0.5)
led.value = True
tells us to send a 3.3v signal over our pin to turn ON the digital device. This is known as it’s value
, which can be boolean, True or False. True is on, False is off, or 1 is on, 0 is off, much like a power switch.
time.sleep(0.5)
takes the time module, and calls the sleep
method. This is a handy “method/function” from the time library/module that lets us take breaks in second incriments. Similar to led.value
, it uses something called dot notation, which means we can write a module/variable, then a .
dot, and we get a list of methods that we can use from this object.
while True:
loop, repeating this .5sec on, .5sec off loop forever.time.sleep(0.5)
to something like (1)
or (0.1)
. What changes to you observe to the LED?