gpio_playground.py 1.2 KB

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