import serial
import time

# Configuration
COM_PORT = "COM7"  # Change this to your actual COM port
BAUD_RATE = 115200
DATA_BITS = 8
PARITY = 'N'       # N = None, E = Even, O = Odd
STOP_BITS = 1

# Data to send (8 characters)
data_to_send = "12345678"

def main():
    try:
        # Open serial port
        ser = serial.Serial(
            port=COM_PORT,
            baudrate=BAUD_RATE,
            bytesize=DATA_BITS,
            parity=PARITY,
            stopbits=STOP_BITS,
            timeout=1
        )

        print(f"Opened {COM_PORT} at {BAUD_RATE} baud")
        print(f"Settings: {DATA_BITS} data bits, parity={PARITY}, stop bits={STOP_BITS}")

        # Small delay to ensure port is ready
        time.sleep(0.1)

        # Send data
        bytes_written = ser.write(data_to_send.encode('utf-8'))
        print(f"Sent {bytes_written} bytes: '{data_to_send}'")

        # Optional: Wait for and read response
        # time.sleep(0.5)
        # if ser.in_waiting > 0:
        #     response = ser.read(ser.in_waiting)
        #     print(f"Received: {response.decode('utf-8', errors='ignore')}")

        # Close port
        ser.close()
        print("Port closed")

    except serial.SerialException as e:
        print(f"Serial error: {e}")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
