|
| 1 | + /* |
| 2 | + DAC Melody player |
| 3 | +
|
| 4 | + Generates a series of tones from MIDI note values |
| 5 | + using the Uno R4 DAC and the AnalogWave Library. |
| 6 | + The melody is "Frere Jacques" |
| 7 | +
|
| 8 | +circuit: |
| 9 | + * audio amp (LM386 used for testing) input+ attached to A0 |
| 10 | + * audio amp input- attached to ground |
| 11 | + * 4-8-ohm speaker attached to amp output+ |
| 12 | + * Potentiometer connected to pin A5 |
| 13 | +
|
| 14 | + created 13 Feb 2017 |
| 15 | + modified 3 Jul 2023 |
| 16 | + by Tom Igoe |
| 17 | +*/ |
| 18 | +#include "analogWave.h" |
| 19 | +analogWave wave(DAC); |
| 20 | + |
| 21 | +#define NOTE_A4 69 // MIDI note value for middle A |
| 22 | +#define FREQ_A4 440 // frequency for middle A |
| 23 | + |
| 24 | +// the tonic, or first note of the key signature for the song: |
| 25 | +int tonic = 65; |
| 26 | +// the melody sequence. Note values are relative to the tonic: |
| 27 | +int melody[] = {1, 3, 5, 1, |
| 28 | + 1, 3, 5, 1, |
| 29 | + 5, 6, 8, 5, 6, 8, |
| 30 | + 8, 10, 8, 6, 5, 1, |
| 31 | + 8, 10, 8, 6, 5, 1, |
| 32 | + 1, -4, 1, |
| 33 | + 1, -4, 1 |
| 34 | + }; |
| 35 | +// the rhythm sequence. Values are 1/note, e.g. 4 = 1/4 note: |
| 36 | +int rhythm[] = {4, 4, 4, 4, |
| 37 | + 4, 4, 4, 4, |
| 38 | + 4, 4, 2, |
| 39 | + 4, 4, 2, |
| 40 | + 8, 8, 8, 8, 4, 4, |
| 41 | + 8, 8, 8, 8, 4, 4, |
| 42 | + 4, 4, 2, |
| 43 | + 4, 4, 2 |
| 44 | + }; |
| 45 | +// which note of the melody to play: |
| 46 | +int noteCounter = 0; |
| 47 | + |
| 48 | +int bpm = 120; // beats per minute |
| 49 | +// duration of a beat in ms |
| 50 | +float beatDuration = 60.0 / bpm * 1000; |
| 51 | + |
| 52 | +void setup() { |
| 53 | +// start the sine wave generator: |
| 54 | + wave.sine(10); |
| 55 | +} |
| 56 | + |
| 57 | +void loop() { |
| 58 | + // current note is an element of the array: |
| 59 | + int currentNote = melody[noteCounter] + tonic; |
| 60 | + // play a note from the melody: |
| 61 | + // convert MIDI note number to frequency: |
| 62 | + float frequency = FREQ_A4 * pow(2, ((currentNote - NOTE_A4) / 12.0)); |
| 63 | + |
| 64 | + // all the notes in this are sixteenth notes, |
| 65 | + // which is 1/4 of a beat, so: |
| 66 | + float noteDuration = beatDuration * (4.0 / rhythm[noteCounter]); |
| 67 | + // turn the note on: |
| 68 | + wave.freq(frequency); |
| 69 | + // tone(speakerPin, frequency, noteDuration * 0.85); |
| 70 | + // keep it on for the appropriate duration: |
| 71 | + delay(noteDuration * 0.85); |
| 72 | + wave.stop(); |
| 73 | + delay(noteDuration * 0.15); |
| 74 | + // turn the note off: |
| 75 | + // noTone(speakerPin); |
| 76 | + // increment the note number for next time through the loop: |
| 77 | + noteCounter++; |
| 78 | + // keep the note in the range from 0 - 32 using modulo: |
| 79 | + noteCounter = noteCounter % 32; |
| 80 | + |
| 81 | +} |
0 commit comments