|
1 |
| -import math |
2 |
| - |
3 |
| -import board |
| 1 | +import adafruit_thermistor |
4 | 2 | import analogio
|
| 3 | +import array |
| 4 | +import audioio |
| 5 | +import board |
5 | 6 | import digitalio
|
| 7 | +import math |
6 | 8 | import neopixel
|
7 |
| -import adafruit_thermistor |
| 9 | +import time |
| 10 | + |
8 | 11 |
|
9 | 12 | class Photocell:
|
10 | 13 | def __init__(self, pin):
|
@@ -63,6 +66,10 @@ def __init__(self):
|
63 | 66 | self._temp = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000, 25, 3950)
|
64 | 67 | self._light = Photocell(board.LIGHT)
|
65 | 68 |
|
| 69 | + # Define audio: |
| 70 | + self.speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) |
| 71 | + self.speaker_enable.switch_to_output(value=False) |
| 72 | + |
66 | 73 | @property
|
67 | 74 | def button_a(self):
|
68 | 75 | """``True`` when Button A is pressed. ``False`` if not.
|
@@ -184,6 +191,40 @@ def red_led(self):
|
184 | 191 | def red_led(self, value):
|
185 | 192 | self._led.value = value
|
186 | 193 |
|
| 194 | + def play_tone(self, frequency, duration): |
| 195 | + """ Produce a tone using the speaker. |
| 196 | +
|
| 197 | + :param int frequency: The frequency of the tone in Hz |
| 198 | + :param float duration: The duration of the tone in seconds |
| 199 | +
|
| 200 | + .. image :: /_static/speaker.jpg |
| 201 | +
|
| 202 | + The two numbers are frequency and duration. Duration is how long it |
| 203 | + plays in seconds. Try changing frequency to change the pitch of the |
| 204 | + tone. |
| 205 | +
|
| 206 | + ..code-block:python |
| 207 | +
|
| 208 | + from adafruit_circuitplayground.express import circuit |
| 209 | +
|
| 210 | + circuit.play_tone(440, 1) |
| 211 | + """ |
| 212 | + length = 8000 // frequency |
| 213 | + sine_wave = array.array("H", [0] * length) |
| 214 | + for i in range(length): |
| 215 | + sine_wave[i] = int(math.sin(math.pi * 2 * i / 18) * (2 ** 15) + 2 ** 15) |
| 216 | + |
| 217 | + sample = audioio.AudioOut(board.SPEAKER, sine_wave) |
| 218 | + |
| 219 | + self.speaker_enable.value = True |
| 220 | + |
| 221 | + sample.play(loop=True) |
| 222 | + time.sleep(duration) |
| 223 | + sample.stop() |
| 224 | + |
| 225 | + self.speaker_enable.value = False |
| 226 | + |
| 227 | + |
187 | 228 | circuit = Express()
|
188 | 229 | """Object that is automatically created on import.
|
189 | 230 |
|
|
0 commit comments