cleanup and test sinewave

master
loooph 2021-09-03 22:59:14 +02:00
parent 125a548ddf
commit 8b072db733
3 changed files with 73 additions and 5 deletions

7
include/filters.hpp Normal file
View File

@ -0,0 +1,7 @@
#include <stdint.h>
#include <function.hpp>
auto simplest_lowpass(Function<uint32_t, int16_t> f_in) {
Function<uint32_t, int16_t> f_out;
}

27
include/generators.hpp Normal file
View File

@ -0,0 +1,27 @@
#include <math.h>
#include <stdint.h>
template<uint32_t period, int16_t max_val>
int16_t sine(uint32_t t) {
// 0 <= t < period is 0 <= t_2pi < 2 pi
float t_2pi = 2 * M_PI / static_cast<float>(period) * t;
return static_cast<int16_t>(sinf(t_2pi) * max_val);
}
template<uint32_t period, int16_t max_val>
int16_t square(uint32_t t) {
if (t <= period / 2) {
return -max_val;
} else {
return max_val;
}
}
template<uint32_t period, int16_t max_val>
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;
}

View File

@ -1,14 +1,48 @@
#include <Arduino.h>
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<period, 512>(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);
}