8000 Changes to the tone function by brentru · Pull Request #24 · adafruit/Adafruit_CircuitPython_SimpleIO · GitHub
[go: up one dir, main page]

Skip to content

Changes to the tone function #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jan 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions examples/tone_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""
'tone_demo.py'.

=================================================
a short piezo song using tone()
"""
import time
import board
import simpleio


while True:
for f in (262, 294, 330, 349, 392, 440, 494, 523):
simpleio.tone(board.A0, f, 0.25)
time.sleep(1)
35 changes: 18 additions & 17 deletions simpleio.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,31 +34,32 @@
import digitalio
import pulseio

def tone(pin, frequency, duration=1):
def tone(pin, frequency, duration=1, length=100):
"""
Generates a square wave of the specified frequency (50% duty cycle)
on a pin
Generates a square wave of the specified frequency on a pin

:param ~microcontroller.Pin Pin: Pin on which to output the tone
:param int frequency: Frequency of tone in Hz
:param float frequency: Frequency of tone in Hz
:param int length: Variable size buffer (optional)
:param int duration: Duration of tone in seconds (optional)
"""
try:
length = 4000 // frequency
square_wave = array.array("H", [0] * length)
for i in range(length):
if i < length / 2:
square_wave.append(0xFFFF)
else:
square_wave.append(0x00)
with audioio.AudioOut(pin, square_wave) as waveform:
waveform.play(loop=True)
time.sleep(duration)
waveform.stop()
except (NameError, ValueError):
with pulseio.PWMOut(pin, frequency=frequency, variable_frequency=False) as pwm:
with pulseio.PWMOut(pin, frequency=int(frequency), variable_frequency=False) as pwm:
pwm.duty_cycle = 0x8000
time.sleep(duration)
except ValueError:
sample_length = length
square_wave = array.array("H", [0] * sample_length)
for i in range(sample_length / 2):
square_wave[i] = 0xFFFF
sample_tone = audioio.AudioOut(pin, square_wave)
sample_tone.frequency = int(len(square_wave) * frequency)
if not sample_tone.playing:
sample_tone.play(loop=True)
time.sleep(duration)
sample_tone.stop()



def bitWrite(x, n, b): #pylint: disable-msg=invalid-name
"""
Expand Down
0