arduino-audio-tools
AudioTimerRP2040.h
1 #pragma once
2 
3 #if defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
4 #include <time.h>
5 
6 #include <functional>
7 
8 #include "AudioTools/CoreAudio/AudioTimer/AudioTimerBase.h"
9 #include "hardware/timer.h"
10 #include "pico/time.h"
11 
12 namespace audio_tools {
13 
14 typedef void (*my_repeating_timer_callback_t)(void *obj);
15 
24 class TimerAlarmRepeatingDriverRP2040 : public TimerAlarmRepeatingDriverBase {
25  public:
26  TimerAlarmRepeatingDriverRP2040() {
27  alarm_pool_init_default();
28  ap = alarm_pool_get_default();
29  }
30 
34  bool begin(const my_repeating_timer_callback_t callback_f, uint32_t time,
35  TimeUnit unit = MS) override {
36  bool result = false;
37  LOGI("timer time: %u %s", (unsigned int)time, toString(unit));
38  this->instanceCallback = callback_f;
39 
40  // we determine the time in microseconds
41  switch (unit) {
42  case MS:
43  result = alarm_pool_add_repeating_timer_ms(ap, time, &staticCallback,
44  this, &timer);
45  break;
46  case US:
47  result = alarm_pool_add_repeating_timer_us(ap, time, &staticCallback,
48  this, &timer);
49  break;
50  case HZ:
51  // convert hz to time in us
52  uint64_t time_us = AudioTime::toTimeUs(time);
53  result = alarm_pool_add_repeating_timer_us(ap, time_us, &staticCallback,
54  this, &timer);
55  break;
56  }
57 
58  return result;
59  }
60 
61  inline static bool staticCallback(repeating_timer *ptr) {
62  TimerAlarmRepeatingDriverRP2040 *self =
63  (TimerAlarmRepeatingDriverRP2040 *)ptr->user_data;
64  self->instanceCallback(self->object);
65  return true;
66  }
67 
68  // ends the timer and if necessary the task
69  bool end() { return cancel_repeating_timer(&timer); }
70 
71  protected:
72  alarm_pool_t *ap = nullptr;
73  repeating_timer_t timer;
74  my_repeating_timer_callback_t instanceCallback = nullptr;
75 };
76 
78 using TimerAlarmRepeatingDriver = TimerAlarmRepeatingDriverRP2040;
79 
80 } // namespace audio_tools
81 
82 #endif
static uint32_t toTimeUs(uint32_t samplingRate, uint8_t limit=10)
converts sampling rate to delay in microseconds (μs)
Definition: AudioTypes.h:256
TimeUnit
Time Units.
Definition: AudioTypes.h:45
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition: AudioConfig.h:872
TimerAlarmRepeatingDriverAVR TimerAlarmRepeatingDriver
use TimerAlarmRepeating!
Definition: AudioTimerAVR.h:94