name = "John"
fav_color = 0x003366
body_temp = 98.65
fav_number = 123
print("name:%s color:%06x temp:%2.1f num:%d" % (name,fav_color,body_temp,fav_number))
# 'name:John color:ff3366 temp:98.6 num:123'

Formatting strings with f-strings

(This doesn't work on 'small' CircuitPythons like QTPy M0 due to the small amounts of flash memory on the board.)

name = "John"
fav_color = 0x003366
body_temp = 98.65
print(f"name:{name} color:{color:06x} temp:{body_temp:2.1f} num:{fav_number:%d}")
# 'name:John color:ff3366 temp:98.6 num:123'
# my_config.py
config = {
    "username": "Grogu Djarin",
    "password": "ig88rules",
    "secret_key": "3a3d9bfaf05835df69713c470427fe35"
}

# code.py
from my_config import config
print("secret:", config['secret_key'])
# 'secret: 3a3d9bfaf05835df69713c470427fe35'

Run different code.py on startup

Use microcontroller.nvm to store persistent state across resets or between boot.py and code.py, and declare that the first byte of nvm will be the startup_mode. Now if you create multiple code.py files (say) code1.py, code2.py, etc. you can switch between them based on startup_mode.

import time
import microcontroller
startup_mode = microcontroller.nvm[0]
if startup_mode == 1:
    import code1      # runs code in `code1.py`
if startup_mode == 2:
    import code2      # runs code in `code2.py`
# otherwise runs 'code.py`
while True:
    print("main code.py")
    time.sleep(1)

Note: in CircuitPyton 7+ you can use supervisor.set_next_code_file() to change which .py file is run on startup. This changes only what happens on reload, not hardware reset or powerup. Using it would look like:

import supervisor
supervisor.set_next_code_file('code_awesome.py')
# and then if you want to run it now, trigger a reload
supervisor.reload()

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

This page (Computery Tasks) was last updated on Mar 29, 2022.

Text editor powered by tinymce.