1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
-
-
- #ifndef __SPEAKER_H__
- #define __SPEAKER_H__
-
- #include "buzzer.h"
-
- class Speaker: public Buzzer {
- private:
- typedef Buzzer super;
-
- struct state_t {
- tone_t tone;
- uint16_t period;
- uint16_t cycles;
- } state;
-
- protected:
-
-
- void reset() {
- super::reset();
- this->state.period = 0;
- this->state.cycles = 0;
- }
-
- public:
-
-
- Speaker() {
- this->reset();
- }
-
-
-
- virtual void tick() {
- if (!this->state.cycles) {
- if (this->buffer.isEmpty()) return;
-
- this->reset();
- this->state.tone = this->buffer.dequeue();
-
-
- this->state.period = 1000000UL / this->state.tone.frequency;
-
- this->state.cycles =
- (this->state.tone.duration * 1000L) / this->state.period;
-
- this->state.period >>= 1;
- this->state.cycles <<= 1;
-
- }
- else {
- uint32_t const us = micros();
- static uint32_t next = us + this->state.period;
-
- if (us >= next) {
- --this->state.cycles;
- next = us + this->state.period;
- if (this->state.tone.frequency > 0) this->invert();
- }
- }
- }
- };
-
- #endif
|