GoPiGo - Mouse control AND ultrasonic sensor

Hi everybody,
I very much like the mouse control of the robot, and it works using the input data stream from the mouse.
(see code below).

Then I tried to combine it with the ultrasonic sensor, i.e. if sth is in the way, the robo should stop.

My Problem is that reading the mouse stream halts the program until an input from the mouse is delivered
before proceeding the program, so I can’t read the distance to objects if the mouse is not used - but
robo might be still running and the wall is getting closer :slight_smile:

Any idea how I can e.g. timeout the buf = file.read(3), so I can do an ultrasonic measurement and
then ask for mouse input again (idea: listen 0.5 sec to mouse, 0.5. sec to ultrasonic and so on) or
any other solution?

Thanks a lot for your help,

Chris

#Open the stream of data coming from the mouse
file = open( "/dev/input/mice", "rb" );
speed=150

debug = 0	#Print raw values when debugging

#Parse through the fata coming from mouse
#Returns: 	[left button pressed,
#		middle button pressed,
#		right button pressed,
#		change of position in x-axis,
#		change of position in y-axis]
def getMouseEvent():
	buf = file.read(3)
	button = ord( buf[0] )
	bLeft = button & 0x1
	bMiddle = ( button & 0x4 ) > 0
	bRight = ( button & 0x2 ) > 0
	x,y = struct.unpack( "bb", buf[1:] )
	if debug:
		print ("L:%d, M: %d, R: %d, x: %d, y: %d\n" % (bLeft,bMiddle,bRight, x, y) )
	return [bLeft,bMiddle,bRight,x,y]

I found this on stackoverflow which is a file read with timeout: http://stackoverflow.com/questions/21429369/read-file-with-timeout-in-python, this might work though the file is actually a data stream from the mouse so it might not work. There was another post on the forums a few days back on how to deal with the same problem on the keyboard, so you can switch to that if you are with keyboard commands instead of mouse: http://www.dexterindustries.com/topic/best-way-to-detect-keypress-with-python/.

-Karan

Thanks Karan,
I was on holiday a few days and now I tried your suggested solution.
Problem is, I’m quiet new to Python and all this stuff, so I dont really
know hiow to make it work. This did not work … :slight_smile:
Any ideas? Thanks, Chris

import os
filno = os.open("/dev/input/mice", os.O_RDONLY|os.O_NONBLOCK); 
f=os.fdopen(filno, "r")
# print f 
# print f.read(3)

print os.read(f.fileno(), 50)

f.close()

Hi Chris,
I did spend some more time thinking about it and it does look a bit complex when I started thinking of better ways to implement this. To make it work as you want, you would have to keep reading the mouse and keep checking the readings from the ultrasonic sensor simultaneously and would have to use threads. One of the libraries that lets you use threads is the multiprocessing library (https://docs.python.org/2/library/multiprocessing.html), which might be your best bet when trying to implement this.

-Karan