Pyserial write stopped working, just hangs

Hello,

I have two Leonard boards. Out of the box, I was able to run the code below from LabHackers to test the USB roundtrip latency via pyserial. However, after playing around a bit with the digitalwrite function within the Arduino IDE, I can't get pyserial to write anything to the arduino. It just hangs forever on the write() call. If I add the write_timeout argument, to the serial.Serial call, it will time out. This is happening on my two boards with multiple computers/OS, USB ports, cables, etc. Any idea what is happening? Thank you!

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function

import serial
import numpy
from timeit import default_timer as getTime
import time

SERIAL_PORT = '/dev/ttyACM2'
ITERATION_COUNT = 100


try:
    sconn = serial.Serial(SERIAL_PORT, baudrate=128000,
                          timeout=0.1, write_timeout=1)
except serial.SerialException as e:
    print("Check SERIAL_PORT variable is correct for device being tested.")
    raise e
time.sleep(2)  # 2 seconds or possibly a bit less

# clear anything in serial rx
while sconn.readline():
    pass

# Test time it takes to send a serial message to the labhackers device
# and receive the serial reply.
results = numpy.zeros(ITERATION_COUNT, dtype=numpy.float64)
for i in range(ITERATION_COUNT):
    print(i)
    tx_time = getTime()
    sconn.write(b"PING")
    r = sconn.readline()
    rx_time = getTime()
    if r:
        results[i] = rx_time-tx_time
    else:
        raise RuntimeError("Serial RX Timeout.")

sconn.close()

# Convert times to msec.
results = results * 1000.0

print("LabHackers' USB Serial Rx - Tx Latency Stats")
print("\tCount: {}".format(results.shape))
print("\tAverage: {:.3f} msec".format(results.mean()))
print("\tMedian: {:.3f} msec".format(numpy.median(results)))
print("\tMin: {:.3f} msec".format(results.min()))
print("\tMax: {:.3f} msec".format(results.max()))
print("\tStdev: {:.3f} msec".format(results.std()))

Should have a colon after the except and an indentation and new line for the rest of that line.

Where is the Arduino code on the receiving end?

Have you tried a system reset on the Leonardo with a double click on the reset button?

Each time you open the serial port the Arduino will be reset. It is best to open it at the start and only close it at the end of the Python code.

This looks okay to me if the intention is to only catch exceptions of type SerialException.

Hey, indeed the Arduino side was not running what I thought it was running. Thanks for making me double-check again!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.