Skip to content

Commit 253dc70

Browse files
brentruladyada
authored andcommitted
Changes to the tone function (#24)
* Changes to the tone function: - uses a fixed length square wave as default (can be variable) like in the mega demo - frequency is now a float instead of an int linted and added example
1 parent 10cd944 commit 253dc70

File tree

2 files changed

+33
-17
lines changed

2 files changed

+33
-17
lines changed

examples/tone_demo.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""
2+
'tone_demo.py'.
3+
4+
=================================================
5+
a short piezo song using tone()
6+
"""
7+
import time
8+
import board
9+
import simpleio
10+
11+
12+
while True:
13+
for f in (262, 294, 330, 349, 392, 440, 494, 523):
14+
simpleio.tone(board.A0, f, 0.25)
15+
time.sleep(1)

simpleio.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -34,31 +34,32 @@
3434
import digitalio
3535
import pulseio
3636

37-
def tone(pin, frequency, duration=1):
37+
def tone(pin, frequency, duration=1, length=100):
3838
"""
39-
Generates a square wave of the specified frequency (50% duty cycle)
40-
on a pin
39+
Generates a square wave of the specified frequency on a pin
4140
4241
:param ~microcontroller.Pin Pin: Pin on which to output the tone
43-
:param int frequency: Frequency of tone in Hz
42+
:param float frequency: Frequency of tone in Hz
43+
:param int length: Variable size buffer (optional)
4444
:param int duration: Duration of tone in seconds (optional)
4545
"""
4646
try:
47-
length = 4000 // frequency
48-
square_wave = array.array("H", [0] * length)
49-
for i in range(length):
50-
if i < length / 2:
51-
square_wave.append(0xFFFF)
52-
else:
53-
square_wave.append(0x00)
54-
with audioio.AudioOut(pin, square_wave) as waveform:
55-
waveform.play(loop=True)
56-
time.sleep(duration)
57-
waveform.stop()
58-
except (NameError, ValueError):
59-
with pulseio.PWMOut(pin, frequency=frequency, variable_frequency=False) as pwm:
47+
with pulseio.PWMOut(pin, frequency=int(frequency), variable_frequency=False) as pwm:
6048
pwm.duty_cycle = 0x8000
6149
time.sleep(duration)
50+
except ValueError:
51+
sample_length = length
52+
square_wave = array.array("H", [0] * sample_length)
53+
for i in range(sample_length / 2):
54+
square_wave[i] = 0xFFFF
55+
sample_tone = audioio.AudioOut(pin, square_wave)
56+
sample_tone.frequency = int(len(square_wave) * frequency)
57+
if not sample_tone.playing:
58+
sample_tone.play(loop=True)
59+
time.sleep(duration)
60+
sample_tone.stop()
61+
62+
6263

6364
def bitWrite(x, n, b): #pylint: disable-msg=invalid-name
6465
"""

0 commit comments

Comments
 (0)