import serial import time import csv # ser = serial.Serial('/dev/cu.SLAB_USBtoUART', baudrate=115200) ser = serial.Serial('/dev/cu.usbmodem1462201', baudrate=115200) time.sleep(1) # while True: # try: # ser.flushInput() # ser_bytes = str(ser.readline()) # useful = ser_bytes.split('\\')[0].split('\'')[1].split('|') # heading = float(useful[1]) # mag_data_raw = useful[3].split(';') # mag_raw_x = float(mag_data_raw[0]) # mag_raw_y = float(mag_data_raw[1]) # mag_raw_z = float(mag_data_raw[2]) # print(f"Heading: {heading}, MAG_X: {mag_raw_x}, MAG Y: {mag_raw_y}, MAG Z: {mag_raw_z}") # except Exception as e: # print(f"Error: {e}") def start_recording(): min_x = 100 max_x = -100 min_y = 100 max_y = -100 csvfile = open('results.csv', 'w', newline='') csvwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) csvwriter.writerow(['time', 'x', 'y', 'z']) print("Starting recording for 30s.") end_time = time.time() + 30 while time.time() < end_time: taking_measurement_end = time.time() + 0.01 try: ser.flushInput() ser_bytes = str(ser.readline()) useful = ser_bytes.split('\\')[0].split('\'')[1] mag_data_raw = useful.split(';') mag_raw_x = float(mag_data_raw[0]) mag_raw_y = float(mag_data_raw[1]) mag_raw_z = float(mag_data_raw[2]) if mag_raw_x < min_x: min_x = mag_raw_x if mag_raw_x > max_x: max_x = mag_raw_x if mag_raw_y < min_y: min_y = mag_raw_y if mag_raw_y > max_y: max_y = mag_raw_y csvwriter.writerow([time.time(), mag_raw_x, mag_raw_y, mag_raw_z]) while time.time() < taking_measurement_end: pass except Exception as e: print(f"Encountered exception: {e}") continue print("Done") print(f"Min x: {min_x}, max x: {max_x}, min y: {min_y}, max y: {max_y}") start_recording() # while True: # try: # ser.flushInput() # ser_bytes = str(ser.readline()) # useful = ser_bytes.split('\\')[0].split('\'')[1] # mag_data_raw = useful.split(';') # mag_raw_x = float(mag_data_raw[0]) # mag_raw_y = float(mag_data_raw[1]) # mag_raw_z = float(mag_data_raw[2]) # print(f"MAG_X: {mag_raw_x}, MAG Y: {mag_raw_y}, MAG Z: {mag_raw_z}") # except Exception as e: # print(f"Error: {e}")