pythonarduinoserial-portpyserial

How to read data from serial port? Python


Hi please bear my basic question as I am new to python.
I am trying to read data from serial port. Basically serial port is a USB port converted to serial port virtually. I am using arduino.
First i tried this code:

while(True):
    ser=serial.Serial('COM6',9600)
    bytoread=ser.inWaiting()
    val=ser.read(bytoread)

But it gave me error.

Permission Error(13,Access is denied, none 5)

But when i changed my code to

while(True):
    ser=serial.Serial()
    ser.baudrate=19600
    ser.port='COM6'
    ser
    ser.open()
    bytoread=ser.inWaiting()
    val=ser.read(bytoread)

Permission error did not come but program is always busy connecting the port. I waited for many minutes but it never moved forward. What I am doing wrong here?


Solution

  • you can do something like :

    import serial
    ser = serial.Serial('COM6', 9600, timeout=None)
    
    while True:
        data = ser.readline()
    

    you can't put ser = serial.Serial('COM5', 9600, timeout=None) in your while loop because it will permanently (re)create the connection...