arduino-audio-tools
AudioTimerAVR.h
1 #pragma once
2 
3 #ifdef __AVR__
4 #include "AudioTools/CoreAudio/AudioTimer/AudioTimerBase.h"
5 
6 namespace audio_tools {
7 typedef void (*repeating_timer_callback_t)(void* obj);
8 class TimerAlarmRepeatingDriverAVR;
9 static TimerAlarmRepeatingDriverAVR* timerAlarmRepeatingRef = nullptr;
10 
20  public:
21  TimerAlarmRepeatingDriverAVR() { timerAlarmRepeatingRef = this; }
22 
26  bool begin(repeating_timer_callback_t callback_f, uint32_t time,
27  TimeUnit unit = MS) override {
28  callback = callback_f;
29 
30  // we determine the time in microseconds
31  uint32_t timeUs = 0;
32  switch (unit) {
33  case MS:
34  timeUs = time * 1000;
35  break;
36  case US:
37  timeUs = time;
38  break;
39  case HZ:
40  // convert hz to time in us
41  timeUs = AudioTime::toTimeUs(time);
42  break;
43  }
44  // frequency = beats / second
45  setupTimer(1000000 / time);
46  return true;
47  }
48 
49  // ends the timer and if necessary the task
50  bool end() override {
51  TRACED();
52  noInterrupts();
53  // end timer callback
54  TCCR1B = 0;
55  interrupts(); // enable all interrupts
56  return true;
57  }
58 
59  static void tickerCallback() {
60  if (timerAlarmRepeatingRef != nullptr &&
61  timerAlarmRepeatingRef->callback != nullptr)
62  timerAlarmRepeatingRef->callback(timerAlarmRepeatingRef);
63  }
64 
65  protected:
66  repeating_timer_callback_t callback = nullptr;
67 
68  void setupTimer(uint64_t sample_rate) {
69  TRACED();
70  // CPU Frequency 16 MHz
71  // prescaler 1, 256 or 1024 => no prescaling
72  uint32_t steps = F_CPU / 8 / sample_rate; // e.g. (16000000/8/44100=>45)
73  if (steps > 65535) {
74  LOGE("requested sample rate not supported: %d - we use %d", sample_rate,
75  F_CPU / 65536);
76  steps = 65535;
77  } else {
78  LOGD("compare match register set to %d", steps);
79  }
80 
81  // setup timer intterupt
82  noInterrupts();
83  TCCR1B = 0;
84  // compare match register
85  OCR1A = steps;
86  TCCR1B |= (1 << WGM12); // CTC mode
87  // TCCR1B |= (1 << CS10); // prescaler 1
88  TCCR1B |= (1 << CS11); // prescaler 8
89  TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
90  interrupts(); // enable all interrupts
91  }
92 };
93 
95 
96 } // namespace audio_tools
97 
98 #endif
static uint32_t toTimeUs(uint32_t samplingRate, uint8_t limit=10)
converts sampling rate to delay in microseconds (μs)
Definition: AudioTypes.h:256
Repeating Timer functions for repeated execution: Plaease use the typedef TimerAlarmRepeating.
Definition: AudioTimerAVR.h:19
bool begin(repeating_timer_callback_t callback_f, uint32_t time, TimeUnit unit=MS) override
Definition: AudioTimerAVR.h:26
Definition: AudioTimerBase.h:22
TimeUnit
Time Units.
Definition: AudioTypes.h:45
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition: AudioConfig.h:868