switch.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """
  2. switch.py
  3. =========
  4. Light up some leds when the USR switch on the pyboard is pressed.
  5. Example Usage::
  6. Micro Python v1.0.1 on 2014-05-12; PYBv1.0 with STM32F405RG
  7. Type "help()" for more information.
  8. >>> import switch
  9. >>> switch.run_loop()
  10. Loop started.
  11. Press Ctrl+C to break out of the loop.
  12. """
  13. import pyb
  14. switch = pyb.Switch()
  15. red_led = pyb.LED(1)
  16. green_led = pyb.LED(2)
  17. orange_led = pyb.LED(3)
  18. blue_led = pyb.LED(4)
  19. all_leds = (red_led, green_led, orange_led, blue_led)
  20. def run_loop(leds=all_leds):
  21. """
  22. Start the loop.
  23. :param `leds`: Which LEDs to light up upon switch press.
  24. :type `leds`: sequence of LED objects
  25. """
  26. print('Loop started.\nPress Ctrl+C to break out of the loop.')
  27. while 1:
  28. try:
  29. if switch():
  30. [led.on() for led in leds]
  31. else:
  32. [led.off() for led in leds]
  33. except OSError: # VCPInterrupt # Ctrl+C in interpreter mode.
  34. break
  35. if __name__ == '__main__':
  36. run_loop()