0

Trying to create very simple keyboard and mouse controller using the Raspberry Pi's GPIO pins. Would love to use the code in a educational setting, so trying to build super easy, readable code for children/students. But the code is acting somewhat strange, it keeps outputting the same keystrokes:

import gpiozero
from pynput.mouse import Button, Controller as MouseController
from pynput.keyboard import Key, Controller as KeyboardController

keyboard = KeyboardController()
mouse = MouseController()

Up = gpiozero.Button(26, bounce_time=0.02)
LeftMouse = gpiozero.Button(17, bounce_time=0.02)

while True:
    if Up.is_pressed:
        print("Up")
        keyboard.press(Key.up)
        Up.wait_for_release()
        keyboard.release(Key.up)
    
    elif LeftMouse.is_pressed:
        print("Left Mouse button")
        mouse.press(button.left)
        LeftMouse.wait_for_release()
        mouse.release(button.left)

Using Python 3.7.3. No matter which GPIO I trigger (26 or 17), the code always outputs 'Up' and press the keyboard 'up' button. It must be something stupid, but I can't seem to figure it out. Would love to keep using the if/elif, so I can expand the code later with more GPIO buttons. Any idea's anyone?

Pieter-Jan
  • 21
  • 6

1 Answers1

0

Although I am not very experienced in the GPIO of Raspberry, I think your code is almost alright. I suspected that the reason of always having 'Up' outcomes, which meant the 2nd mouse condition statement was bypass, was probably due to the word 'button' being not consistent with the module you called in the first line? Below is the one after using 'Button' throughout. Probably when you triggered pin 17, it did pass through the printing stage but it could not penetrate further. It will no choice but to select the first keyboard statement. So, it would end up with 'Up' all the way.

from pynput.mouse import Button, Controller as MouseController
    
    elif LeftMouse.is_pressed:
        print("Left Mouse button")
        mouse.press(Button.left)
        LeftMouse.wait_for_release()
        mouse.release(Button.left)

I also found the below link quite useful in order to make sure the packages imported and defined properly. pynput - Importing keyboard and mouse

Looking forward to hearing from your update.

Eureka JX
  • 66
  • 3