Working sender code:
import wifi
import socketpool
import time
import board
import busio
import adafruit_bno08x
from adafruit_bno08x.i2c import BNO08X_I2C
from adafruit_bno08x import (
BNO_REPORT_ACCELEROMETER,
BNO_REPORT_GYROSCOPE,
BNO_REPORT_MAGNETOMETER,
BNO_REPORT_ROTATION_VECTOR,
)
import adafruit_requests
AP credentials
SSID = ‘PicoW_AP’
PASSWORD = ‘12345678’
Connect to the AP
wifi.radio.connect(SSID, PASSWORD)
print(“Connected to AP, IP address:”, wifi.radio.ipv4_address)
Server address (AP’s IP address)
SERVER_IP = ‘192.168.4.1’ # Default IP for Pico W AP
SERVER_PORT = 12345
Function definitions
def quaternion_to_rotation_matrix(w, x, y, z):
r = [[0]3 for _ in range(3)]
r[0][0] = 1 - 2(yy + zz)
r[0][1] = 2*(xy - wz)
r[0][2] = 2*(xz + wy)
r[1][0] = 2*(xy + wz)
r[1][1] = 1 - 2*(xx + zz)
r[1][2] = 2*(yz - wx)
r[2][0] = 2*(xz - wy)
r[2][1] = 2*(yz + wx)
r[2][2] = 1 - 2*(xx + yy)
return r
def rotate_vector_by_matrix(vector, matrix):
result = [0]*3
for i in range(3):
for j in range(3):
result[i] += vector[j] * matrix[j][i]
return result
def get_compass_direction(rotated_x, rotated_y):
angle_rad = math.atan2(rotated_y, rotated_x)
angle_deg = math.degrees(angle_rad)
if angle_deg < 0:
angle_deg += 360
compass_direction = (90 - angle_deg) % 360
return compass_direction
Initialize IMU
i2c = busio.I2C(board.GP27, board.GP26, frequency=800000)
bno = BNO08X_I2C(i2c, address=0x4A)
bno.enable_feature(BNO_REPORT_ACCELEROMETER)
bno.enable_feature(BNO_REPORT_GYROSCOPE)
bno.enable_feature(BNO_REPORT_MAGNETOMETER)
bno.enable_feature(BNO_REPORT_ROTATION_VECTOR)
Set up the client socket
pool = socketpool.SocketPool(wifi.radio)
sock = pool.socket(pool.AF_INET, pool.SOCK_STREAM)
sock.connect((SERVER_IP, SERVER_PORT))
while True:
quat_i, quat_j, quat_k, quat_real = bno.quaternion
rotation_matrix = quaternion_to_rotation_matrix(quat_real, quat_i, quat_j, quat_k)
unit_x = [1, 0, 0]
unit_y = [0, 1, 0]
unit_z = [0, 0, 1]
rotated_x = rotate_vector_by_matrix(unit_x, rotation_matrix)[0]
rotated_y = rotate_vector_by_matrix(unit_y, rotation_matrix)[0]
rotated_z = rotate_vector_by_matrix(unit_z, rotation_matrix)[0]
message = "Values: X: {:.2f}, Y: {:.2f}, Z: {:.2f}".format(rotated_x, rotated_y, rotated_z)
print(message)
sock.send(message.encode())