Using Python I need a Concurrently While Loop with a PS4 Controller Event Loop

291 views Asked by At

Using Python I want to run two loops concurrently. The first is a regular while loop. The second is a while loop based on file events from a Bluetooth connected PS4 controller.

The two loops need to know what the other loops are up to.

Here is the relevant code with some comments for the missing code:

# Read PS4 controller events
infile_path = "/dev/input/event4"
in_file = open(infile_path, "rb")
FORMAT = 'llHHi'
EVENT_SIZE = struct.calcsize(FORMAT)
event = in_file.read(EVENT_SIZE)

# Event while loop reacting to PS4 events
while event:

  # React to a PS4 controller event
  # For example, start a motor when the X button is pressed
  # Or stop the motor when the X button is released

  # Read the next event
  event = in_file.read(EVENT_SIZE)

# Regular while loop
while True:
  
  # While Loop Code
  # I need code in here to be able to override the event loop
  # For example, stop the motor (even if the X button is pressed) if the motor senses resistance  

in_file.close()

I don't think it really matters, but I'm using Pybricks, it's built on MicroPython and optimized for robotics. I'm also using ev3dev, it's a Debian image also optimized for robotics. My full code is available on my GitHub.

1

There are 1 answers

0
Adam On

I ended up putting the PS4 event loop in a thread and the main script in a wile loop (not threaded). I then had one global variable storing all of the PS4 button statuses and that seemed to work fine.