From c16eca829fe2288dd4e0249dd660c59b5631858c Mon Sep 17 00:00:00 2001 From: brentru Date: Wed, 26 Jul 2017 10:51:04 -0400 Subject: [PATCH] Introduced tone helper modeled after arduino's tone. Works on digital and analog pins. --- simpleio.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/simpleio.py b/simpleio.py index a967bc3..38f5419 100644 --- a/simpleio.py +++ b/simpleio.py @@ -25,12 +25,39 @@ The `simpleio` module contains classes to provide simple access to IO. """ - +import audioio +import array import digitalio import pulseio import math import time +def tone(pin, frequency, duration = 1): + """ + Generates a square wave of the specified frequency (50% duty cycle) + on a pin + + :param ~microcontroller.Pin Pin: Pin on which to output the tone + :param int frequency: Frequency of tone in Hz + :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 ValueError: + with pulseio.PWMOut(pin, frequency = frequency, variable_frequency = False) as pwm: + pwm.duty_cycle = 0x8000 + time.sleep(duration) + def shift_in(dataPin, clock, msb_first=True): """ Shifts in a byte of data one bit at a time. Starts from either the LSB or