Skip to content

Commit a2c13bd

Browse files
authored
Merge branch 'adafruit:main' into main
2 parents bbd1f86 + cd47073 commit a2c13bd

File tree

67 files changed

+1897
-298
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+1897
-298
lines changed

CPBoxing_Glove_Tracker/code.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# SPDX-FileCopyrightText: 2023 Trevor Beaton for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
import time
5+
import ssl
6+
import math
7+
import board
8+
import microcontroller
9+
import wifi
10+
import socketpool
11+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
12+
from adafruit_io.adafruit_io import IO_MQTT
13+
from adafruit_adxl34x import ADXL345
14+
from adafruit_lc709203f import LC709203F, PackSize
15+
16+
17+
try:
18+
from secrets import secrets
19+
except ImportError:
20+
print("WiFi and Adafruit IO credentials are kept in secrets.py - please add them there!")
21+
raise
22+
23+
aio_username = secrets["aio_username"]
24+
aio_key = secrets["aio_key"]
25+
26+
# Wi-Fi
27+
try:
28+
print("Connecting to %s" % secrets["ssid"])
29+
wifi.radio.connect(secrets["ssid"], secrets["password"])
30+
print("Connected to %s!" % secrets["ssid"])
31+
# Wi-Fi connectivity fails with error messages, not specific errors, so this except is broad.
32+
except Exception as e: # pylint: disable=broad-except
33+
print("Failed to connect to WiFi. Error:", e, "\nBoard will hard reset in 5 seconds.")
34+
time.sleep(5)
35+
microcontroller.reset()
36+
37+
# Create a socket pool
38+
pool = socketpool.SocketPool(wifi.radio)
39+
40+
# Initialize a new MQTT Client object
41+
mqtt_client = MQTT.MQTT(
42+
broker="io.adafruit.com",
43+
username=secrets["aio_username"],
44+
password=secrets["aio_key"],
45+
socket_pool=pool,
46+
ssl_context=ssl.create_default_context(),
47+
)
48+
49+
# Initialize Adafruit IO MQTT "helper"
50+
io = IO_MQTT(mqtt_client)
51+
52+
try:
53+
# If Adafruit IO is not connected...
54+
if not io.is_connected:
55+
# Connect the client to the MQTT broker.
56+
print("Connecting to Adafruit IO...")
57+
io.connect()
58+
print("Connected to Adafruit IO!")
59+
except Exception as e: # pylint: disable=broad-except
60+
print("Failed to get or send data, or connect. Error:", e,
61+
"\nBoard will hard reset in 30 seconds.")
62+
time.sleep(30)
63+
microcontroller.reset()
64+
65+
threshold = 25 # set threshold value here
66+
time_interval = 0.5 # set the time interval in seconds
67+
68+
# create the I2C bus object
69+
i2c = board.STEMMA_I2C()
70+
# For ADXL345
71+
accelerometer = ADXL345(i2c)
72+
73+
battery_monitor = LC709203F(i2c)
74+
battery_monitor.pack_size = PackSize.MAH400
75+
76+
t0 = time.monotonic()
77+
78+
while True:
79+
x, y, z = accelerometer.acceleration
80+
t1 = time.monotonic()
81+
dt = t1 - t0
82+
83+
total_acceleration = math.sqrt(x**2 + y**2 + z**2)
84+
if total_acceleration >= threshold:
85+
print("Battery Percent: {:.2f} %".format(battery_monitor.cell_percent))
86+
print("Collision strength: %.2f" % total_acceleration)
87+
io.publish("punch-strength", total_acceleration)
88+
89+
# add code here to trigger an event or alert the user
90+
t0 = t1
91+
time.sleep(time_interval)

CPX_Simple_Simon/code.py

Lines changed: 59 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import math
1515
import board
1616
from analogio import AnalogIn
17-
from adafruit_circuitplayground.express import cpx
17+
from adafruit_circuitplayground import cp
1818

1919
FAILURE_TONE = 100
2020
SEQUENCE_DELAY = 0.8
@@ -30,56 +30,51 @@
3030
1 : { 'pads':(4,5), 'pixels':(0,1,2), 'color':0x00FF00, 'freq':415 },
3131
2 : { 'pads':(6,7), 'pixels':(2,3,4), 'color':0xFFFF00, 'freq':252 },
3232
3 : { 'pads':(1, ), 'pixels':(5,6,7), 'color':0x0000FF, 'freq':209 },
33-
4 : { 'pads':(2,3), 'pixels':(7,8,9), 'color':0xFF0000, 'freq':310 },
33+
4 : { 'pads':(2,3), 'pixels':(7,8,9), 'color':0xFF0000, 'freq':310 },
3434
}
3535

3636
def choose_skill_level():
3737
# Default
3838
skill_level = 1
3939
# Loop until button B is pressed
40-
while not cpx.button_b:
40+
while not cp.button_b:
4141
# Button A increases skill level setting
42-
if cpx.button_a:
42+
if cp.button_a:
4343
skill_level += 1
4444
skill_level = skill_level if skill_level < 5 else 1
4545
# Indicate current skill level
46-
cpx.pixels.fill(0)
46+
cp.pixels.fill(0)
4747
for p in range(skill_level):
48-
cpx.pixels[p] = 0xFFFFFF
48+
cp.pixels[p] = 0xFFFFFF
4949
time.sleep(DEBOUNCE)
5050
return skill_level
5151

5252
def new_game(skill_level):
5353
# Seed the random function with noise
54-
a4 = AnalogIn(board.A4)
55-
a5 = AnalogIn(board.A5)
56-
a6 = AnalogIn(board.A6)
57-
a7 = AnalogIn(board.A7)
54+
with AnalogIn(board.A4) as a4, AnalogIn(board.A5) as a5, AnalogIn(board.A6) as a6:
55+
seed = a4.value
56+
seed += a5.value
57+
seed += a6.value
5858

59-
seed = a4.value
60-
seed += a5.value
61-
seed += a6.value
62-
seed += a7.value
59+
random.seed(seed)
6360

64-
random.seed(seed)
65-
66-
# Populate the game sequence
67-
return [random.randint(1,4) for i in range(SEQUENCE_LENGTH[skill_level])]
61+
# Populate the game sequence
62+
return [random.randint(1,4) for i in range(SEQUENCE_LENGTH[skill_level])]
6863

6964
def indicate_button(button, duration):
7065
# Turn them all off
71-
cpx.pixels.fill(0)
66+
cp.pixels.fill(0)
7267
# Turn on the ones for the given button
7368
for p in button['pixels']:
74-
cpx.pixels[p] = button['color']
69+
cp.pixels[p] = button['color']
7570
# Play button tone
7671
if button['freq'] == None:
7772
time.sleep(duration)
7873
else:
79-
cpx.play_tone(button['freq'], duration)
74+
cp.play_tone(button['freq'], duration)
8075
# Turn them all off again
81-
cpx.pixels.fill(0)
82-
76+
cp.pixels.fill(0)
77+
8378
def show_sequence(sequence, step):
8479
# Set tone playback duration based on current location
8580
if step <= 5:
@@ -88,21 +83,21 @@ def show_sequence(sequence, step):
8883
duration = 0.320
8984
else:
9085
duration = 0.220
91-
86+
9287
# Play back sequence up to current step
9388
for b in range(step):
9489
time.sleep(0.05)
95-
indicate_button(SIMON_BUTTONS[sequence[b]], duration)
90+
indicate_button(SIMON_BUTTONS[sequence[b]], duration)
9691

9792
def cap_map(b):
98-
if b == 1: return cpx.touch_A1
99-
if b == 2: return cpx.touch_A2
100-
if b == 3: return cpx.touch_A3
101-
if b == 4: return cpx.touch_A4
102-
if b == 5: return cpx.touch_A5
103-
if b == 6: return cpx.touch_A6
104-
if b == 7: return cpx.touch_A7
105-
93+
if b == 1: return cp.touch_A1
94+
if b == 2: return cp.touch_A2
95+
if b == 3: return cp.touch_A3
96+
if b == 4: return cp.touch_A4
97+
if b == 5: return cp.touch_A5
98+
if b == 6: return cp.touch_A6
99+
if b == 7: return cp.touch_TX
100+
106101
def get_button_press():
107102
# Loop over all the buttons
108103
for button in SIMON_BUTTONS.values():
@@ -115,74 +110,74 @@ def get_button_press():
115110

116111
def game_lost(step):
117112
# Show button that should have been pressed
118-
cpx.pixels.fill(0)
113+
cp.pixels.fill(0)
119114
for p in SIMON_BUTTONS[sequence[step]]['pixels']:
120-
cpx.pixels[p] = SIMON_BUTTONS[sequence[step]]['color']
121-
115+
cp.pixels[p] = SIMON_BUTTONS[sequence[step]]['color']
116+
122117
# Play sad sound :(
123-
cpx.play_tone(FAILURE_TONE, 1.5)
124-
118+
cp.play_tone(FAILURE_TONE, 1.5)
119+
125120
# And just sit here until reset
126121
while True:
127122
pass
128-
123+
129124
def game_won():
130125
# Play 'razz' special victory signal
131126
for i in range(3):
132-
indicate_button(SIMON_BUTTONS[4], 0.1)
133-
indicate_button(SIMON_BUTTONS[2], 0.1)
134-
indicate_button(SIMON_BUTTONS[3], 0.1)
135-
indicate_button(SIMON_BUTTONS[1], 0.1)
136-
indicate_button(SIMON_BUTTONS[4], 0.1)
127+
indicate_button(SIMON_BUTTONS[4], 0.1)
128+
indicate_button(SIMON_BUTTONS[2], 0.1)
129+
indicate_button(SIMON_BUTTONS[3], 0.1)
130+
indicate_button(SIMON_BUTTONS[1], 0.1)
131+
indicate_button(SIMON_BUTTONS[4], 0.1)
137132
indicate_button(SIMON_BUTTONS[2], 0.1)
138133

139134
# Change tones to failure tone
140135
for button in SIMON_BUTTONS.values():
141136
button['freq'] = FAILURE_TONE
142-
137+
143138
# Continue for another 0.8 seconds
144139
for i in range(2):
145-
indicate_button(SIMON_BUTTONS[3], 0.1)
146-
indicate_button(SIMON_BUTTONS[1], 0.1)
147-
indicate_button(SIMON_BUTTONS[4], 0.1)
148-
indicate_button(SIMON_BUTTONS[2], 0.1)
149-
140+
indicate_button(SIMON_BUTTONS[3], 0.1)
141+
indicate_button(SIMON_BUTTONS[1], 0.1)
142+
indicate_button(SIMON_BUTTONS[4], 0.1)
143+
indicate_button(SIMON_BUTTONS[2], 0.1)
144+
150145
# Change tones to silence
151146
for button in SIMON_BUTTONS.values():
152147
button['freq'] = None
153-
148+
154149
# Loop lights forever
155150
while True:
156-
indicate_button(SIMON_BUTTONS[3], 0.1)
157-
indicate_button(SIMON_BUTTONS[1], 0.1)
158-
indicate_button(SIMON_BUTTONS[4], 0.1)
159-
indicate_button(SIMON_BUTTONS[2], 0.1)
160-
161-
# Initialize setup
162-
cpx.pixels.fill(0)
163-
cpx.pixels[0] = 0xFFFFFF
151+
indicate_button(SIMON_BUTTONS[3], 0.1)
152+
indicate_button(SIMON_BUTTONS[1], 0.1)
153+
indicate_button(SIMON_BUTTONS[4], 0.1)
154+
indicate_button(SIMON_BUTTONS[2], 0.1)
155+
156+
# Initialize setup
157+
cp.pixels.fill(0)
158+
cp.pixels[0] = 0xFFFFFF
164159
skill_level = choose_skill_level()
165160
sequence = new_game(skill_level)
166161
current_step = 1
167162

168-
#Loop forever
163+
# Loop forever
169164
while True:
170165
# Show sequence up to current step
171166
show_sequence(sequence, current_step)
172-
167+
173168
# Read player button presses
174169
for step in range(current_step):
175170
start_guess_time = time.monotonic()
176171
guess = None
177172
while (time.monotonic() - start_guess_time < GUESS_TIMEOUT) and (guess == None):
178173
guess = get_button_press()
179174
if not guess == SIMON_BUTTONS[sequence[step]]:
180-
game_lost(sequence[step])
175+
game_lost(step)
181176

182177
# Advance the game forward
183178
current_step += 1
184179
if current_step > len(sequence):
185180
game_won()
186-
187-
# Small delay before continuing
181+
182+
# Small delay before continuing
188183
time.sleep(SEQUENCE_DELAY)

CircuitPython_Mastodon_API_Examples/Read_From_Mastodon/code.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
hashtag = "CircuitPython"
1515

1616
# connect to SSID
17-
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
17+
wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
1818

1919
# add your mastodon token as 'mastodon_token' to your settings.toml file
2020
headers = {'Authorization': 'Bearer ' + os.getenv('mastodon_token') + 'read:statuses'}

CircuitPython_Mastodon_API_Examples/Send_To_Mastodon/code.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
url = 'https://' + os.getenv('mastodon_host') + '/api/v1/statuses'
1515

1616
# connect to SSID
17-
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
17+
wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
1818

1919
pool = socketpool.SocketPool(wifi.radio)
2020
requests = adafruit_requests.Session(pool, ssl.create_default_context())
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# SPDX-FileCopyrightText: 2023 Jeff Epler for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
import board
4+
import digitalio
5+
import rotaryio
6+
from adafruit_hid.mouse import Mouse
7+
from usb_hid import devices
8+
9+
SCALE = 4
10+
11+
class RelativeEncoder:
12+
def __init__(self, pin_a, pin_b, divisor=1):
13+
self._encoder = rotaryio.IncrementalEncoder(pin_a, pin_b, divisor)
14+
self._old = self._encoder.position
15+
16+
@property
17+
def delta(self):
18+
old = self._old
19+
new = self._old = self._encoder.position
20+
return new - old
21+
22+
xpos = RelativeEncoder(board.A0, board.A1)
23+
ypos = RelativeEncoder(board.A2, board.A3)
24+
lmb = digitalio.DigitalInOut(board.SCL)
25+
lmb.pull = digitalio.Pull.UP
26+
rmb = digitalio.DigitalInOut(board.SDA)
27+
rmb.pull = digitalio.Pull.UP
28+
29+
mouse = Mouse(devices)
30+
31+
while True:
32+
dx = xpos.delta * SCALE
33+
dy = ypos.delta * SCALE
34+
l = not lmb.value
35+
r = not rmb.value
36+
mouse.report[0] = (
37+
mouse.MIDDLE_BUTTON if (l and r) else
38+
mouse.LEFT_BUTTON if l else
39+
mouse.RIGHT_BUTTON if r else
40+
0)
41+
42+
if dx or dy:
43+
mouse.move(dx, dy)
44+
else:
45+
mouse._send_no_move() # pylint: disable=protected-access

0 commit comments

Comments
 (0)