Skip to content

Commit f38e550

Browse files
brentrutannewt
authored andcommitted
Introduced tone helper modeled after arduino's tone. Works on digital and analog pins. (#12)
Fixes #2
1 parent f4d2736 commit f38e550

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

simpleio.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,39 @@
2525
2626
The `simpleio` module contains classes to provide simple access to IO.
2727
"""
28-
28+
import audioio
29+
import array
2930
import digitalio
3031
import pulseio
3132
import math
3233
import time
3334

35+
def tone(pin, frequency, duration = 1):
36+
"""
37+
Generates a square wave of the specified frequency (50% duty cycle)
38+
on a pin
39+
40+
:param ~microcontroller.Pin Pin: Pin on which to output the tone
41+
:param int frequency: Frequency of tone in Hz
42+
:param int duration: Duration of tone in seconds (optional)
43+
"""
44+
try:
45+
length = 4000 // frequency
46+
square_wave = array.array("H", [0] * length)
47+
for i in range(length):
48+
if i < length / 2:
49+
square_wave.append(0xFFFF)
50+
else:
51+
square_wave.append(0x00)
52+
with audioio.AudioOut(pin, square_wave) as waveform:
53+
waveform.play(loop=True)
54+
time.sleep(duration)
55+
waveform.stop()
56+
except ValueError:
57+
with pulseio.PWMOut(pin, frequency = frequency, variable_frequency = False) as pwm:
58+
pwm.duty_cycle = 0x8000
59+
time.sleep(duration)
60+
3461
def shift_in(dataPin, clock, msb_first=True):
3562
"""
3663
Shifts in a byte of data one bit at a time. Starts from either the LSB or

0 commit comments

Comments
 (0)