Circuitpython

From Sketching with Hardware at LMU Wiki
Jump to navigation Jump to search

Introduction and step by step tutorial from Adafruit

Installing CircuitPython[edit]

Go to circuitpython.org/downloads and download the version for your board.

For the Raspberry PI Pico connect the board to the computer and the folder RPI-RP2 shows ups in your file system. For the Arduino Nano Connect RP2040 force the bootloder mode to upload the .uf2 file. Copy the .uf2 into the folder of the board.

Cp01.png Cp02.png

Now you should be able to connect to the board and use the editor.

If you need more help, here is a more detailed description on the installation process at adafruit.com

On the download site there is also a webbased download process - where the browser makes a serial connection to the board.

CircuitPy Drive[edit]

After installing CircuitPython on the board and reconnecting the board, it should show up as a USB drive on your computer with the name CircuitPy.

Here you can directly access the code you write and data you safe from your programs.

Cp05-usb-drive.png

As the board is a USB drive do not just unplug it - use "safe remove" feature of your OS.

Cp06-safe-remove.png Cp07-safe-remove.png

Running your first CircuitPython Program[edit]

In the file system of the board (that shows up as USB Drive CIRCUITPY) there is a file code.py.

To write your program, open code.py and edit it with your code. Once you safe it, it will be automatically excuted. The file name must be code.py or main.py.

Try it out with the following program. Just use any editor and open code.py. Replace it with the following code and you should see the LED flash. Changes the sleep times. Each time you safe it the new program will be active:

 1 # write on serial line and blink onbaord LED
 2 import board
 3 import digitalio
 4 import time
 5 
 6 led = digitalio.DigitalInOut(board.LED)
 7 led.direction = digitalio.Direction.OUTPUT
 8 
 9 while True:
10     led.value = False
11     time.sleep(0.8)
12     led.value = True
13     time.sleep(0.2)


 1 # check input, switch LED, write on serial line
 2 import board
 3 import digitalio
 4 from digitalio import DigitalInOut, Direction, Pull
 5 import time
 6 
 7 led = digitalio.DigitalInOut(board.LED)
 8 led.direction = digitalio.Direction.OUTPUT
 9 
10 switch = DigitalInOut(board.D2)
11 switch.direction = Direction.INPUT
12 switch.pull = Pull.UP
13 
14 while True:
15     time.sleep(0.2)
16     if switch.value:
17         led.value = False
18         print("Off")
19     else:
20         led.value = True
21         print("On")

Using Libraries[edit]

Here are examples of how to use libraries.

accelerometer of the Arduino Nano Connect RP2024[edit]

How to read the accelerometer of the Arduino Nano Connect RP2024.

Download the library (in this case it is in the zip from Adafruit, see Download Project Bundle).

Copy the library folders into the library folder on the USB drive (CIRCUITPY).

Cp08-lib.png Cp09-lib02.png

Now you can use the libraries, e.g. for reading the accelerometer using the adafruit_lsm6ds library.


 1 # SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries
 2 #
 3 # SPDX-License-Identifier: MIT
 4 import time
 5 import board
 6 from adafruit_lsm6ds.lsm6dsox import LSM6DSOX
 7 
 8 i2c = board.I2C()  # uses board.SCL and board.SDA
 9 # i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
10 sensor = LSM6DSOX(i2c)
11 
12 while True:
13     print("Acceleration: X:%.2f, Y: %.2f, Z: %.2f m/s^2" % (sensor.acceleration))
14     print("Gyro X:%.2f, Y: %.2f, Z: %.2f radians/s" % (sensor.gyro))
15     print("")
16     time.sleep(0.5)

for more details see: on how to use the onboard IMU of the Arduino Nano RP2040 Connect (LSM6DSOXTR)

Keyboard emulator[edit]

for more details on the mouse and keyboard emulator see the Adafruit page

We have also an example, where the IMU of the Arduino Nano Connect RP2040 is read and strings are send to the computer.

 1 # SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
 2 #
 3 # SPDX-License-Identifier: MIT
 4 
 5 """CircuitPython Essentials HID Keyboard example"""
 6 import time
 7 import board
 8 import digitalio
 9 from digitalio import DigitalInOut, Direction, Pull
10 import usb_hid
11 from adafruit_hid.keyboard import Keyboard
12 from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
13 from adafruit_hid.keycode import Keycode
14 
15 led = digitalio.DigitalInOut(board.LED)
16 led.direction = digitalio.Direction.OUTPUT
17 
18 switch = DigitalInOut(board.D2)
19 switch.direction = Direction.INPUT
20 switch.pull = Pull.UP
21 
22 # The keyboard object!
23 time.sleep(1)  # Sleep for a bit to avoid a race condition on some systems
24 keyboard = Keyboard(usb_hid.devices)
25 keyboard_layout = KeyboardLayoutUS(keyboard)  # We're in the US :)
26 
27 
28 while True:
29     time.sleep(2)
30     if switch.value:
31         led.value = False
32         print("Off")
33     else:
34         led.value = True
35         print("On")
36         keyboard_layout.write("Hi There")  # ...Print the string

Complaining Sensor[edit]

  1 #"""based on CircuitPython Essentials HID Keyboard example"""
  2 
  3 # IF you connect D2 and GND it acts as keyboard
  4 
  5 import time
  6 import board
  7 import digitalio
  8 from digitalio import DigitalInOut, Direction, Pull
  9 import usb_hid
 10 from adafruit_hid.keyboard import Keyboard
 11 from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
 12 from adafruit_hid.keycode import Keycode
 13 from adafruit_lsm6ds.lsm6dsox import LSM6DSOX
 14 
 15 i2c = board.I2C()  # uses board.SCL and board.SDA
 16 # i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
 17 sensor = LSM6DSOX(i2c)
 18 
 19 led = digitalio.DigitalInOut(board.LED)
 20 led.direction = digitalio.Direction.OUTPUT
 21 
 22 switch = DigitalInOut(board.D2)
 23 switch.direction = Direction.INPUT
 24 switch.pull = Pull.UP
 25 
 26 def sensorRead():
 27         a=(sensor.acceleration)
 28         g=(sensor.gyro)
 29         return (a+g)
 30 
 31 # The keyboard object!
 32 time.sleep(1)  # Sleep for a bit to avoid a race condition on some systems
 33 keyboard = Keyboard(usb_hid.devices)
 34 keyboard_layout = KeyboardLayoutUS(keyboard)  # We're in the US :)
 35 
 36 
 37 while True:
 38     readings = []
 39     
 40     for _ in range(100):
 41         reading = sensorRead()
 42         readings.append(reading)
 43         time.sleep(0.02)  # Sleep for 100 milliseconds
 44     
 45     sum_absolute_differences = [0] * 6
 46 
 47     for i in range(1, len(readings)):
 48         for j in range(6):  # Assuming each reading has 6 components
 49             sum_absolute_differences[j] += abs(readings[i][j] - readings[i-1][j])
 50     
 51     x = sum(sum_absolute_differences)
 52     print(x)
 53     
 54     #for i, reading in enumerate(readings):
 55         #print(f"Reading {i+1}: {reading}")
 56     
 57     if switch.value:
 58         led.value = False
 59         write2keyboard = False
 60         #print("Off")
 61     else:
 62         led.value = True
 63         write2keyboard = True
 64         #print("On")
 65 
 66     #if write2keyboard: 
 67     #    keyboard.press(Keycode.SHIFT, Keycode.A)
 68     #    keyboard.press(Keycode.ENTER)
 69 
 70     if 0 <= x <= 20:
 71         print("nothing")
 72     elif 20 < x <= 180:
 73         print("nice, I like this\n")
 74         if write2keyboard:
 75             keyboard_layout.write("nice, I like this\n")
 76     elif 180 < x <= 300:
 77         print("are you careful?")
 78         if write2keyboard:
 79             keyboard_layout.write("are zou careful_\n")
 80     elif 300 < x <= 400:
 81         print("be careful with me!")
 82         if write2keyboard:
 83             keyboard_layout.write("be careful with me!\n")
 84     elif 400 < x <= 600:
 85         print("no this is not nice!")
 86         if write2keyboard:
 87             keyboard_layout.write("no this is not nice!\n")
 88     elif 600 < x <= 800:
 89         print("this hurts!!!")
 90         if write2keyboard:
 91             keyboard_layout.write("this hurts!!!\n")
 92     elif x > 800:
 93         print("you are killing me")
 94         if write2keyboard:
 95             keyboard_layout.write("zou are killing me\n")
 96     else:
 97         print("Value out of range")
 98         
 99     if write2keyboard:
100             time.sleep(1)
101     time.sleep(1)

Finding your PIN names - Pin mapping script[edit]

CircuitPython uses it own names which makes it easier to use the same code on different boards. But this requires you to first find out which PINs on your physical board map to the logical pins in the program code.

There is a pin mapping scriptt avaiable for this at Adafruit. You can download the project bundel there. Here is the script, too. And below are the mappings for the Arduino Nano Connect RP2024 and the Raspberry Pi Pico

 1 # SPDX-FileCopyrightText: 2020 anecdata for Adafruit Industries
 2 # SPDX-FileCopyrightText: 2021 Neradoc for Adafruit Industries
 3 # SPDX-FileCopyrightText: 2021-2023 Kattni Rembor for Adafruit Industries
 4 # SPDX-FileCopyrightText: 2023 Dan Halbert for Adafruit Industries
 5 #
 6 # SPDX-License-Identifier: MIT
 7 
 8 """CircuitPython Essentials Pin Map Script"""
 9 import microcontroller
10 import board
11 try:
12     import cyw43  # raspberrypi
13 except ImportError:
14     cyw43 = None
15 
16 board_pins = []
17 for pin in dir(microcontroller.pin):
18     if (isinstance(getattr(microcontroller.pin, pin), microcontroller.Pin) or
19         (cyw43 and isinstance(getattr(microcontroller.pin, pin), cyw43.CywPin))):
20         pins = []
21         for alias in dir(board):
22             if getattr(board, alias) is getattr(microcontroller.pin, pin):
23                 pins.append(f"board.{alias}")
24         # Add the original GPIO name, in parentheses.
25         if pins:
26             # Only include pins that are in board.
27             pins.append(f"({str(pin)})")
28             board_pins.append(" ".join(pins))
29 
30 for pins in sorted(board_pins):
31     print(pins)

When you run the script on a specific controller you get a text ouput that is the mapping.

CircuitPython Pin Mapping for Arduino Nano Connect RP2024[edit]

 1 board.A0 (GPIO26)
 2 board.A1 (GPIO27)
 3 board.A2 (GPIO28)
 4 board.A3 (GPIO29)
 5 board.A4 board.SDA (GPIO12)
 6 board.A5 board.SCL (GPIO13)
 7 board.CS1 board.ESP_CS (GPIO9)
 8 board.D0 board.TX (GPIO0)
 9 board.D1 board.RX (GPIO1)
10 board.D10 (GPIO5)
11 board.D11 board.MOSI (GPIO7)
12 board.D12 board.MISO (GPIO4)
13 board.D13 board.LED board.SCK (GPIO6)
14 board.D2 (GPIO25)
15 board.D3 (GPIO15)
16 board.D4 (GPIO16)
17 board.D5 (GPIO17)
18 board.D6 (GPIO18)
19 board.D7 (GPIO19)
20 board.D8 (GPIO20)
21 board.D9 (GPIO21)
22 board.ESP_BUSY (GPIO10)
23 board.ESP_GPIO0 (GPIO2)
24 board.ESP_RESET (GPIO3)
25 board.INT1 (GPIO24)
26 board.MICROPHONE_CLOCK (GPIO23)
27 board.MICROPHONE_DATA (GPIO22)
28 board.MISO1 (GPIO8)
29 board.MOSI1 (GPIO11)
30 board.SCK1 (GPIO14)

CircuitPython Pin Mapping for Raspberry PI Pico[edit]

 1 board.A0 board.GP26 board.GP26_A0 (GPIO26)
 2 board.A1 board.GP27 board.GP27_A1 (GPIO27)
 3 board.A2 board.GP28 board.GP28_A2 (GPIO28)
 4 board.A3 board.VOLTAGE_MONITOR (GPIO29)
 5 board.GP0 (GPIO0)
 6 board.GP1 (GPIO1)
 7 board.GP10 (GPIO10)
 8 board.GP11 (GPIO11)
 9 board.GP12 (GPIO12)
10 board.GP13 (GPIO13)
11 board.GP14 (GPIO14)
12 board.GP15 (GPIO15)
13 board.GP16 (GPIO16)
14 board.GP17 (GPIO17)
15 board.GP18 (GPIO18)
16 board.GP19 (GPIO19)
17 board.GP2 (GPIO2)
18 board.GP20 (GPIO20)
19 board.GP21 (GPIO21)
20 board.GP22 (GPIO22)
21 board.GP23 board.SMPS_MODE (GPIO23)
22 board.GP24 board.VBUS_SENSE (GPIO24)
23 board.GP25 board.LED (GPIO25)
24 board.GP3 (GPIO3)
25 board.GP4 (GPIO4)
26 board.GP5 (GPIO5)
27 board.GP6 (GPIO6)
28 board.GP7 (GPIO7)
29 board.GP8 (GPIO8)
30 board.GP9 (GPIO9)

Install the Mu Editor[edit]

Follow the instructions for installting the Mu Editor.

  • Install it on your system
  • On first start up select CircuitPython as Mode

Cp3-mu.png

  • Test if it works in the CircuitPython REPL console

Cp4-mu.png