Pico-Arduino
PicoTone.h
1 #pragma once
2 
3 #include "PicoTimer.h"
4 #include "Map.h"
5 
6 // forward declaratioins
7 extern int64_t stop_tone_callback(alarm_id_t id, void *user_data);
8 
9 
15 class PicoTone {
16  public:
17  PicoTone(){
18  }
19 
20  ~PicoTone(){
21  noTone();
22  }
23 
24  static bool generate_sound_callback(repeating_timer_t *rt){
25  PicoTone *pt = (PicoTone*)rt->user_data;
26  pt->state = !pt->state; // toggle state
27  digitalWrite(pt->pin, pt->state);
28  return true;
29  }
30 
31  void tone(uint8_t pinNumber, unsigned int frequency) {
32  pin = pinNumber;
33  int delay = 1000 / frequency / 2;
34  alarm.start(generate_sound_callback, delay, MS, this);
35  }
36 
37  void noTone() {
38  alarm.stop();
39  }
40 
41  bool operator==(const PicoTone& other){
42  return other.pin == this->pin;
43  }
44 
45  bool operator!=(const PicoTone& other){
46  return other.pin != this->pin;
47  }
48 
49  int pin;
50  bool state;
51 
52  protected:
53  TimerAlarmRepeating alarm;
54 };
55 
56 
62  public:
63  static int64_t stop_tone_callback(alarm_id_t id, void *user_data){
64  // ugliy hack: we receive the pin number in user_data (not a pointer!)
65  PicoTone* ptr = (PicoTone*) user_data;
66  noTone(ptr->pin);
67  return 0;
68  }
69 
70  // static interface which supports multipe pins concurrently
71  static void tone(uint8_t pinNumber, unsigned int frequency, int duration) {
72  PicoTone ptone = pinMap().get(pinNumber);
73  if (ptone==empyTone()){
74  // add entry
75  pinMap().put(pinNumber, ptone);
76  }
77  ptone.tone(pinNumber, frequency);
78  add_alarm_in_ms(duration, stop_tone_callback, &ptone , false);
79  }
80 
81  // static interface which supports multipe pins
82  static void noTone(uint8_t pinNumber) {
83  // find the actual PicoTone with the pin number
84  PicoTone ptone = pinMap().get(pinNumber);
85  if (ptone!=empyTone()){
86  ptone.noTone();
87  }
88  }
89 
90  static const PicoTone empyTone() {
91  static const PicoTone EMPTY_TONE;
92  return EMPTY_TONE;
93  }
94 
95  // for static interface
96  static Map<int, PicoTone> pinMap(){
97  static Map<int, PicoTone> ArduinoPicoTonePinMap(empyTone());
98  return ArduinoPicoTonePinMap;
99  }
100 
101 
102 };
103 
104 
ArduinoPicoTone provides static methods for PicoTone.
Definition: PicoTone.h:61
A simple key value map collection.
Definition: Map.h:12
We use the TimerAlarmRepeating to generate tones.
Definition: PicoTone.h:15
Repeating Timer functions for simple scheduling of repeated execution.
Definition: PicoTimer.h:54