Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
Rafay Zia Mir Avatar asked Oct 28 '25 05:10

Rafay Zia Mir


1 Answers

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...

like image 60
Dadep Avatar answered Oct 29 '25 19:10

Dadep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!