tone-generator/tone.hpp

40 lines
595 B
C++
Raw Normal View History

2024-08-19 22:43:24 +10:00
#pragma once
#include <inttypes.h>
2024-10-03 22:42:51 +10:00
#include <avr/pgmspace.h>
2024-10-01 13:39:28 +10:00
#include "util.hpp"
2024-08-19 22:43:24 +10:00
2024-10-03 22:42:51 +10:00
extern const PROGMEM int8_t TONE_LOOKUP[4][256];
2024-08-19 22:43:24 +10:00
struct Tone {
enum Type {
tt_sine = 0,
tt_saw = 1,
tt_square = 2,
tt_triangle = 3,
};
2024-08-19 22:43:24 +10:00
uint32_t phase;
uint16_t frequency;
uint8_t amplitude;
Type mode;
2024-08-19 22:43:24 +10:00
2024-10-01 13:39:28 +10:00
inline bool active() const AW_IN {
2024-08-19 22:43:24 +10:00
return amplitude > 0;
}
2024-10-01 13:39:28 +10:00
inline void update(uint32_t t) AW_IN {
2024-08-19 22:43:24 +10:00
phase += t * frequency;
}
2024-10-01 13:39:28 +10:00
inline int get() const AW_IN {
2024-10-03 22:42:51 +10:00
int8_t v = pgm_read_byte_near(&TONE_LOOKUP[mode][(uint8_t)(phase >> 12)]);
return (int)v * amplitude;
2024-08-19 22:43:24 +10:00
}
};