Skip to content

Instantly share code, notes, and snippets.

@kevinlinxc
Created February 4, 2024 04:00
Show Gist options
  • Save kevinlinxc/e7481883265454284905f068df6f1811 to your computer and use it in GitHub Desktop.
Save kevinlinxc/e7481883265454284905f068df6f1811 to your computer and use it in GitHub Desktop.
Serial Sender
import serial
import serial.tools.list_ports
def get_ports():
"""
Get a list of available serial ports.
Returns:
List of serial ports, or None if no ports are available.
"""
serial_ports = serial.tools.list_ports.comports()
if not serial_ports:
print("No serial ports available.")
return None
return serial_ports
def select_serial_port(ports, preset_port=None):
"""
Terminal UI for selecting a serial port. If you pass in a valid port name as preset_port, it will be
selected automatically, so you only have to set it once per computer by changing preset_port.
"""
if preset_port in [port.device for port in ports]:
return preset_port
elif preset_port is not None:
print(f"{preset_port} is not a valid serial port: {ports}")
print("Available serial ports:")
for idx, port in enumerate(ports, start=1):
print(f"{idx}: {port.device}")
selection = input("Enter the number of the serial port you want to use: ")
try:
selection = int(selection)
if 1 <= selection <= len(ports):
selected_port = ports[selection - 1].device
print(f"Selected port: {selected_port}")
return selected_port
else:
print("Invalid selection. Please enter a valid number.")
exit(1)
except ValueError:
print("Invalid input. Please enter a number.")
exit(1)
if __name__ == '__main__':
ports = get_ports()
port = select_serial_port(ports)
ser = serial.Serial(port, 57600)
while True:
input_1 = input("Enter a command: ")
ser.write(input_1.encode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment