I have a button box connected via a serial port adapter to a USB port.
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.
What I am doing so far is this:
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()
If I do this, however, I get the following error:
TypeError: an integer is required
If I check line
after the button press, I get the following value:
'\x02'
The value changes according to the button pressed: '\x02'
, '\x03'
etc. So it seems to at least detect the right button pressed.
The last thing I tried to do is the following. In order to convert the string into an integer, I tried to replace '\x0'
:
line
a=str(line)
a.replace('\x0', "")
a
And I get the following error:
ValueError: invalid \x escape
'\x02'
is escaped code for a string containing ONE character with (ascii/ansi/unicode) value 2. Your line variable is 1 character long. Try len(line)
If you want to print the button number by extracting the value of this character try: print(ord(line[0]))