From 8b072db7335cdcd6e05c282afbf07b22bff7863d Mon Sep 17 00:00:00 2001 From: loooph Date: Fri, 3 Sep 2021 22:59:14 +0200 Subject: [PATCH] cleanup and test sinewave --- include/filters.hpp | 7 +++++++ include/generators.hpp | 27 ++++++++++++++++++++++++++ src/main.cpp | 44 +++++++++++++++++++++++++++++++++++++----- 3 files changed, 73 insertions(+), 5 deletions(-) create mode 100644 include/filters.hpp create mode 100644 include/generators.hpp diff --git a/include/filters.hpp b/include/filters.hpp new file mode 100644 index 0000000..426e50b --- /dev/null +++ b/include/filters.hpp @@ -0,0 +1,7 @@ +#include + +#include + +auto simplest_lowpass(Function f_in) { + Function f_out; +} diff --git a/include/generators.hpp b/include/generators.hpp new file mode 100644 index 0000000..7376e5c --- /dev/null +++ b/include/generators.hpp @@ -0,0 +1,27 @@ +#include +#include + +template +int16_t sine(uint32_t t) { + // 0 <= t < period is 0 <= t_2pi < 2 pi + float t_2pi = 2 * M_PI / static_cast(period) * t; + return static_cast(sinf(t_2pi) * max_val); +} + +template +int16_t square(uint32_t t) { + if (t <= period / 2) { + return -max_val; + } else { + return max_val; + } +} + +template +int16_t sawtooth(uint32_t t) { + // f(t) = a t + y + // f(0) = -max_val = y + // f(period) = a * period - max_val = max_val + // a = 2 * max_val / period + return 2 * max_val * t / period - max_val; +} diff --git a/src/main.cpp b/src/main.cpp index 8931747..2f12972 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,14 +1,48 @@ #include -constexpr unsigned SWITCH_DELAY_MS = 2000; +#include "generators.hpp" +#include "filters.hpp" + +constexpr int DAC_PIN = A2; + +constexpr uint16_t SAMPLING_RATE_HZ = 8000; + +constexpr unsigned long SAMPLE_US = 1000000 / SAMPLING_RATE_HZ; + +#ifndef LED_BUILTIN + #define LED_BUILTIN PC13 +#endif + +unsigned long last_time_us = 0; + +int16_t val; + +bool sample_computed = false; + +constexpr uint32_t hz_to_micros(uint32_t hz) { + return 1000000 / hz; +} void setup() { delay(3000); } void loop() { - int val = analogRead(A0); - delay(20); - analogWrite(PA_4, val); - delay(20); + unsigned long time_us = micros(); + unsigned long delta = time_us - last_time_us; + if (!sample_computed) { + if (delta < SAMPLE_US) { + constexpr uint32_t period = hz_to_micros(412); + val = sine(time_us % period); + sample_computed = true; + } + } + else { + if (delta >= SAMPLE_US) { + last_time_us = time_us; + analogWrite(DAC_PIN, val); + sample_computed = false; + } + } + delayMicroseconds(1); }