MicroPython Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

Let's perform the following steps:

  1. Run the following lines of code in the REPL while keeping push button A pressed:
>>> from adafruit_circuitplayground.express import cpx
>>> if cpx.button_a:
...     cpx.play_tone(500, 0.2)
...     
...     
... 
>>>
  1. The speaker should have given a low-pitch beep. Run the following code while keeping push button B pressed, and you should hear a high-pitch beep:
>>> if cpx.button_b:
...     cpx.play_tone(900, 0.2)
...     
...     
... 
>>> 
  1. The code that follows combines all the code shown in this recipe and adds a while loop to it to make one complete program. Add this to the main.py file, and, when executed, it will produce either a high-or low-pitch beep each time either push button A or push button B is pressed:
from adafruit_circuitplayground.express import cpx

while True:
    if cpx.button_a:
        cpx.play_tone(500, 0.2)
    if cpx.button_b:
        cpx.play_tone(900, 0.2)