title: Reading serial port input
body: <p>I have a button box connected via a serial port adapter to a USB port. </p>
  
  <p>The button box has 5 buttons. What I am trying to do, is to record what button has been pressed (and when). So far, I will focus on what button. The code will be used in a PsychoPy experiment. </p>
  
  <p>What I am doing so far is this:</p>
  
  <pre><code>import serial
  import serial.tools.list_ports as port_list
  ports = list(port_list.comports()) # search for the devices
  #for p in ports: print (p)
  
  ser = serial.Serial('/dev/ttyUSB0', 19200, timeout=1)
  
  
  if(ser.isOpen() == False): #open the serial port only if NOT open yet
      ser.open()
  
  ser.flushInput() #erase all info in the box about previous button-presses
  
  print("connected to: " + ser.portstr)
  
  line = ser.read()
  print(chr(line))
  ser.close()
  </code></pre>
  
  <p>If I do this, however, I get the following error:</p>
  
  <pre><code>TypeError: an integer is required
  </code></pre>
  
  <p>If I check <code>line</code> after the button press, I get the following value:</p>
  
  <pre><code>'\x02'
  </code></pre>
  
  <p>The value changes according to the button pressed: <code>'\x02'</code>, <code>'\x03'</code> etc. So it seems to at least detect the right button pressed.</p>
  
  <p>The last thing I tried to do is the following. In order to convert the string into an integer, I tried to replace <code>'\x0'</code>:</p>
  
  <pre><code>line
  a=str(line)
  a.replace('\x0', "")
  a
  </code></pre>
  
  <p>And I get the following error:</p>
  
  <pre><code>ValueError: invalid \x escape
  </code></pre>