#!/usr/bin/env python3 import sys import struct import subprocess import re import os import os.path import argparse UF2_MAGIC_START0 = 0x0A324655 # "UF2\n" UF2_MAGIC_START1 = 0x9E5D5157 # Randomly selected UF2_MAGIC_END = 0x0AB16F30 # Ditto INFO_FILE = "/INFO_UF2.TXT" appstartaddr = 0x2000 familyid = 0x0 def is_uf2(buf): w = struct.unpack(" #include #if PICO_ON_DEVICE #include "hardware/clocks.h" #include "hardware/structs/clocks.h" #endif #include "pico/stdlib.h" #if USE_AUDIO_SPDIF #include "pico/audio_spdif.h" #endif #define SINE_WAVE_TABLE_LEN 2048 #define SAMPLES_PER_BUFFER 256 static int16_t sine_wave_table[SINE_WAVE_TABLE_LEN]; struct audio_buffer_pool *init_audio() { static audio_format_t audio_format = { .format = AUDIO_BUFFER_FORMAT_PCM_S16, .sample_freq = 44100, .channel_count = 1 }; static struct audio_buffer_format producer_format = { .format = &audio_format, .sample_stride = 2 }; struct audio_buffer_pool *producer_pool = audio_new_producer_pool(&producer_format, 3, SAMPLES_PER_BUFFER); // todo correct size bool __unused ok; const struct audio_format *output_format; output_format = audio_spdif_setup(&audio_format, &audio_spdif_default_config); if (!output_format) { panic("PicoAudio: Unable to open audio device.\\n"); } //ok = audio_spdif_connect(producer_pool); ok = audio_spdif_connect(producer_pool); assert(ok); audio_spdif_set_enabled(true); return producer_pool; } '''.strip() outbuf += "\n" + convert_to_carray(inpbuf).decode() outbuf += "\n" + ''' #define RESET_btn 12 int main() { stdio_init_all(); gpio_init(RESET_btn); gpio_set_dir(RESET_btn, GPIO_IN); gpio_pull_up(RESET_btn); for (int i = 0; i < SINE_WAVE_TABLE_LEN; i++) { sine_wave_table[i] = 32767 * cosf(i * 2 * (float) (M_PI / SINE_WAVE_TABLE_LEN)); } struct audio_buffer_pool *ap = init_audio(); uint32_t step = 0x10; uint32_t pos = 0; uint32_t pos_max = SINE_WAVE_TABLE_LEN; // pos_max = bindata_len; uint vol = 80; uint melody = 0; while (true) { if (!gpio_get(RESET_btn)) { while (!gpio_get(RESET_btn)) gpio_put(25, 0); melody ^= 1; if (melody==1) pos_max = bindata_len; else pos_max = SINE_WAVE_TABLE_LEN; if (melody==1) step = 0x1; else step = 0x10; pos = 0; } struct audio_buffer *buffer = take_audio_buffer(ap, true); int16_t *samples = (int16_t *) buffer->buffer->bytes; for (uint i = 0; i < buffer->max_sample_count; i++) { if (melody==1) samples[i] = (bindata[pos]) ; else samples[i] = (vol * sine_wave_table[pos]) >> 8u; pos += step; if (pos >= pos_max) pos -= pos_max; } buffer->sample_count = buffer->max_sample_count; give_audio_buffer(ap, buffer); } puts("\\n"); return 0; } '''.strip() ext = "h" else: outbuf = convert_to_uf2(inpbuf) print("Converting to %s, output size: %d, start address: 0x%x" % (ext, len(outbuf), appstartaddr)) if args.output: write_file(args.output, outbuf.encode()) else: write_file("sine_wave_spdif.c", outbuf.encode()) if __name__ == "__main__": main()