1 min read

Getting raw data from a USB mouse in Linux using Python

If you are geek your mouth should be watering by now. I will like to thank Oscar Lindberg and his cool Linux friend for this code! I was trying to get multiple-mice movement data. This is the code that got me started. Once I beautify my multiple-mouse code I will be posting it here as well. Without further ado :

mouse = file('/dev/input/mouse0')
while True:
    status, dx, dy = tuple(ord(c) for c in mouse.read(3))

    def to_signed(n):
        return n - ((0x80 & n) << 1)
    dx = to_signed(dx)
    dy = to_signed(dy)
    print "%#02x %d %d" % (status, dx, dy)

I hope this just made your day!

Python3 Note:

hint for python3 people coming back to this, change the file line to

 mouse = open(‘/dev/input/mouse3’, ‘rb’)  
 and the tuple line to  
 status, dx, dy = tuple(c for c in mouse.read(3))

Thank you Tech2077!