title: Python3 Two-Way Serial Communication: Reading In Data
body: <p>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. </p>
  
  <p>What I need is a convenient way to do it in real-time. So far I have the following code:</p>
  
  <pre><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 &gt;= 5):
                  break
          ser.close()
      except Exception as e:
          print ("Error communicating...: " + str(e))
  else:
      print ("Cannot open serial port.")
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>Starting Up Serial Monitor
  Exception: Opening serial port: Port is already open.
  write data: 1
  read data: 
  </code></pre>
  
  <p>and it goes forever. There is no read data or whatsoever. </p>
  
  <p>Where am I mistaken?</p>