Skip to content

Instantly share code, notes, and snippets.

@todbot
Last active February 16, 2023 23:41
Show Gist options
  • Save todbot/50037e5cebad83381c0b6bab6a81e449 to your computer and use it in GitHub Desktop.
Save todbot/50037e5cebad83381c0b6bab6a81e449 to your computer and use it in GitHub Desktop.
Play audio while also POSTing to a URL on PicoW (or any CircuitPython device with native WiFi)
# audio_plus_http_post.py -- Play audio while also POSTing to a URL on PicoW
# (or any CircuitPython device with native WiFi)
# 16 Feb 2023 - @todbot / Tod Kurt, from @studioStephe(she/they) post on Adafruit Discord
#
# Notes:
# - Glitches on first POST, but subsequent POSTs are glitch free.
# - Could get around this by muting mixer.voice[0].volume on first POST
# - Or could get around by doing throw-away POST before starting audio
# - The glitching appears to be related to DNS lookups?
#
import os
import time, array, math
import board, microcontroller
import wifi, ssl, socketpool
import audiocore, audiomixer, audiopwmio
import adafruit_requests
print("Hello there")
wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
print("Connected to WiFi")
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
post_url = "https://httpbin.org/post"
post_data = {
"someparam1": "Some Important Value",
"someparam2": "Hello_There",
"someparam3": "OhNoData",
}
# create a sinewave array for use with RawSample
def make_sinewave(samplerate, freq):
length = samplerate // freq
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 - 1))
return sine_wave
SAMPLERATE=22050
sine440_buf = make_sinewave(SAMPLERATE, 440)
sine440_raw = audiocore.RawSample(sine440_buf, sample_rate=SAMPLERATE)
# or could use a WAV file
#sine440_wav = audiocore.WaveFile(open("/sine_440_aud.wav", "rb"))
sine440 = sine440_raw # sine440_raw or sine440_wav
# set up audio output and mixer, attach mixer to audio output
audio = audiopwmio.PWMAudioOut(board.GP28)
mixer = audiomixer.Mixer(voice_count=1, sample_rate=SAMPLERATE, channel_count=1,
bits_per_sample=16, samples_signed=True)
audio.play(mixer) # attach mixer to audio
# start playing wav file @ 1/2 volume
print("playing sinewave")
mixer.voice[0].level = .5
mixer.voice[0].play(sine440, loop=True)
while True:
try:
print("-" * 40)
print("Posting to %s" % post_url)
response = requests.request("POST", url=post_url, data=post_data)
print("response: ", response.text)
print("-" * 40)
response.close()
for i in range(10):
print( 10-i,"..", end='')
time.sleep(1)
print()
except Exception as e:
print("Error:\n", str(e))
print("Resetting microcontroller in 10 seconds")
time.sleep(10)
microcontroller.reset()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment