"""Simple example to play a wave file""" # This example only works on Feathers that have analog audio out! import digitalio import board import audioio import audiocore WAV_FILE_NAME = "StreetChicken.wav" # Change to the name of your wav file! enable = digitalio.DigitalInOut(board.D10) enable.direction = digitalio.Direction.OUTPUT enable.value = True with audioio.AudioOut(board.A0) as audio: # Speaker connector wave_file = open(WAV_FILE_NAME, "rb") wave = audiocore.WaveFile(wave_file) audio.play(wave) while audio.playing: pass
def wheel(pos): # Input a value 0 to 255 to get a color value. if pos < 0 or pos > 255: return (0, 0, 0) elif pos < 85: return (int(pos * 3), int(255 - pos * 3), 0) elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 return (0, int(pos * 3), int(255 - pos * 3)) # Play the welcome wav (if its there) with audioio.AudioOut(board.A1, right_channel=board.A0) as audio: try: f = open("welcome.wav", "rb") wave = audioio.WaveFile(f) audio.play(wave) j = 0 trellis.pixels._neopixel.brightness = 0.25 while audio.playing: for i in range(32): pixel_index = (i * 256 // 32) + j trellis.pixels._neopixel[i] = wheel(pixel_index & 255) trellis.pixels._neopixel.show() j = (j + 1) % 256 time.sleep(0.005) f.close() # Clear all pixels
# Set to the length in seconds of the "on.wav" file POWER_ON_SOUND_DURATION = 1.7 NUM_PIXELS = 83 # Number of pixels used in project NEOPIXEL_PIN = board.D5 POWER_PIN = board.D10 enable = digitalio.DigitalInOut(POWER_PIN) enable.direction = digitalio.Direction.OUTPUT enable.value = False strip = neopixel.NeoPixel(NEOPIXEL_PIN, NUM_PIXELS, brightness=1, auto_write=False) strip.fill(0) # NeoPixels off ASAP on startup strip.show() audio = audioio.AudioOut(board.A0) # Speaker wave_file = None # Set up accelerometer on I2C bus, 4G range: i2c = board.I2C() accel = adafruit_lis3dh.LIS3DH_I2C(i2c) accel.range = adafruit_lis3dh.RANGE_4_G COLOR_IDLE = COLOR # 'idle' color is the default COLOR_HIT = ALT_COLOR # "hit" color is ALT_COLOR set above COLOR_SWING = ALT_COLOR # "swing" color is ALT_COLOR set above def play_wav(name, loop=False): """ Play a WAV file in the 'sounds' directory.
ring.fill((255, 0, 0)) # Light sensor light = analogio.AnalogIn(board.LIGHT) BRIGHT = 40000 DARK = 10000 ACTIVITY_THRESHOLD = 20000 # button button_a = DigitalInOut(board.BUTTON_A) button_a.direction = Direction.INPUT button_a.pull = Pull.DOWN # audio output cpx_audio = audioio.AudioOut(board.A0) def play_file(wavfile): with open(wavfile, "rb") as f: wav = audiocore.WaveFile(f) cpx_audio.play(wav) while cpx_audio.playing: pass # Generate one period of wave. length = 8000 // 440 wave_array = array.array("H", [0] * length) for i in range(length): # Sine wave
self.next_choice = idx if idx >= 1: result = all_folders[idx - 1] self.next_choice = idx + 1 if self.next_choice == len(choices): self.next_choice = 1 # Go to first folder, not "surprise me" else: result = random.choice(all_folders) return join(base, result) # pylint: disable=invalid-name enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) enable.direction = digitalio.Direction.OUTPUT enable.value = True speaker = audioio.AudioOut(board.SPEAKER, right_channel=board.A1) mp3stream = audiomp3.MP3Decoder(open("/rsrc/splash.mp3", "rb")) speaker.play(mp3stream) font = adafruit_bitmap_font.bitmap_font.load_font("rsrc/5x8.bdf") playback_display = PlaybackDisplay() board.DISPLAY.show(playback_display.group) font.load_glyphs(range(32, 128)) BUTTON_SEL = const(8) BUTTON_START = const(4) BUTTON_A = const(2) BUTTON_B = const(1) joystick = analogjoy.AnalogJoystick()
import time from random import seed, randint import board import digitalio import displayio import audioio import adafruit_imageload import adafruit_touchscreen seed(int(time.monotonic())) # Set up audio speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) speaker_enable.switch_to_output(False) if hasattr(board, 'AUDIO_OUT'): audio = audioio.AudioOut(board.AUDIO_OUT) elif hasattr(board, 'SPEAKER'): audio = audioio.AudioOut(board.SPEAKER) else: raise AttributeError('Board does not have a builtin speaker!') NUMBER_OF_BOMBS = 15 # Board pieces OPEN0 = 0 OPEN1 = 1 OPEN2 = 2 OPEN3 = 3 OPEN4 = 4 OPEN5 = 5
def play_file(filename): print("playing file " + filename) f = open(filename, "rb") a = audioio.AudioOut(board.A0, f) a.play()
def play_file(filename): print("playing file " + filename) f = open(filename, "rb") a = audioio.AudioOut(board.A0, f) a.play() time.sleep(bpm / 960) # sixteenthNote delay
RED = (16, 0, 0) GREEN = (0, 16, 0) BLACK = (0, 0, 0) pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.2) pixels.fill(BLACK) # Create a motor on Crickit Motor 1 port motor = crickit.dc_motor_1 ############### User variables run_time = 6 speed = 0.65 ############### Music cpx_audio = audioio.AudioOut(board.A0) # speaker out on Crickit def play_file(wavfile): with open(wavfile, "rb") as f: wav = audioio.WaveFile(f) cpx_audio.play(wav) while cpx_audio.playing: pass wav_file_name = "circus.wav" play_file(wav_file_name) while True: # set NeoPixels green in direction of movement
trig_button.switch_to_input(pull=Pull.UP) alt_button = DigitalInOut(board.A5) alt_button.switch_to_input(pull=Pull.UP) # ---ACCELEROMETER SETUP--- # Set up accelerometer on I2C bus, 4G range: i2c = busio.I2C(board.SCL, board.SDA) int1 = DigitalInOut(board.D6) accel = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1) # ---SPEAKER SETUP--- enable = DigitalInOut(board.D10) enable.direction = Direction.OUTPUT enable.value = True # Set up speakers and mixer. Stereo files, where music has empty right channel, FX empty left speaker = audioio.AudioOut(board.A0, right_channel=board.A1) mixer = audiomixer.Mixer(channel_count=2, buffer_size=2304, sample_rate=22050) # ---NEOPIXEL SETUP--- pixel_pin = board.D5 pixel_num = 154 pixels = neopixel.NeoPixel(pixel_pin, pixel_num, brightness=0.6, auto_write=False, pixel_order=neopixel.GRBW) # ^ change pixel_order depending on RGB vs. RGBW pixels # ---Pixel Map--- # this is the physical order in which the strips are plugged pixel_stripA = PixelSubset(pixels, 0, 18) # 18 pixel strip
# 20 FEB 2018 21:46 import digitalio import audioio import board import time import busio import adafruit_ssd1306 import analogio from adafruit_waveform import sine # Create 440Hz sine tone sample and assign to feather's DAC FREQUENCY = 440 # 440 Hz middle 'A' SAMPLERATE = 8000 # 8000 samples/second, recommended! wave = sine.sine_wave(SAMPLERATE, FREQUENCY) a440 = audioio.AudioOut(board.A0, wave) a440.frequency = SAMPLERATE # Initialize MIDI engine states midiRunningStatus = 0 midiState = 0 midiNoteBufferIndex = 0 midiNoteBuffer = [128, 128, 128, 128, 128, 128, 128, 128, 128, 128] midiNoteToRemove = 255 # Set up MCP4922 dual DAC daccs = digitalio.DigitalInOut(board.A5) # A5 is DAC CS spi = busio.SPI(board.SCK, board.MOSI) from adafruit_bus_device.spi_device import SPIDevice mcp4922 = SPIDevice(spi, daccs, baudrate=8000000, polarity=0, phase=0)
import audioio import array import time import digitalio from board import SPEAKER, SPEAKER_ENABLE # Switch on the speaker for output. speaker_enable = digitalio.DigitalInOut(SPEAKER_ENABLE) speaker_enable.switch_to_output(value=True) duration = 2 length = 8000 // 1760 wave = array.array("H", [0] * length) wave[0] = int(2**15 - 1) with audioio.AudioOut(SPEAKER, wave) as speaker: speaker.play(loop=True) time.sleep(duration) speaker.stop()
# list all input buttons here buttons = [ digitalio.DigitalInOut(board.D13), digitalio.DigitalInOut(board.D12), digitalio.DigitalInOut(board.D11), digitalio.DigitalInOut(board.D10), digitalio.DigitalInOut(board.D9), digitalio.DigitalInOut(board.D6), digitalio.DigitalInOut(board.D5), digitalio.DigitalInOut(board.SCL), digitalio.DigitalInOut(board.SDA), digitalio.DigitalInOut(board.A1) ] # initialize speaker output pin audio_pin = audioio.AudioOut(board.A0) # initialize all buttons in the list for i in buttons: i.switch_to_input(pull=digitalio.Pull.UP) # test all buttons print("Test Buttons") for index, button in enumerate(buttons): print("Push Button " + str(index)) while button.value: pass print(str(i)) print("Button " + str(index) + " works.")
trellis = adafruit_trellism4.TrellisM4Express() trellis.pixels.brightness = 0.05 note_letters = ['c', 'd', 'e', 'f', 'g', 'a', 'b'] colors = [(255, 0, 0), (255, 127, 0), (255, 255, 0), (0, 255, 0), (0, 0, 255), (46, 43, 95), (139, 0, 255)] notes = {} wave_dict = {3:"sine",4:"triangle",5:"sawtooth",6:"square"} for octave in range(3,7): for note_letter in note_letters: cur_note = "%s%s" % (note_letter, octave) single_octave = "%s%s" % (note_letter, 4) notes[cur_note] = audioio.WaveFile(open("notes/%s/%s.wav" % (wave_dict[octave], single_octave), "rb")) audio = audioio.AudioOut(left_channel=board.A0, right_channel=board.A1) mixer = audioio.Mixer(voice_count=7, sample_rate=8000, channel_count=2, bits_per_sample=16, samples_signed=True) audio.play(mixer) for i, color in enumerate(colors): trellis.pixels[i,0] = color trellis.pixels[i,1] = color trellis.pixels[i,2] = color trellis.pixels[i,3] = color prev_pressed = [] while True: #print(trellis.pressed_keys) cur_keys = trellis.pressed_keys if cur_keys != prev_pressed:
# make the 2 input buttons buttonA = DigitalInOut(board.BUTTON_A) buttonA.direction = Direction.INPUT buttonA.pull = Pull.DOWN n_pixels = 10 pixels = neopixel.NeoPixel(board.NEOPIXEL, n_pixels, auto_write=False) # "gong.wav" is for external speaker # Use "gong-4db.wav" for internal speaker with lower volume # "gong-54db.wav" is for debugging silently at night... audiofiles = ["gong-4db.wav", "gong-54db.wav", "gong.wav"] filename = audiofiles[0] f = open(filename, "rb") audio = audioio.AudioOut(board.A0, f) ticker = 0 pattern = 0 # Idea is taken from https://github.com/adafruit/Adafruit_Python_WS2801/blob/master/examples/rainbow.py # Define the wheel function to interpolate between different hues. def wheel(pos): """ Takes pos value (0-255) and return RGB color in wheel """ if pos < 85: return (pos * 3, 255 - pos * 3, 0) elif pos < 170: pos -= 85 return (255 - pos * 3, 0, pos * 3) else: pos -= 170
def __init__(self): self.dac = audioio.AudioOut(board.A0)
def _generate_sample(self, length=100): if self._sample is not None: return self._sine_wave = array.array("H", PyBadger._sine_sample(length)) self._sample = audioio.AudioOut(board.SPEAKER) self._sine_wave_sample = audioio.RawSample(self._sine_wave)
BUTTON = crickit.SIGNAL1 crickit.seesaw.pin_mode(BUTTON, crickit.seesaw.INPUT_PULLUP) # LED connected to 5V & Drive pin #1: LED = crickit.drive_1 LED.duty_cycle = 65535 # Find all Wave files in CIRCUITPY storage: WAVEFILES = [ file for file in os.listdir("/") if (file.endswith(".wav") and not file.startswith("._")) ] print("Audio files found:", WAVEFILES) # Audio playback object: AUDIO = audioio.AudioOut(board.A0) # Function to play a wave file in its entirety: def play_file(wavfile): print("Playing", wavfile) with open(wavfile, "rb") as f: wav = audiocore.WaveFile(f) AUDIO.play(wav) while AUDIO.playing: LED.duty_cycle = random.randint(5000, 30000) time.sleep(0.1) LED.duty_cycle = 65535 while True:
#------------------------------------------------------------------------------------------- while True: """ Toggle status LED on Feather. Comment this part out after debugging. """ status_led.value = True time.sleep(0.5) status_led.value = False time.sleep(0.5) """ Get accelerometer reading and do calculation """ ACCEL_X, ACCEL_Y, ACCEL_Z = ACCEL.acceleration # read accelerometer ACCEL_SQUARED = ACCEL_X * ACCEL_X + ACCEL_Z * ACCEL_Z + ACCEL_Y * ACCEL_Y """ Check if holocron movement was above threshold. If it was, begin playing sound. This part of the code blocks until sound is complete. """ if (ACCEL_SQUARED > MOVE_THRESH): with audioio.AudioOut( board.A0 ) as AUDIO: # speaker connected to analog out (pin A0 on Feather m0) wave_file = open(WAV_FILE_NAME, "rb") # open .wav wave = audioio.WaveFile(wave_file) AUDIO.play(wave) # start audio """ While audio plays, animate a breathing effect on the Jewel""" i = NORM_BRIGHTNESS * 100 # convert to number 0-100 instead of fractional number while AUDIO.playing: """ Increase in brightness to max. Break early if the audio finishes playing """ while i < (MAX_BRIGHTNESS * 100) and AUDIO.playing: JEWEL.brightness = (i / 100.0) i += 1
mid_x = 256.0 mid_y = 256.0 mult_x = dac_x_max / range_x mult_y = dac_y_max / range_y ### https://github.com/adafruit/circuitpython/issues/1992 print("length of rawdata", len(rawdata)) use_wav = True poor_wav_bug_workaround = False leave_wav_looping = True ### A0 will be x, A1 will be y if use_wav: print("Using audioio.RawSample for DACs") dacs = audioio.AudioOut(board.A0, right_channel=board.A1) else: print("Using analogio.AnalogOut for DACs") a0 = analogio.AnalogOut(board.A0) a1 = analogio.AnalogOut(board.A1) ### 10Hz is about ok for AudioOut, optimistic for AnalogOut frame_t = 1 / 10 prev_t = time.monotonic() angle = 0 ### in radians frame = 1 while True: ##print("Transforming data for frame:", frame, "at", prev_t) ### Rotate the points of the vector graphic around its centre idx = 0
print(3) time.sleep(1) print(2) time.sleep(1) print(1) time.sleep(1) #print("recording", time.monotonic()) print("recording") #trigger = digitalio.DigitalInOut(board.A1) #trigger.switch_to_output(value = True) with audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA) as mic: mic.record(buf, len(buf)) #trigger.value = False #print("done recording", time.monotonic()) print("done recording") speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) speaker_enable.switch_to_output(value=True) time.sleep(1) #trigger.value = True #print("playback", time.monotonic()) print("playback") with audioio.AudioOut(board.SPEAKER, buf) as speaker: speaker.frequency = 8000 speaker.play() while speaker.playing: pass #trigger.value = False
backlight.duty_cycle = 65535 except: board.DISPLAY.auto_brightness = False board.DISPLAY.brightness = 1.0 # define the bounding boxes for each button red_button = ((25, 30), (65, 80)) yellow_button = ((25, 100), (65, 150)) blue_button = ((25, 170), (65, 230)) # and then make a list with all the button boxes and wave files buttons = ((red_button, cwd + "/red.wav"), (yellow_button, cwd + "/yellow.wav"), (blue_button, cwd + "/blue.wav")) audio = audioio.AudioOut(board.AUDIO_OUT) audiofilename = None audiofile = None def play_file(file_name): global audiofile, audiofilename print("Playing", file_name) if audio.playing: # stop previous audio file if audiofilename == file_name: # same file, bail! return audio.pause audiofile.close() # and play this file audiofile = open(file_name, "rb") audiofilename = file_name
button = DigitalInOut(board.BUTTON_A) button.direction = Direction.INPUT button.pull = Pull.DOWN # Generate one period of sine wav. length = SAMPLERATE // FREQUENCY sine_wave = array.array("H", [0] * length) for i in range(length): sine_wave[i] = int(math.sin(math.pi * 2 * i / 18) * (2**15) + 2**15) # enable the speaker spkrenable = DigitalInOut(board.SPEAKER_ENABLE) spkrenable.direction = Direction.OUTPUT spkrenable.value = True sample = audioio.AudioOut(board.SPEAKER, sine_wave) sample.frequency = SAMPLERATE # Setup the pixels pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.2, auto_write=False) pixels.fill((0, 0, 0)) pixels.show() # Setup the controller controller = AnalogIn(board.A1) while True: dir_x = 1 dir_y = 1 speed_x = 5
def __init__(self, *, url=None, headers=None, json_path=None, regexp_path=None, default_bg=0x000000, status_neopixel=None, text_font=None, text_position=None, text_color=0x808080, text_wrap=False, text_maxlen=0, text_transform=None, image_json_path=None, image_resize=None, image_position=None, caption_text=None, caption_font=None, caption_position=None, caption_color=0x808080, success_callback=None, debug=False): self._debug = debug try: self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT) # pylint: disable=no-member except ValueError: self._backlight = None self.set_backlight(1.0) # turn on backlight self._url = url self._headers = headers if json_path: if isinstance(json_path[0], (list, tuple)): self._json_path = json_path else: self._json_path = (json_path,) else: self._json_path = None self._regexp_path = regexp_path self._success_callback = success_callback if status_neopixel: self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2) else: self.neopix = None self.neo_status(0) try: os.stat(LOCALFILE) self._uselocal = True except OSError: self._uselocal = False if self._debug: print("Init display") self.splash = displayio.Group(max_size=15) if self._debug: print("Init background") self._bg_group = displayio.Group(max_size=1) self._bg_file = None self._default_bg = default_bg self.splash.append(self._bg_group) # show thank you and bootup file if available for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"): try: os.stat(bootscreen) board.DISPLAY.show(self.splash) for i in range(100, -1, -1): # dim down self.set_backlight(i/100) time.sleep(0.005) self.set_background(bootscreen) board.DISPLAY.wait_for_frame() for i in range(100): # dim up self.set_backlight(i/100) time.sleep(0.005) time.sleep(2) except OSError: pass # they removed it, skip! self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE) self._speaker_enable.switch_to_output(False) self.audio = audioio.AudioOut(board.AUDIO_OUT) try: self.play_file("pyportal_startup.wav") except OSError: pass # they deleted the file, no biggie! # Make ESP32 connection if self._debug: print("Init ESP32") esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_gpio0 = DigitalInOut(board.ESP_GPIO0) esp32_reset = DigitalInOut(board.ESP_RESET) esp32_cs = DigitalInOut(board.ESP_CS) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) self._esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset, esp32_gpio0) #self._esp._debug = 1 for _ in range(3): # retries try: print("ESP firmware:", self._esp.firmware_version) break except RuntimeError: print("Retrying ESP32 connection") time.sleep(1) self._esp.reset() else: raise RuntimeError("Was not able to find ESP32") requests.set_interface(self._esp) if url and not self._uselocal: self._connect_esp() # set the default background self.set_background(self._default_bg) board.DISPLAY.show(self.splash) if self._debug: print("Init SD Card") sd_cs = DigitalInOut(board.SD_CS) self._sdcard = None try: self._sdcard = adafruit_sdcard.SDCard(spi, sd_cs) vfs = storage.VfsFat(self._sdcard) storage.mount(vfs, "/sd") except OSError as error: print("No SD card found:", error) self._qr_group = None if self._debug: print("Init caption") self._caption = None if caption_font: self._caption_font = bitmap_font.load_font(caption_font) self.set_caption(caption_text, caption_position, caption_color) if text_font: if isinstance(text_position[0], (list, tuple)): num = len(text_position) if not text_wrap: text_wrap = [0] * num if not text_maxlen: text_maxlen = [0] * num if not text_transform: text_transform = [None] * num else: num = 1 text_position = (text_position,) text_color = (text_color,) text_wrap = (text_wrap,) text_maxlen = (text_maxlen,) text_transform = (text_transform,) self._text = [None] * num self._text_color = [None] * num self._text_position = [None] * num self._text_wrap = [None] * num self._text_maxlen = [None] * num self._text_transform = [None] * num self._text_font = bitmap_font.load_font(text_font) if self._debug: print("Loading font glyphs") # self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' # b'0123456789:/-_,. ') gc.collect() for i in range(num): if self._debug: print("Init text area", i) self._text[i] = None self._text_color[i] = text_color[i] self._text_position[i] = text_position[i] self._text_wrap[i] = text_wrap[i] self._text_maxlen[i] = text_maxlen[i] self._text_transform[i] = text_transform[i] else: self._text_font = None self._text = None self._image_json_path = image_json_path self._image_resize = image_resize self._image_position = image_position if image_json_path: if self._debug: print("Init image path") if not self._image_position: self._image_position = (0, 0) # default to top corner if not self._image_resize: self._image_resize = (320, 240) # default to full screen if self._debug: print("Init touchscreen") # pylint: disable=no-member self.touchscreen = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR, board.TOUCH_YD, board.TOUCH_YU, calibration=((5200, 59000), (5800, 57000)), size=(320, 240)) # pylint: enable=no-member self.set_backlight(1.0) # turn on backlight gc.collect()
color_mode = 0 oldidx = 0 newidx = 0 delta = 0 newx = 0 newy = 0 occupied_bits = [False for _ in range(WIDTH * HEIGHT)] # Add Audio file... f = open("water-click.wav", "rb") wav = audiocore.WaveFile(f) print("%d channels, %d bits per sample, %d Hz sample rate " % (wav.channel_count, wav.bits_per_sample, wav.sample_rate)) audio = audioio.AudioOut(board.A1) #audio.play(wav) def index_of_xy(x, y): """Convert an x/column and y/row into an index into a linear pixel array. :param int x: column value :param int y: row value """ return (y >> 8) * WIDTH + (x >> 8) def already_present(limit, x, y): """Check if a pixel is already used. :param int limit: the index into the grain array of
# start by showing start splash display.show(start_group) # setup for break beam LED pin break_beam = digitalio.DigitalInOut(board.A1) break_beam.direction = digitalio.Direction.INPUT break_beam.pull = digitalio.Pull.UP # setup for button pin button = digitalio.DigitalInOut(board.D4) button.direction = digitalio.Direction.INPUT button.pull = digitalio.Pull.UP # setup for speaker pin speaker = audioio.AudioOut(board.A0) # mp3 decoder setup file = "/hoopBloop0.mp3" mp3stream = audiomp3.MP3Decoder(open(file, "rb")) # state machines used in the loop score = 0 hoops = False button_state = False beam_state = False sample = 0 while True: # button debouncing if not button.value and not button_state:
import usb_midi #import neopixel import adafruit_midi from adafruit_midi.note_on import NoteOn from adafruit_midi.note_off import NoteOff #from adafruit_midi.control_change import ControlChange #from adafruit_midi.pitch_bend import PitchBend # Turn the speaker on speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) speaker_enable.direction = digitalio.Direction.OUTPUT speaker_enable.value = True dac = audioio.AudioOut(board.SPEAKER) # 440Hz is the standard frequency for A4 (A above middle C) # MIDI defines middle C as 60 and modulation wheel is cc 1 by convention A4refhz = const(440) midi_note_A4 = 69 # magic_factor is playing things slower as the noise needs # to cover a long period to be convincing # Can get this to 1536 if it's allocated before import adafruit_midi # but half_wave_len must be an integer so dictates lower magic_factor sample_len = 1024 magic_factor = 512 # base_sample_rate may end up as non integer base_sample_rate = A4refhz / magic_factor * sample_len max_sample_rate = 350000 # a CPX / M0 DAC limitation
def __init__( self, *, url=None, headers=None, json_path=None, regexp_path=None, default_bg=0x000000, status_neopixel=None, text_font=None, text_position=None, text_color=0x808080, text_wrap=False, text_maxlen=0, text_transform=None, json_transform=None, image_json_path=None, image_resize=None, image_position=None, image_dim_json_path=None, caption_text=None, caption_font=None, caption_position=None, caption_color=0x808080, image_url_path=None, success_callback=None, esp=None, external_spi=None, debug=False ): self._debug = debug try: if hasattr(board, "TFT_BACKLIGHT"): self._backlight = pulseio.PWMOut( board.TFT_BACKLIGHT ) # pylint: disable=no-member elif hasattr(board, "TFT_LITE"): self._backlight = pulseio.PWMOut( board.TFT_LITE ) # pylint: disable=no-member except ValueError: self._backlight = None self.set_backlight(1.0) # turn on backlight self._url = url self._headers = headers if json_path: if isinstance(json_path[0], (list, tuple)): self._json_path = json_path else: self._json_path = (json_path,) else: self._json_path = None self._regexp_path = regexp_path self._success_callback = success_callback if status_neopixel: self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2) else: self.neopix = None self.neo_status(0) try: os.stat(LOCALFILE) self._uselocal = True except OSError: self._uselocal = False if self._debug: print("Init display") self.splash = displayio.Group(max_size=15) if self._debug: print("Init background") self._bg_group = displayio.Group(max_size=1) self._bg_file = None self._default_bg = default_bg self.splash.append(self._bg_group) # show thank you and bootup file if available for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"): try: os.stat(bootscreen) board.DISPLAY.show(self.splash) for i in range(100, -1, -1): # dim down self.set_backlight(i / 100) time.sleep(0.005) self.set_background(bootscreen) try: board.DISPLAY.refresh(target_frames_per_second=60) except AttributeError: board.DISPLAY.wait_for_frame() for i in range(100): # dim up self.set_backlight(i / 100) time.sleep(0.005) time.sleep(2) except OSError: pass # they removed it, skip! self._speaker_enable = 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!") try: self.play_file("pyportal_startup.wav") except OSError: pass # they deleted the file, no biggie! if esp: # If there was a passed ESP Object if self._debug: print("Passed ESP32 to PyPortal") self._esp = esp if external_spi: # If SPI Object Passed spi = external_spi else: # Else: Make ESP32 connection spi = busio.SPI(board.SCK, board.MOSI, board.MISO) else: if self._debug: print("Init ESP32") esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_gpio0 = DigitalInOut(board.ESP_GPIO0) esp32_reset = DigitalInOut(board.ESP_RESET) esp32_cs = DigitalInOut(board.ESP_CS) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) self._esp = adafruit_esp32spi.ESP_SPIcontrol( spi, esp32_cs, esp32_ready, esp32_reset, esp32_gpio0 ) # self._esp._debug = 1 for _ in range(3): # retries try: print("ESP firmware:", self._esp.firmware_version) break except RuntimeError: print("Retrying ESP32 connection") time.sleep(1) self._esp.reset() else: raise RuntimeError("Was not able to find ESP32") requests.set_socket(socket, self._esp) if url and not self._uselocal: self._connect_esp() if self._debug: print("My IP address is", self._esp.pretty_ip(self._esp.ip_address)) # set the default background self.set_background(self._default_bg) board.DISPLAY.show(self.splash) if self._debug: print("Init SD Card") sd_cs = DigitalInOut(board.SD_CS) self._sdcard = None try: self._sdcard = adafruit_sdcard.SDCard(spi, sd_cs) vfs = storage.VfsFat(self._sdcard) storage.mount(vfs, "/sd") except OSError as error: print("No SD card found:", error) self._qr_group = None # Tracks whether we've hidden the background when we showed the QR code. self._qr_only = False if self._debug: print("Init caption") self._caption = None if caption_font: self._caption_font = bitmap_font.load_font(caption_font) self.set_caption(caption_text, caption_position, caption_color) if text_font: if isinstance(text_position[0], (list, tuple)): num = len(text_position) if not text_wrap: text_wrap = [0] * num if not text_maxlen: text_maxlen = [0] * num if not text_transform: text_transform = [None] * num else: num = 1 text_position = (text_position,) text_color = (text_color,) text_wrap = (text_wrap,) text_maxlen = (text_maxlen,) text_transform = (text_transform,) self._text = [None] * num self._text_color = [None] * num self._text_position = [None] * num self._text_wrap = [None] * num self._text_maxlen = [None] * num self._text_transform = [None] * num self._text_font = bitmap_font.load_font(text_font) if self._debug: print("Loading font glyphs") # self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' # b'0123456789:/-_,. ') gc.collect() for i in range(num): if self._debug: print("Init text area", i) self._text[i] = None self._text_color[i] = text_color[i] self._text_position[i] = text_position[i] self._text_wrap[i] = text_wrap[i] self._text_maxlen[i] = text_maxlen[i] self._text_transform[i] = text_transform[i] else: self._text_font = None self._text = None # Add any JSON translators self._json_transform = [] if json_transform: if callable(json_transform): self._json_transform.append(json_transform) else: self._json_transform.extend(filter(callable, json_transform)) self._image_json_path = image_json_path self._image_url_path = image_url_path self._image_resize = image_resize self._image_position = image_position self._image_dim_json_path = image_dim_json_path if image_json_path or image_url_path: if self._debug: print("Init image path") if not self._image_position: self._image_position = (0, 0) # default to top corner if not self._image_resize: self._image_resize = ( board.DISPLAY.width, board.DISPLAY.height, ) # default to full screen if hasattr(board, "TOUCH_XL"): if self._debug: print("Init touchscreen") # pylint: disable=no-member self.touchscreen = adafruit_touchscreen.Touchscreen( board.TOUCH_XL, board.TOUCH_XR, board.TOUCH_YD, board.TOUCH_YU, calibration=((5200, 59000), (5800, 57000)), size=(board.DISPLAY.width, board.DISPLAY.height), ) # pylint: enable=no-member self.set_backlight(1.0) # turn on backlight elif hasattr(board, "BUTTON_CLOCK"): if self._debug: print("Init cursor") self.mouse_cursor = Cursor( board.DISPLAY, display_group=self.splash, cursor_speed=8 ) self.mouse_cursor.hide() self.cursor = CursorManager(self.mouse_cursor) else: raise AttributeError( "PyPortal module requires either a touchscreen or gamepad." ) gc.collect()
# Servo angles MOUTH_START = 95 MOUTH_END = 90 # 17 is labeled SERVO 1 on CRICKIT pwm = PWMOut(seesaw, 17) # must be 50 cannot change pwm.frequency = 50 # microservo usually is 400/2500 (tower pro sgr2r) my_servo = servo.Servo(pwm, min_pulse=400, max_pulse=2500) # Starting servo locations my_servo.angle = MOUTH_START # Audio playback object and helper to play a full file a = audioio.AudioOut(board.A0) def play_file(wavfile): print("Playing", wavfile) with open(wavfile, "rb") as f: wav = audioio.WaveFile(f) a.play(wav) while a.playing: my_servo.angle = MOUTH_END time.sleep(.15) my_servo.angle = MOUTH_START time.sleep(.15) while True:
for i in range(llength): low_freq_wave[i] = int( (1 + math.sin(math.pi * 2 * i / llength)) * tone_volume * (2**15 - 1)) frequency = 1600 # Set this to the Hz of the tone you want to generate. length = 8000 // frequency high_freq_wave = array.array("H", [0] * length) for i in range(length): high_freq_wave[i] = int( (1 + math.sin(math.pi * 2 * i / length)) * tone_volume * (2**15 - 1)) #audio = audioio.AudioOut(board.A0, board.A0) #low_freq_wave_sample = audioio.RawSample(low_freq_wave) f = open("laugh.wav", "rb") a = audioio.AudioOut(board.A0, f) analog_in = AnalogIn(board.A1) i = 0 while True: #print(analog_in.value) if (signal_to_send[i] == 1): a = audioio.AudioOut(board.A0, high_freq_wave) print("playing") a.play(loop=True) time.sleep(signal_length / 2) a.stop() time.sleep(signal_length / 2) else: a = audioio.AudioOut(board.A0, low_freq_wave) print("playing")