Skip to content

Commit b28fac7

Browse files
brentruBrent Rubell
authored andcommitted
Introduced tone helper modeled after arduino's tone. Works on digital and analog pins.
1 parent f4d2736 commit b28fac7

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

simpleio.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,43 @@
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, tone_analog = False):
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+
:param bool tone_analog: True if Analog Pin A0 is used instead of digitial
44+
"""
45+
if tone_analog:
46+
length = 4000 // frequency
47+
square_wave = array.array("H", [0] * length)
48+
for i in range(length):
49+
if(i < length / 2):
50+
square_wave.append(0xFFFF)
51+
else:
52+
square_wave.append(0x00)
53+
waveform = audioio.AudioOut(pin, square_wave)
54+
waveform.play(loop=True)
55+
time.sleep(duration)
56+
waveform.stop()
57+
waveform.deinit()
58+
else:
59+
pwm = pulseio.PWMOut(pin, frequency = frequency, variable_frequency = False)
60+
for i in range(0, duration):
61+
pwm.duty_cycle = 0x8000
62+
time.sleep(1)
63+
pwm.deinit()
64+
3465
def shift_in(dataPin, clock, msb_first=True):
3566
"""
3667
Shifts in a byte of data one bit at a time. Starts from either the LSB or

0 commit comments

Comments
 (0)