diff --git a/motor_test.py b/motor_test.py index 3084a50..0c43fcd 100644 --- a/motor_test.py +++ b/motor_test.py @@ -25,6 +25,7 @@ class Driver: self.msgs = 0 self.other = [] # last few lines that weren't $MAll, for debugging self.alive = True + self.error = None # set if the serial port fails in the reader thread threading.Thread(target=self._rx, daemon=True).start() self.send("$pwm:0,0,0,0#") self.send("$mtype:1#") # 1 = Yahboom 520 motor @@ -51,7 +52,11 @@ class Driver: def _rx(self): buf = b"" while self.alive: - buf += self.ser.read(self.ser.in_waiting or 1) + try: + buf += self.ser.read(self.ser.in_waiting or 1) + except serial.SerialException as e: + self.error = str(e) + return while b"#" in buf: line, buf = buf.split(b"#", 1) i = line.rfind(b"$") @@ -78,6 +83,8 @@ def hold(d, ch, value, seconds): """Keep re-sending the PWM so it holds even if the board has a command timeout.""" end = time.perf_counter() + seconds while time.perf_counter() < end: + if d.error: + sys.exit(f"\nSerial error: {d.error}") d.pwm(ch, value) time.sleep(0.1) @@ -88,6 +95,8 @@ def hand(d): print("Turn ONE wheel by hand, one full turn FORWARD (as if the robot drives toward the tape).") print("Then the other wheel. Ctrl-C when done.\n") while True: + if d.error: + sys.exit(f"\nSerial error: {d.error}") t, n, _ = d.get() m3 = t[2] - base[2] m4 = t[3] - base[3] @@ -102,15 +111,17 @@ def spin(d): print(f"\n--- {name} ---") for p in SPIN_STEPS: hold(d, ch, p, 0.5) # let it spin up - t0, _, _ = d.get(); s0 = time.perf_counter() + t0, n0, _ = d.get(); s0 = time.perf_counter() hold(d, ch, p, 1.0) # measure over 1 s - t1, _, _ = d.get(); s1 = time.perf_counter() + t1, n1, other = d.get(); s1 = time.perf_counter() cps = (t1[ch] - t0[ch]) / (s1 - s0) rpm = cps / TICKS_PER_REV * 60 - print(f"pwm {p:+5d} -> {cps:+8.0f} counts/s {rpm:+6.1f} wheel rpm") + print(f"pwm {p:+5d} -> {cps:+8.0f} counts/s {rpm:+6.1f} wheel rpm {n1 - n0:4d} msgs") d.stop() time.sleep(1.0) - print("\nDone.") + _, _, other = d.get() + print("\nnon-encoder lines from the board:", other if other else "none") + print("Done.") def main():