Skip to content

Commit 781c710

Browse files
Fix joystick angle
1 parent 63850c7 commit 781c710

File tree

1 file changed

+41
-9
lines changed

1 file changed

+41
-9
lines changed

internal_filesystem/boot_fri3d-2024.py

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import machine
66
import cst816s
77
import i2c
8+
import math
89

910
import lvgl as lv
1011
import task_handler
@@ -117,6 +118,34 @@ def read_joystick():
117118
return mapping['key']
118119
return None # No key triggered
119120

121+
# Rotate: UP = 0°, RIGHT = 90°, DOWN = 180°, LEFT = 270°
122+
def read_joystick_angle(threshold=0.1):
123+
# Read ADC values
124+
val_up_down = adc_up_down.read()
125+
val_left_right = adc_left_right.read()
126+
127+
if time.time() < 60:
128+
print(f"val_up_down: {val_up_down}")
129+
print(f"val_left_right: {val_left_right}")
130+
131+
# Normalize to [-1, 1]
132+
x = (val_left_right - 2048) / 2048 # Positive x = RIGHT
133+
y = (val_up_down - 2048) / 2048 # Positive y = UP
134+
if time.time() < 60:
135+
print(f"x,y = {x},{y}")
136+
137+
# Check if joystick is near center
138+
magnitude = math.sqrt(x*x + y*y)
139+
if time.time() < 60:
140+
print(f"magnitude: {magnitude}")
141+
if magnitude < threshold:
142+
return None # Neutral position
143+
144+
# Calculate angle in degrees with UP = 0°, clockwise
145+
angle_rad = math.atan2(-x, y)
146+
angle_deg = math.degrees(angle_rad)
147+
angle_deg = (angle_deg + 360) % 360 # Normalize to [0, 360)
148+
return angle_deg
120149

121150
# Key repeat configuration
122151
# This whole debounce logic is only necessary because LVGL 9.2.2 seems to have an issue where
@@ -155,15 +184,18 @@ def keypad_read_cb(indev, data):
155184
current_key = lv.KEY.END
156185
else:
157186
# Check joystick
158-
joystick = read_joystick()
159-
if joystick == "LEFT":
160-
current_key = lv.KEY.LEFT
161-
elif joystick == "RIGHT":
162-
current_key = lv.KEY.RIGHT
163-
elif joystick == "UP":
164-
current_key = lv.KEY.UP
165-
elif joystick == "DOWN":
166-
current_key = lv.KEY.DOWN
187+
joystick = read_joystick_angle(0.25)
188+
if joystick:
189+
if time.time() < 60:
190+
print(f"joystick angle: {joystick}")
191+
if joystick == "LEFT":
192+
current_key = lv.KEY.LEFT
193+
elif joystick == "RIGHT":
194+
current_key = lv.KEY.RIGHT
195+
elif joystick == "UP":
196+
current_key = lv.KEY.UP
197+
elif joystick == "DOWN":
198+
current_key = lv.KEY.DOWN
167199

168200
# Key repeat logic
169201
if current_key:

0 commit comments

Comments
 (0)