slidecommander.py (2292B)
1 import serial 2 import serial.tools.list_ports 3 import time 4 5 def list_serial_ports(): 6 # Get a list of all serial ports 7 ports = serial.tools.list_ports.comports() 8 # Print the available ports 9 if not ports: 10 print("No serial ports found.") 11 else: 12 print("Available serial ports:") 13 for port in ports: 14 print(f"{port.device} - {port.description}") 15 return port.device 16 17 def listen_serial_port(serial_port): 18 baud_rate = 57600# Set the baud rate according to your device 19 # Create a serial connection 20 try: 21 ser = serial.Serial(serial_port, baud_rate, timeout=1) 22 print(f"Connected to {serial_port} at {baud_rate} baud.") 23 except serial.SerialException as e: 24 print(f"Error: {e}") 25 exit() 26 # Give some time for the connection to establish 27 time.sleep(0) 28 # Read data from the serial port 29 try: 30 while True: 31 if ser.in_waiting > 0: # Check if there is data waiting to be read 32 received_data = ser.readline().decode('utf-8').strip() # Read a line and decode 33 print(f"Received: {received_data}") 34 except KeyboardInterrupt: 35 print("Exiting...") 36 finally: 37 # Close the serial connection 38 ser.close() 39 print("Serial connection closed.") 40 41 def send_serial_port(serial_port,msg): 42 baud_rate = 57600 # Set the baud rate according to your device 43 # Create a serial connection 44 try: 45 ser = serial.Serial(serial_port, baud_rate, timeout=1) 46 print(f"Connected to {serial_port} at {baud_rate} baud.") 47 except serial.SerialException as e: 48 print(f"Error: {e}") 49 exit() 50 51 # Give some time for the connection to establish 52 53 # Write data to the serial port 54 data_to_send = msg # Add a newline if needed 55 try: 56 ser.write(data_to_send.encode('utf-8')) # Encode the string to bytes 57 print(f"Sent: {data_to_send.strip()}") 58 except Exception as e: 59 print(f"Error while sending data: {e}") 60 61 # Close the serial connection 62 ser.close() 63 print("Serial connection closed.") 64 65 if __name__ == "__main__": 66 port = list_serial_ports() 67 while True: 68 user_input = input("slidecommando: ") 69 send_serial_port(port,user_input) 70