|
| 1 | +// SPDX-FileCopyrightText: 2023 Kattni Rembor for Adafruit Industries |
| 2 | +// SPDX-FileCopyrightText: Earle F. Philhower, III |
| 3 | +// |
| 4 | +// SPDX-License-Identifier: MIT |
| 5 | + |
| 6 | +/* |
| 7 | + This example plays a tune through a mono amplifier using a simple sine wave. |
| 8 | +
|
| 9 | + Released to the public domain by Earle F. Philhower, III <earlephilhower@yahoo.com> |
| 10 | +
|
| 11 | + Adapted from stereo original example 2023 by Kattni Rembor |
| 12 | +*/ |
| 13 | + |
| 14 | +#include <PWMAudio.h> |
| 15 | + |
| 16 | +PWMAudio pwm(0, true); // GP0 = left, GP1 = right |
| 17 | + |
| 18 | +const int freq = 48000; // Output frequency for PWM |
| 19 | + |
| 20 | +int16_t mono = 0; |
| 21 | + |
| 22 | +const int notes[] = { 784, 880, 698, 349, 523 }; |
| 23 | +const int dly[] = { 400, 500, 700, 500, 1000 }; |
| 24 | +const int noteCnt = sizeof(notes) / sizeof(notes[0]); |
| 25 | + |
| 26 | +int freqMono = 1; |
| 27 | + |
| 28 | +double sineTable[128]; // Precompute sine wave in 128 steps |
| 29 | + |
| 30 | +unsigned int cnt = 0; |
| 31 | +void cb() { |
| 32 | + while (pwm.availableForWrite()) { |
| 33 | + double now = ((double)cnt) / (double)freq; |
| 34 | + int freqScale = freqMono << 7; // Prescale by 128 to avoid FP math later on |
| 35 | + pwm.write((int16_t)(mono * sineTable[(int)(now * freqScale) & 127])); |
| 36 | + cnt++; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +void setup() { |
| 41 | + // Set up sine table for waveform generation |
| 42 | + for (int i = 0; i < 128; i++) { |
| 43 | + sineTable[i] = sin(i * 2.0 * 3.14159 / 128.0); |
| 44 | + } |
| 45 | + pwm.setBuffers(4, 32); // Give larger buffers since we're are 48khz sample rate |
| 46 | + pwm.onTransmit(cb); |
| 47 | + pwm.begin(freq); |
| 48 | +} |
| 49 | + |
| 50 | +void loop() { |
| 51 | + delay(1000); |
| 52 | + mono = 0; |
| 53 | + Serial.println("loop"); |
| 54 | + for (int i = 0; i < noteCnt; i++) { |
| 55 | + freqMono = notes[i]; |
| 56 | + mono = 5000; |
| 57 | + delay(dly[i]); |
| 58 | + } |
| 59 | + mono = 0; |
| 60 | + delay(3000); |
| 61 | +} |
0 commit comments