Nov-10-2021, 06:16 PM
(This post was last modified: Nov-10-2021, 06:16 PM by deanhystad.)
Serial expects data to be bytes and you give it a str. I am surprised this didn't raise an exception. What version of Python are you using? In pre-3.0 Python str and bytes were the same. Now str is made up of unicode characters.
This is some serial code I extracted from a recent project. I did some editing, so this code may not run as is.
This is some serial code I extracted from a recent project. I did some editing, so this code may not run as is.
import serial class SerialDevice(): def __init__(self, port_name='COM1', baudrate=19200, timeout=0.1): self.port = serial.Serial() self.port.port = port_name self.port.baudrate = baudrate self.port.timeout = timeout def open(self, port_name=None, baudrate=None, timeout=None): if port_name is not None: self.port.port = port_name if baudrate is not None: self.port.baudrate = baudrate if timeout is not None: self.port.timeout = timeout self.close() self.port.open() if not self.port.is_open: raise IOError(f'Open failed on port {self.port.port}') def close(self): if self.port.is_open: self.port.close() def send_cmd(self, command): """Send command and read reply""" if not self.port.is_open: raise IOError('Port is not open') self.port.write(f'{command}\r'.encode()) reply = self.port.read_until(b'\r') # My device uses /r as a terminator if not reply: raise IOError('Read timeout error') return reply.decode()The main things you are missing are encoding the strs to bytes before sending/writing with a corresponding decoding on the other side, and a timeout. Every serial program that uses read (and especially readline) should specify a timeout.