Skip to content

Instantly share code, notes, and snippets.

@badjano
Created February 28, 2021 17:36
Show Gist options
  • Save badjano/ddf552ab0fbd990e77491a4a823dad06 to your computer and use it in GitHub Desktop.
Save badjano/ddf552ab0fbd990e77491a4a823dad06 to your computer and use it in GitHub Desktop.
Mouse and keyboard control for raspberry pi LCD HAT ST7735S
from pymouse import PyMouse
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
btn_up = 5
btn_down = 26
btn_left = 19
btn_right = 6
btn_key1 = 21
btn_key2 = 20
btn_key3 = 16
# Up, Down, left, right, Button
GPIO.setup(btn_up, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(btn_down, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(btn_left, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(btn_right, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(btn_key1, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(btn_key2, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(btn_key3, GPIO.IN, GPIO.PUD_UP)
def main():
m = PyMouse()
key1_pressed = False
key2_pressed = False
key3_pressed = False
mouse_speed = 5
while True:
nowxy = m.position()
if not GPIO.input(btn_key1) and not key1_pressed: # button pressed
key1_pressed = True
print("KEY1")
m.click(nowxy[0], nowxy[1], 1)
elif key1_pressed and GPIO.input(btn_key1): # button released
key1_pressed = False
if not GPIO.input(btn_key2) and not key2_pressed: # button pressed
key2_pressed = True
print("KEY2")
m.click(nowxy[0], nowxy[1], 2)
elif key2_pressed and GPIO.input(btn_key2): # button released
key2_pressed = False
if not GPIO.input(btn_key3) and not key3_pressed: # button pressed
key3_pressed = True
print("KEY3")
m.click(nowxy[0], nowxy[1], 2)
elif key3_pressed and GPIO.input(btn_key3): # button released
key3_pressed = False
dirs = [
not GPIO.input(btn_up),
not GPIO.input(btn_down),
not GPIO.input(btn_left),
not GPIO.input(btn_right)
]
if dirs[0]: # button pressed
m.move(nowxy[0] - mouse_speed, nowxy[1])
mouse_speed += 1
if dirs[1]: # button pressed
m.move(nowxy[0] + mouse_speed, nowxy[1])
mouse_speed += 1
if dirs[2]: # button pressed
m.move(nowxy[0], nowxy[1] + mouse_speed)
mouse_speed += 1
if dirs[3]: # button pressed
m.move(nowxy[0], nowxy[1] - mouse_speed)
mouse_speed += 1
if sum([1 if a else 0 for a in dirs]) == 0:
mouse_speed = 5
time.sleep(0.03) # Poll every 20ms (otherwise CPU load gets too high)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment