- MicroPython Cookbook
- Marwan Alsabbagh
- 233字
- 2021-06-24 14:28:16
How to do it...
Let's perform the following steps:
- Run the following lines of code in the REPL. You should hear a high-pitched beeping sound for 0.5 seconds:
>>> from adafruit_circuitplayground.express import cpx >>> import time >>> >>> BEEP_HIGH = 960 >>> BEEP_LOW = 800 >>> >>> cpx.pixels.brightness = 0.10 >>> cpx.start_tone(BEEP_HIGH) >>> time.sleep(0.5) >>> cpx.stop_tone()
- Use the following code to play a beeping sound in the background while 10 pixels turn red at 0.1-second intervals. The beeping will then stop at the end of the animation:
>>> cpx.start_tone(BEEP_HIGH) >>> for i in range(10): ... cpx.pixels[i] = 0xFF0000 ... time.sleep(0.1) ... >>> cpx.stop_tone() >>>
- Use the following block of code to perform a similar operation, but with a lower pitch. Here, the pixel animation will turn off each pixel one by one, ending the tone at the end of the animation:
>>> cpx.start_tone(BEEP_LOW) >>> for i in range(10): ... cpx.pixels[i] = 0x000000 ... time.sleep(0.1) ... >>> cpx.stop_tone() >>>
- The code that follows combines all the code shown in this recipe to make one complete program. Add this to the main.py file and it will play a siren alarm and animate the pixels on and off with the siren:
from adafruit_circuitplayground.express import cpx import time BEEP_HIGH = 960 BEEP_LOW = 800 cpx.pixels.brightness = 0.10 cpx.start_tone(BEEP_HIGH) for i in range(10): cpx.pixels[i] = 0xFF0000 time.sleep(0.1) cpx.stop_tone() cpx.start_tone(BEEP_LOW) for i in range(10): cpx.pixels[i] = 0x000000 time.sleep(0.1) cpx.stop_tone()