gpio_playground.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import asyncio
  2. import pigpio
  3. """
  4. A simple GPIO pin toggler using pigpio and asyncio.
  5. Toggles GPIO pins based on keyboard input (Enter key).
  6. """
  7. pins = [27]
  8. # pins = [17, 27, 22]
  9. async def toggle_pin(pin: int, shared_state):
  10. """Toggle a GPIO pin based on shared state."""
  11. pi = pigpio.pi()
  12. if not pi.connected:
  13. raise RuntimeError(f"Failed to connect to pigpio daemon for pin {pin}")
  14. try:
  15. while True:
  16. pi.write(pin, shared_state['state'])
  17. await asyncio.sleep(0.1) # Small delay to prevent CPU overuse
  18. finally:
  19. pi.write(pin, 0)
  20. pi.stop()
  21. async def handle_input(shared_state):
  22. """Handle keyboard input to toggle pins."""
  23. while True:
  24. await asyncio.get_event_loop().run_in_executor(None, input, "Press Enter to toggle pins...")
  25. shared_state['state'] = 1 - shared_state['state'] # Toggle state
  26. print(f"Toggled pins to: {'ON' if shared_state['state'] else 'OFF'}")
  27. async def main():
  28. """Run input handling and pin toggling in parallel."""
  29. shared_state = {'state': 0}
  30. pin_tasks = [toggle_pin(pin, shared_state) for pin in pins]
  31. await asyncio.gather(handle_input(shared_state), *pin_tasks)
  32. if __name__ == "__main__":
  33. try:
  34. asyncio.run(main())
  35. except KeyboardInterrupt:
  36. print("Exiting...")