Todbot's General Python Tricks

These are general Python tips that may be useful in CircuitPython.

blank_array = [0] * 50   # creats 50-element list of zeros

Storing multiple values per list entry

Create simple data structures as config to control your program. Unlike Arduino, you can store multiple values per list/array entry.

mycolors = (
    # color val, name
    (0x0000FF, "blue"),
    (0x00FFFF, "cyan"),
    (0xFF00FF, "purple"),
)
for i in range(len(mycolors)):
    (val, name) = mycolors[i]
    print("my color ", name, "has the value", val)
import sys
print(sys.modules.keys())
# 'dict_keys([])'
import board
import neopixel
import adafruit_dotstar
print(sys.modules.keys())
prints "dict_keys(['neopixel', 'adafruit_dotstar'])"
a = 123
b = 'hello there'
my_globals = sorted(dir)
print(my_globals)
# prints "['__name__', 'a', 'b']"
if 'a' in my_globals:
  print("you have a variable named 'a'!")
if 'c' in my_globals:
  print("you have a variable named 'c'!")

Display the running CircuitPython release

With an established serial connection, press Ctrl+c:

Adafruit CircuitPython 7.1.1 on 2022-01-14; S2Pico with ESP32S2-S2FN4R2
>>>

Without connection or code running, check the boot_out.txt file in your CIRCUITPY drive.

import os
print(os.uname().release)
'7.1.1'
print(os.uname().version)
'7.1.1 on 2022-01-14'

This guide was first published on Apr 02, 2022. It was last updated on Apr 02, 2022.

This page (General Python) was last updated on Apr 05, 2022.

Text editor powered by tinymce.