import time from serial import Serial from serial.tools import list_ports from serial_sync import SerialSync BAUDRATE = 115200 SERIAL_TIMEOUT = 1.0 CALIBRATION_PERIOD_S = 30.0 def choose_serial_port() -> str: ports = list(list_ports.comports()) if not ports: raise RuntimeError("No serial ports found") print("Available serial ports:") for index, port in enumerate(ports): print(f"{index}: {port.device} ({port.description})") while True: try: choice = int(input("Choose a port: ")) if 0 <= choice < len(ports): return ports[choice].device except ValueError: pass print("Invalid choice, try again.") def main() -> None: try: port = choose_serial_port() print() print(f"Opening {port} at {BAUDRATE} baud...") with Serial( port=port, baudrate=BAUDRATE, timeout=SERIAL_TIMEOUT, ) as serial: # # Opening the serial port may reset an Arduino, # so allow it to boot before calibration. # print("Waiting for Arduino to start...") time.sleep(5) sync = SerialSync(serial) print() print(f"Calibrating for {CALIBRATION_PERIOD_S:.1f} seconds...") sync.calibrate_sync(CALIBRATION_PERIOD_S) print() print("Synchronization complete") print("------------------------") print(f"Scale: {sync._scale:.12f}") print(f"Offset: {sync._offset:.0f} ns") print(f"Offset: {sync._offset / 1_000_000:.6f} ms") except KeyboardInterrupt: print("\nInterrupted.") except Exception as exc: print(f"\nError: {exc}") if __name__ == "__main__": main()