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