Apr-07-2021, 10:34 PM
I don't know if there's anything useful in the following code, but perhaps.
I wrote it to connect to an Arduino UNO, some of the code (commented) was from a github account, some of my own.
I wrote it to connect to an Arduino UNO, some of the code (commented) was from a github account, some of my own.
# ArduinoSerial.py # Author: Larz60+ # Detect available serial ports, open and close same # License MIT license see MIT_license.txt # from ArPaths import ArPaths import sys import glob import serial class ArduinoSerial: def __init__(self, baudrate=9600, serialport=None, serialtimeout=2, sstream=None): self.Apath = ArPaths() self.baud = baudrate self.port = serialport self.timeout = serialtimeout self.sstream = sstream def setport(self): if self.port is None: ports = glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") print(f"ports: {ports}") self.port = ports[0] def OpenSerialPort(self): self.setport() print(f"self.port: {self.port}") self.sstream = serial.Serial(self.port, self.baud, timeout=self.timeout) print(f"self.sstream: {self.sstream}") return self.sstream def CloseSerialPort(self): self.sstream.close() def find_serial_ports(self): """ Source for this code: https://gist.github.com/tekk/5c8d6824108dfb771a1e16aa8bc479f0 Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result def main(): aser = ArduinoSerial() ports = aser.find_serial_ports() print(f"Ports (find): {ports}") aser.OpenSerialPort() aser.CloseSerialPort() if __name__ == '__main__': main()output of internal test:
Output:Ports (find): ['/dev/ttyACM0']
ports: ['/dev/ttyACM0']
self.port: /dev/ttyACM0
self.sstream: Serial<id=0x7faf12c0b0a0, open=True>(port='/dev/ttyACM0', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2, xonxoff=False, rtscts=False, dsrdtr=False)