From 8b0c7e98b8f4d7afe952801a05092d7ed4d0d7ee Mon Sep 17 00:00:00 2001 From: iabdalkader Date: Wed, 15 Feb 2023 15:26:54 +0100 Subject: [PATCH] Examples: Add waveform generator example. --- .../Waveform_Generator/Waveform_Generator.ino | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 examples/Waveform_Generator/Waveform_Generator.ino diff --git a/examples/Waveform_Generator/Waveform_Generator.ino b/examples/Waveform_Generator/Waveform_Generator.ino new file mode 100644 index 0000000..d6a80b5 --- /dev/null +++ b/examples/Waveform_Generator/Waveform_Generator.ino @@ -0,0 +1,121 @@ +// This example generates different waveforms based on user input on A12/DAC1. + +#include "AdvancedDAC.h" + +#define N_SAMPLES (256) +#define DEFAULT_FREQUENCY (16000) + +AdvancedDAC dac1(A12); +uint8_t SAMPLES_BUFFER[N_SAMPLES]; +size_t dac_frequency = DEFAULT_FREQUENCY; + +void generate_waveform(int cmd) +{ + switch (cmd) { + case 't': + // Triangle wave + Serial.print("Waveform: Triangle "); + for (int i=0; i 1000) { + dac_frequency /= 2; + } else { + break; + } + + dac1.stop(); + delay(500); + if (!dac1.begin(AN_RESOLUTION_8, dac_frequency * N_SAMPLES, N_SAMPLES, 32)) { + Serial.println("Failed to start DAC1 !"); + } + delay(500); + break; + + default: + Serial.print("Unknown command "); + Serial.println((char) cmd); + return; + } + + Serial.print(dac_frequency/1000); + Serial.println("KHz"); +} + +void setup() { + Serial.begin(115200); + + while (!Serial) { + + } + + + Serial.println("Enter a command:"); + Serial.println("t: Triangle wave"); + Serial.println("q: Square wave"); + Serial.println("s: Sine wave"); + Serial.println("r: Sawtooth wave"); + Serial.println("+: Increase frequency"); + Serial.println("-: Decrease frequency"); + + generate_waveform('s'); + + // DAC initialization + if (!dac1.begin(AN_RESOLUTION_8, DEFAULT_FREQUENCY * N_SAMPLES, N_SAMPLES, 32)) { + Serial.println("Failed to start DAC1 !"); + while (1); + } +} + +void loop() { + if (Serial.available() > 0) { + int cmd = Serial.read(); + if (cmd != '\n') { + generate_waveform(cmd); + } + } + + if (dac1.available()) { + // Get a free buffer for writing. + SampleBuffer buf = dac1.dequeue(); + + // Write data to buffer. + for (size_t i=0; i