Python3 Two-Way Serial Communication: Reading In Data

Viewed 33966

I am trying to establish a two-way communication via Python3. There is a laser range finder plugged into one of my USB ports and I'd like to send/receive commands to that. I have a sheet of commands which can be sent and what they would return, so this part is already there.

What I need is a convenient way to do it in real-time. So far I have the following code:

import serial, time

SERIALPORT = "/dev/ttyUSB0"
BAUDRATE = 115200

ser = serial.Serial(SERIALPORT, BAUDRATE)
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.timeout = None          #block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 0     #timeout for write

print ("Starting Up Serial Monitor")

try:
    ser.open()
except Exception as e:
    print ("Exception: Opening serial port: " + str(e))

if ser.isOpen():
    try:
        ser.flushInput()
        ser.flushOutput()
        ser.write("1\r\n".encode('ascii'))
        print("write data: 1")
        time.sleep(0.5)
        numberOfLine = 0
        while True:
            response = ser.readline().decode('ascii')
            print("read data: " + response)
            numberOfLine = numberOfLine + 1
            if (numberOfLine >= 5):
                break
        ser.close()
    except Exception as e:
        print ("Error communicating...: " + str(e))
else:
    print ("Cannot open serial port.")

So in the above code I am sending "1" which should trigger "getDistance()" function of the laser finder and return the distance in mm. I tried this on Putty and it works, returns distances up to 4 digits. However, when I launch the above Python script, my output is only the following:

Starting Up Serial Monitor
Exception: Opening serial port: Port is already open.
write data: 1
read data: 

and it goes forever. There is no read data or whatsoever.

Where am I mistaken?

3 Answers

try this code

try:
  ser = serial.Serial("/dev/ttyS0", 9600) #for COM3
  ser_bytes = ser.readline()
  time.sleep(1)
  inp = ser_bytes.decode('utf-8')
  print (inp)
except:
  pass
Related