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