Mozzi  version v2.0
sound synthesis library for Arduino
Metronome.h
1 /*
2  * Metronome.h
3  *
4  * This file is part of Mozzi.
5  *
6  * Copyright 2012-2024 Tim Barrass and the Mozzi Team
7  *
8  * Mozzi is licensed under the GNU Lesser General Public Licence (LGPL) Version 2.1 or later.
9  *
10  */
11 
12 
13 #ifndef METRO_H_
14 #define METRO_H_
15 
16 #include "EventDelay.h"
17 
18 /** A metronome class which is like an EventDelay which retriggers itself when the delay time is up, to produce a repeating beat.
19 Metronome can be set() to a number of milliseconds, then after calling start(), ready() will return true when the time is up.
20 Alternatively, start(milliseconds) will call set() and start() together.
21 This is called Metronome to avoid conflict with the Arduino Metro library.
22 */
23 class Metronome: public EventDelay
24 {
25 
26 public:
27 
28  /** Constructor.
29  Declare a Metronome object.
30  @param delay_milliseconds how long between each occasion when ready() returns true.
31  */
32  Metronome(unsigned int delay_milliseconds = 0): EventDelay(delay_milliseconds), stopped(false) {
33  }
34 
35 
36  /** Start the metronome.
37  @todo have a parameter to set whether it's single or repeating, so start doesn't have to be called for repeats.
38  Pro: simpler user programming. Con: would require an if..then every time ready() is called.
39  */
40  inline
41  void start()
42  {
43  deadline=audioTicks()+ticks;
44  stopped = false;
45  }
46 
47 
48  /** Set the time between beats and start the metronome.
49  @param delay_milliseconds delay time in milliseconds.
50  */
51  inline
52  void start(unsigned int delay_milliseconds)
53  {
54  set(delay_milliseconds);
55  start();
56  }
57 
58 
59 
60  /** Set the beats per minute.
61  @param bpm beats per minute
62  */
63  inline
64  void setBPM(float bpm)
65  {
66  set((unsigned int) (60000.f/bpm));
67  }
68 
69 
70 
71 
72  /** Call this in updateControl() or updateAudio() to check if it is time for a beat.
73  @return true if the time for one is up.
74  */
75  inline
76  bool ready()
77  {
78  unsigned long now = audioTicks();
79  if ((now<deadline) || stopped) return false;
80 
81  deadline=now-(now-deadline)+ticks; // subtract overrun so the timing doesn't slip
82  return true;
83  }
84 
85 
86  inline
87  void stop(){
88  stopped = true;
89  }
90 
91 private:
92  bool stopped;
93 };
94 
95 
96 
97 
98 /**
99 @example 02.Control/Metronome_SampleHuffman/Metronome_SampleHuffman.ino
100 This example shows how to use the Metronome class.
101 */
102 
103 #endif /* METRO_H_ */