Python+Microcontroller=Mouse

Tech B 0 Tallied Votes 260 Views Share

I used Parallax's Basic Stamp Homework Board and an accelerometer to use as a mouse. It works better than I thought it would. PySerial is used to grab the debugged values from the stamp. The circuit is compiled of two push buttons, 2 LEDs to tell when a button is pushed, and the accelerometer. The chip is coded in BASIC:
Where IN9, IN10 are the push buttons
and X on pin 8, Y on pin 7, and are read by pulse rate.

' {$STAMP BS2}
' {$PBASIC 2.5}

x VAR Word
y VAR Word

DO

  PULSIN 8, 1, x
  PULSIN 7, 1, y
  DEBUG LF, ? x , ? y , ? IN9, ? IN10

LOOP
#Accelorometer mouse (Basic Stamp 2)
#3-12-10
#Tech B.

from ctypes import *
import serial
import win32api
import win32con

s = serial.Serial('COM5') #Will differ between systems. I use Serial to USB cable
user = windll.user32

#inital x,y values
x = 0
y = 0
speed = 10


def lUP():
   win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
def lDOWN():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
def rUP():
    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, 0, 0)
def rDOWN():
    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0)


c1 = 0#used to make sure no double clicks happen on accident
c2 = 0

#Main Loop
while 1:
  try:
    d = s.readline()
    d = d.split()
    if int(d[2]) > 2700:
        print 'right'
        if x < 1400:
            x += speed
    elif int(d[2]) < 2400:
        print 'left'
        if x > 0:
            x -= speed
    if int(d[5]) > 2600:
        print 'up'
        if y > 0:
            y -= speed
    elif int(d[5]) < 2400:
        print 'down'
        if y < 900:
            y += speed
    if int(d[8]) == 1 and c1 == 0:
        lDOWN()
        c1 += 1
    elif int(d[8]) == 0:
        lUP()
        c1 = 0
    if int(d[11]) == 1:
        rDOWN()
        rUP()

    user.SetCursorPos(x,y)
  except:
      pass