To improve efficieny, I used an example on Raspi-TV.
Also, link to the latest version of what is now pynput for mouse/keyboard input.
It uses interrupts rather than a timer. I did something very similar for 6 buttons connected to GPIO pins. Each button simulates a mouse click at a different point on the screen. This is what it would look like for your example.
I utilized GPIO 1 as an interrupt to the program. In my case, I don't use GPIO 1, and I wanted the program to continue to run indefinitely. However, you could hook another button up to that, or create a piece of code that would change the state from 0 to 1 to stop the script below. RPi.GPIO runs all of the detection triggers in a single thread, so the below script will continue to run until GPIO 1 in this case experiences a rising edge. I believe that would be lower overhead than freezing the thread for a timer every 0.2 seconds.
from pynput.mouse import Button, Controller
import RPi.GPIO as GPIO
import time
mouse = Controller()
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(1,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def GB1(channel):
print(f"Detected Left Most Green Button on {channel}")
mouse.position = (300,275)
mouse.press(Button.left)
mouse.release(Button.left)
GPIO.add_event_detect(16,GPIO.RISING, callback=GB1, bouncetime=200)
try:
print("Waiting...")
GPIO.wait_for_edge(1, GPIO.RISING)
print("Time's up..")
except:
print("Exception, exiting.")
GPIO.cleanup()
finally:
print("Normal Program Exit.")
GPIO.cleanup()