Beispiel #1
0
def tone(pin, frequency, duration=1, length=100):
    """
    Generates a square wave of the specified frequency on a pin

    :param ~microcontroller.Pin pin: Pin on which to output the tone
    :param float frequency: Frequency of tone in Hz
    :param int length: Variable size buffer (optional)
    :param int duration: Duration of tone in seconds (optional)
    """
    if length * frequency > 350000:
        length = 350000 // frequency
    try:
        # pin with PWM
        # pylint: disable=no-member
        with pwmio.PWMOut(pin,
                          frequency=int(frequency),
                          variable_frequency=False) as pwm:
            pwm.duty_cycle = 0x8000
            time.sleep(duration)
        # pylint: enable=no-member
    except ValueError:
        # pin without PWM
        sample_length = length
        square_wave = array.array("H", [0] * sample_length)
        for i in range(sample_length / 2):
            square_wave[i] = 0xFFFF
        square_wave_sample = audiocore.RawSample(square_wave)
        square_wave_sample.sample_rate = int(len(square_wave) * frequency)
        with AudioOut(pin) as dac:
            if not dac.playing:
                dac.play(square_wave_sample, loop=True)
                time.sleep(duration)
            dac.stop()
Beispiel #2
0
def _play_to_pin(tune, base_tone, min_freq, duration, octave, tempo):
    """Using the prepared input send the notes to the pin
    """
    pwm = isinstance(base_tone, pulseio.PWMOut)
    for note in tune.split(","):
        piano_note, note_duration = _parse_note(note, duration, octave)
        if piano_note in PIANO:
            if pwm:
                base_tone.frequency = int(PIANO[piano_note])
                base_tone.duty_cycle = 2**15
            else:
                # AudioOut interface changed in CP 3.x
                if sys.implementation.version[0] >= 3:
                    pitch = int(PIANO[piano_note])
                    sine_wave = sine.sine_wave(16000, pitch)
                    sine_wave_sample = audiocore.RawSample(sine_wave)
                    base_tone.play(sine_wave_sample, loop=True)
                else:
                    base_tone.frequency = int(16000 *
                                              (PIANO[piano_note] / min_freq))
                    base_tone.play(loop=True)

        time.sleep(4 / note_duration * 60 / tempo)
        if pwm:
            base_tone.duty_cycle = 0
        else:
            base_tone.stop()
        time.sleep(0.02)
def waveform_sawtooth(length, waves, volumes):
    for vol in volumes:
        waveraw = array.array("H", [
            midpoint +
            round(vol * sawtooth((idx + 0.5) / length * twopi + math.pi))
            for idx in list(range(length))
        ])
        waves.append((audiocore.RawSample(waveraw), waveraw))
Beispiel #4
0
 def _generate_sample(self, length=100):
     if self._sample is not None:
         return
     self._sine_wave = array.array("H", Express._sine_sample(length))
     if sys.implementation.version[0] >= 3:
         self._sample = audioio.AudioOut(board.SPEAKER)
         self._sine_wave_sample = audiocore.RawSample(self._sine_wave)
     else:
         raise NotImplementedError(
             "Please use CircuitPython 3.0 or higher.")
Beispiel #5
0
 def __init__(self):
     self.duration = 0
     self.start = 0
     tone_volume = 1  # volume is from 0.0 to 1.0
     frequency = 440  # Set this to the Hz of the tone you want to generate.
     length = 4000 // frequency
     sine_wave = array.array("H", [0] * length)
     for i in range(length):
         sine_wave[i] = int((1 + math.sin(math.pi * 2 * i / length)) *
                            tone_volume * (2**15 - 1))
     self.sine_wave_sample = audiocore.RawSample(sine_wave)
 def _generate_sample(self, length=100):
     if AUDIO_ENABLED:
         if self._sample is not None:
             return
         self._sine_wave = array.array("H",
                                       PyBadgerBase._sine_sample(length))
         # pylint: disable=not-callable
         self._sample = self._audio_out(board.SPEAKER)  # pylint: disable=not-callable
         self._sine_wave_sample = audiocore.RawSample(self._sine_wave)
     else:
         print("Required audio modules were missing")
    def __init__(self):
        self.duration = 0
        self.start = 0
        tone_volume = 1  # volume is from 0.0 to 1.0
        frequency = 440  # Set this to the Hz of the tone you want to generate.
        length = 4000 // frequency
        sine_wave = array.array("H", [0] * length)
        for i in range(length):
            sine_wave[i] = int((1 + math.sin(math.pi * 2 * i / length)) *
                               tone_volume * (2**15 - 1))
        self.sine_wave_sample = audiocore.RawSample(sine_wave)

        self._speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.switch_to_output(False)

        if hasattr(board, "AUDIO_OUT"):
            self.audio = audioio.AudioOut(board.AUDIO_OUT)
        elif hasattr(board, "SPEAKER"):
            self.audio = audioio.AudioOut(board.SPEAKER)
        else:
            raise AttributeError("Board does not have a builtin speaker!")
    def update(self, shape, frequency):
        if shape == self.shape and frequency == self.frequency:
            return

        if frequency != self.frequency:
            self.reallocate(frequency)
            self.frequency = frequency

        self.shape = shape
        if shape == shapes.SINE:
            self.make_sine()
        elif shape == shapes.SQUARE:
            self.make_square()
        elif shape == shapes.TRIANGLE:
            self.make_triangle()
        elif shape == shapes.SAWTOOTH:
            self.make_sawtooth()

        self.dac.stop()
        self.dac.play(audiocore.RawSample(self.sample,
                                          channel_count=1,
                                          sample_rate=64000),
                      loop=True)
Beispiel #9
0
 def _generate_sample(self, length=100):
     if self._sample is not None:
         return
     self._sine_wave = array.array("H", self._sine_sample(length))
     self._sample = audiopwmio.PWMAudioOut(board.SPEAKER)
     self._sine_wave_sample = audiocore.RawSample(self._sine_wave)
        ### Keep x position within legal values (if needed)
        ##dac_a0_x = min(dac_a0_x, dac_x_max)
        ##dac_a0_x = max(dac_a0_x, 0)
        dac_a1_y = round((sine * pcy + cosine * pcx + halfrange_y) * mult_y)
        ### Keep y position within legal values (if needed)
        ##dac_a1_y = min(dac_a1_y, dac_y_max)
        ##dac_a1_y = max(dac_a1_y, 0)
        rawdata[idx] = dac_a0_x - dac_x_mid  ### adjust for "h" array
        rawdata[idx + 1] = dac_a1_y - dac_y_mid  ### adjust for "h" array
        idx += 2

    if use_wav:
        ### 200k (maybe 166.667k) seems to be practical limit
        ### 1M permissible but seems same as around 200k
        output_wave = audiocore.RawSample(rawdata,
                                          channel_count=2,
                                          sample_rate=200 * 1000)

        ### The image may "warp" sometimes with loop=True due to a strange bug
        ### https://github.com/adafruit/circuitpython/issues/1992
        if poor_wav_bug_workaround:
            while True:
                dacs.play(output_wave)
                if time.monotonic() - prev_t >= frame_t:
                    break
        else:
            dacs.play(output_wave, loop=True)
            while time.monotonic() - prev_t < frame_t:
                pass
            if not leave_wav_looping:
                dacs.stop()
 def _generate_sample(self, length=100):
     if self._sample is not None:
         return
     self._sine_wave = array.array("H", PyBadgerBase._sine_sample(length))
     self._sample = self._audio_out(board.SPEAKER)  # pylint: disable=not-callable
     self._sine_wave_sample = audiocore.RawSample(self._sine_wave)
Beispiel #12
0
Update the following pin names to a viable pin combination:
* BIT_CLOCK_PIN
* WORD_SELECT_PIN
* DATA_PIN
"""
import time
import array
import math
import audiocore
import board
import audiobusio

audio = audiobusio.I2SOut(board.BIT_CLOCK_PIN, board.WORD_SELECT_PIN,
                          board.DATA_PIN)

tone_volume = 0.1  # Increase this to increase the volume of the tone.
frequency = 440  # Set this to the Hz of the tone you want to generate.
length = 8000 // frequency
sine_wave = array.array("h", [0] * length)
for i in range(length):
    sine_wave[i] = int(
        (math.sin(math.pi * 2 * i / length)) * tone_volume * (2**15 - 1))
sine_wave_sample = audiocore.RawSample(sine_wave)

while True:
    audio.play(sine_wave_sample, loop=True)
    time.sleep(1)
    audio.stop()
    time.sleep(1)
timeout = time.monotonic()

while True:
    print((light.value, ))

    # determine height of pixels
    pixel_height = map_range(light.value, DARK, BRIGHT, 0, num_pixels)
    pixels.fill((0, 0, 0))
    for p in range(pixel_height):
        pixels[p] = wheel(int(p / num_pixels * 255))
        pixels.show()

    # determine squeek
    freq = int(map_range(light.value, DARK, BRIGHT, 440, 8800))
    sine_wave = audiocore.RawSample(wave_array,
                                    channel_count=1,
                                    sample_rate=freq)
    cpx_audio.stop()
    cpx_audio.play(sine_wave, loop=True)

    # check no activity
    if light.value > ACTIVITY_THRESHOLD:
        timeout = time.monotonic()  # reset our timeout

    # 4 seconds no activity
    if time.monotonic() - timeout > 4:
        break

pixels.fill((255, 0, 0))
pixels.show()
play_file("03_no_sanctuary.wav")
Beispiel #14
0
# This generates a raw set of samples that represents one full
# cycle of a sine wave. If you wanted different waveforms, you
# could change the formula here to generate that instead.
def generate_noise(volume=1.0):
    volume = volume * (2 ** 15 - 1)  # Increase this to increase the volume of the tone.
    length = 800
    samples = array.array("H", [0] * length)

    for i in range(length):
        samples[i] = int(random.random() * volume)
    
    return samples

noise = generate_noise(0.8)
sample = audiocore.RawSample(noise)

# Change this to set the noise sample's frequency.
# This generate works well as pretty low numbers,
# but you can get some interesting effects at higher
# values.
frequency = 2
sample.sample_rate = frequency * len(noise)


while True:
    if bhb.triggered:
        bhb.gate_out = True
        bhb.play(sample, loop=True)

    if bhb.released:
Beispiel #15
0
# Plays a simple 8ksps 440 Hz sin wave
#
# Adapted from "Audio output via digital PWM article"
# https://circuitpython.readthedocs.io/en/latest/shared-bindings/audiopwmio/index.html
# for Maker Pi Pico
#
# Copy this file to Maker Pi Pico CIRCUITPY drive as code.py to run it on power up.
#

import audiocore
import audiopwmio
import board
import array
import time
import math

# Generate one period of sine wav.
length = 8000 // 440
sine_wave = array.array("H", [0] * length)
for i in range(length):
    sine_wave[i] = int(math.sin(math.pi * 2 * i / length) * (2**15) + 2**15)

dac = audiopwmio.PWMAudioOut(board.GP18)
sine_wave = audiocore.RawSample(sine_wave, sample_rate=8000)
dac.play(sine_wave, loop=True)
time.sleep(1)
dac.stop()
trigger.switch_to_output(True)

# Generate one period of sine wav.
length = 8000 // 440

samples = []
sample_names = [
    "unsigned 8 bit", "signed 8 bit", "unsigned 16 bit", "signed 16 bit"
]

# unsigned 8 bit
u8 = array.array("B", [0] * length)
for i in range(length):
    u8[i] = int(math.sin(math.pi * 2 * i / length) * (2**7) + 2**7)

samples.append(audiocore.RawSample(u8, sample_rate=4000))

# signed 8 bit
s8 = array.array("b", [0] * length)
for i in range(length):
    s8[i] = int(math.sin(math.pi * 2 * i / length) * (2**7))

samples.append(audiocore.RawSample(s8, sample_rate=16000))

# unsigned 16 bit
u16 = array.array("H", [0] * length)
for i in range(length):
    u16[i] = int(math.sin(math.pi * 2 * i / length) * (2**15) + 2**15)

samples.append(audiocore.RawSample(u16, sample_rate=8000))
import rp2pio
import adafruit_pioasm

time.sleep(10)

trigger = digitalio.DigitalInOut(board.D4)
trigger.switch_to_output(True)

# Generate one period of sine wav.
length = 8000 // 440

# signed 16 bit
s16 = array.array("h", [0] * length)
for i in range(length):
    s16[i] = int(math.sin(math.pi * 2 * i / length) * (2**15))
    print(s16[i])

sample = audiocore.RawSample(s16, sample_rate=8000)

dac = audiobusio.I2SOut(bit_clock=board.D10,
                        word_select=board.D11,
                        data=board.D12)

trigger.value = False
dac.play(sample, loop=True)
time.sleep(1)
dac.stop()
trigger.value = True

print("done")
Beispiel #18
0
import time
import array
import math
import audiocore
import board
import audiobusio

sample_rate = 8000
tone_volume = .1  # Increase or decrease this to adjust the volume of the tone.
frequency = 440  # Set this to the Hz of the tone you want to generate.
length = sample_rate // frequency  # One freqency period
sine_wave = array.array("H", [0] * length)
for i in range(length):
    sine_wave[i] = int(
        (math.sin(math.pi * 2 * frequency * i / sample_rate) * tone_volume + 1)
        * (2**15 - 1))

# For Feather M0 Express, ItsyBitsy M0 Express, Metro M0 Express
audio = audiobusio.I2SOut(board.D1, board.D0, board.D9)
# For Feather M4 Express
# audio = audiobusio.I2SOut(board.D1, board.D10, board.D11)
# For Metro M4 Express
# audio = audiobusio.I2SOut(board.D3, board.D9, board.D8)
sine_wave_sample = audiocore.RawSample(sine_wave, sample_rate=sample_rate)

while True:
    audio.play(sine_wave_sample, loop=True)
    time.sleep(1)
    audio.stop()
    time.sleep(1)