example program outputting some octaves over and over again

master
loooph 2021-09-05 22:27:04 +02:00
parent b60e0a6c46
commit d2d8a9882a
1 changed files with 46 additions and 23 deletions

View File

@ -5,44 +5,67 @@
constexpr int DAC_PIN = A2;
constexpr uint16_t SAMPLING_RATE_HZ = 8000;
constexpr uint32_t SAMPLING_RATE_HZ = 44100;
constexpr unsigned long SAMPLE_US = 1000000 / SAMPLING_RATE_HZ;
#ifndef LED_BUILTIN
#define LED_BUILTIN PC13
#endif
constexpr uint32_t SAMPLE_US = 1000000 / SAMPLING_RATE_HZ;
unsigned long last_time_us = 0;
int16_t val;
int32_t sample, next_sample;
int32_t i = 0;
int32_t sample_count = 0;
bool sample_computed = false;
bool next_sample_computed = false;
constexpr uint32_t hz_to_micros(uint32_t hz) {
return 1000000 / hz;
}
constexpr uint32_t mhz_to_micros(uint32_t mhz) {
return 1000 * hz_to_micros(mhz);
}
template<int32_t min, int32_t max>
constexpr int32_t shift_and_restrict(int32_t val) {
val += (max - min) / 2 + 1;
if (val < min) {
val = min;
}
if (val > max) {
val = max;
}
return val;
}
void writeVal(int32_t val) {
val = shift_and_restrict<0, 255>(val);
analogWrite(DAC_PIN, val);
}
void setup() {
delay(3000);
delay(1000);
}
void loop() {
static int32_t note = -56;
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;
uint32_t delta = time_us - last_time_us;
if (!next_sample_computed) {
constexpr uint32_t period = hz_to_micros(440);
next_sample = stretch(sine<period, 127>, powf(2, note / 12.0), time_us);
next_sample_computed = true;
}
if (delta >= SAMPLE_US) {
last_time_us = time_us;
writeVal(next_sample);
next_sample_computed = false;
++sample_count;
}
if (16 * sample_count >= SAMPLING_RATE_HZ) {
sample_count = 0;
++note;
if (note > 12) {
note = -56;
}
}
else {
if (delta >= SAMPLE_US) {
last_time_us = time_us;
analogWrite(DAC_PIN, val);
sample_computed = false;
}
}
delayMicroseconds(1);
}