-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep_pi_sender.py
102 lines (94 loc) · 3.17 KB
/
step_pi_sender.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import sys
import time
from typing import Optional
import evdev
from evdev import ecodes
from serial import Serial
def get_board_device() -> Optional[evdev.InputDevice]:
""" Return the Wii Balance Board device. """
devices = [
path
for path in evdev.list_devices()
if evdev.InputDevice(path).name == "Nintendo Wii Remote Balance Board"
]
if not devices:
return None
board = evdev.InputDevice(
devices[0],
)
return board
def get_raw_measurement(device: evdev.InputDevice):
"""
Read one measurement from the board.
Code is based on:
https://github.com/jmahmood/bbev/tree/main
https://pypi.org/project/weii/0.1.1/
"""
data = [None] * 4
length = 228
width = 433
tries = 50
while True:
event = device.read_one()
if event is None:
continue
# Measurements are in decigrams, so we convert them to kilograms here.
if event.code == ecodes.ABS_HAT1X:
# Top left.
data[0] = event.value
elif event.code == ecodes.ABS_HAT0X:
# Top right.
data[1] = event.value
elif event.code == ecodes.ABS_HAT0Y:
# Bottom left.
data[2] = event.value
elif event.code == ecodes.ABS_HAT1Y:
# Bottom right.
data[3] = event.value
elif event.code == ecodes.BTN_A:
sys.exit("ERROR: User pressed board button while measuring, aborting.")
elif event.code == ecodes.SYN_DROPPED:
pass
elif event.code == ecodes.SYN_REPORT and event.value == 3:
pass
elif event.code == ecodes.SYN_REPORT and event.value == 0:
if None in data:
if tries == 0:
time.sleep(1)
tries += 15
else:
tries -= 1
# This measurement failed to read one of the sensors, try again.
data = [None] * 4
continue
else:
# calculate x and y cop coordinates in mm
x_cop = width/2 * (data[1] + data[2] - data[0] - data[3]) / sum(data)
y_cop = length/2 * (data[0] + data[1] - data[2] - data[3]) / sum(data)
return [x_cop, y_cop]
else:
print(f"ERROR: Got unexpected event: {evdev.categorize(event)}")
if __name__ == "__main__":
print("Waiting for board...")
boardfound = None
while not boardfound:
boardfound = get_board_device()
if boardfound:
print("Board found!")
break
time.sleep(1)
print("Opening serial port...")
with Serial('/dev/ttyGS0', 9600, timeout=1) as ser:
print(f"Serial port {ser.name} opened.")
while True:
try:
data = get_raw_measurement(boardfound)
except Exception as e:
print("Exception, closing serial port...")
break
data = [round(i, 4) for i in data]
ser.reset_output_buffer()
ser.write(f"{str(data)}\n".encode())
time.sleep(0.01)
print(f"Serial port {ser.name} closed.")
print("Exiting...")