gpio_playground.py 876 B

123456789101112131415161718192021222324252627282930
  1. import asyncio
  2. import pigpio
  3. async def toggle_pin(pin: int):
  4. """Toggle a GPIO pin indefinitely."""
  5. pi = pigpio.pi()
  6. if not pi.connected:
  7. raise RuntimeError(f"Failed to connect to pigpio daemon for pin {pin}")
  8. state = 0
  9. try:
  10. while True:
  11. state = 1 - state # Toggle state between 0 and 1
  12. pi.write(pin, state)
  13. await asyncio.sleep(1) # Wait 1 second between toggles
  14. finally:
  15. pi.write(pin, 0) # Ensure the pin is turned off
  16. pi.stop()
  17. async def main():
  18. """Run multiple toggle_pin tasks in parallel."""
  19. pins = [17, 27, 22] # Replace with the GPIO pins you want to toggle
  20. tasks = [toggle_pin(pin) for pin in pins]
  21. await asyncio.gather(*tasks)
  22. if __name__ == "__main__":
  23. try:
  24. asyncio.run(main())
  25. except KeyboardInterrupt:
  26. print("Exiting...")