Last active
November 14, 2023 00:11
-
-
Save todbot/8df80b8783a615a7e63c383746781916 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# "output" a waveform of a given length at a given frequency | |
import time | |
import math | |
# frequency in Hz of wave | |
frequency = 3 | |
# length of the wave, number of samples in the wave | |
LENGTH = 13 | |
# sine wave values written to the DAC | |
sin_wave = [ | |
int(math.sin(math.pi * 2 * i / LENGTH) * ((2**15) - 1) + 2**15) | |
for i in range(LENGTH) | |
] | |
print(sin_wave) | |
wave_index = 0 # where in the wave we're at | |
wave_sleep = 1 / (frequency * LENGTH) # how long to sleep between wave samples | |
print("wave_sleep:", wave_sleep) | |
time.sleep(1) | |
while True: | |
print( "%5d %d" % (sin_wave[wave_index], wave_index) ) | |
wave_index = (wave_index + 1) % LENGTH | |
time.sleep( wave_sleep ) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# "output" a waveform of a given length at a given frequency | |
# with the ability to change its frequency easily with asyncio | |
import asyncio | |
import time | |
import math | |
# frequency in Hz of wave | |
frequency = 5 | |
# length of the sine wave | |
LENGTH = 13 | |
# sine wave values written to the DAC | |
sin_wave = [ | |
int(math.sin(math.pi * 2 * i / LENGTH) * ((2**15) - 1) + 2**15) | |
for i in range(LENGTH) | |
] | |
print(sin_wave) | |
async def wave_player(): | |
wave_index = 0 | |
while True: | |
wave_sleep = 1/(frequency * LENGTH) | |
print( "%5d %2d %f" % (sin_wave[wave_index], wave_index, wave_sleep) ) | |
wave_index = (wave_index + 1) % LENGTH | |
await asyncio.sleep( wave_sleep ) | |
async def frequency_changer(): | |
global frequency # we change this, so must declare it | |
while True: | |
frequency = 5 | |
print("changing frequency to ", frequency) | |
await asyncio.sleep( 5 ) | |
frequency = 0.3 | |
print("changing frequency to ", frequency) | |
await asyncio.sleep( 5 ) | |
async def main(): | |
task1 = asyncio.create_task( wave_player() ) | |
task2 = asyncio.create_task( frequency_changer() ) | |
await asyncio.gather(task1,task2) | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment