Skip to content

Commit 9e47823

Browse files
kattnitannewt
authored andcommitted
Added speaker tones to Circuit Playground Express CircuitPython API. (#2)
Added speaker tones to Circuit Playground Express CircuitPython API. Included image for docs.
1 parent c98e4ee commit 9e47823

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

_static/speaker.jpg

692 KB
Loading

adafruit_circuitplayground/express.py

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
import math
2-
3-
import board
1+
import adafruit_thermistor
42
import analogio
3+
import array
4+
import audioio
5+
import board
56
import digitalio
7+
import math
68
import neopixel
7-
import adafruit_thermistor
9+
import time
10+
811

912
class Photocell:
1013
def __init__(self, pin):
@@ -63,6 +66,10 @@ def __init__(self):
6366
self._temp = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000, 25, 3950)
6467
self._light = Photocell(board.LIGHT)
6568

69+
# Define audio:
70+
self.speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
71+
self.speaker_enable.switch_to_output(value=False)
72+
6673
@property
6774
def button_a(self):
6875
"""``True`` when Button A is pressed. ``False`` if not.
@@ -184,6 +191,40 @@ def red_led(self):
184191
def red_led(self, value):
185192
self._led.value = value
186193

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+
187228
circuit = Express()
188229
"""Object that is automatically created on import.
189230

0 commit comments

Comments
 (0)