Mozzi  version v1.1.0
sound synthesis library for Arduino
MozziGuts.h
1 /*
2  * MozziGuts.h
3  *
4  * Copyright 2012 Tim Barrass.
5  *
6  * This file is part of Mozzi.
7  *
8  * Mozzi by Tim Barrass is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
9  *
10  */
11 
12 #ifndef MOZZIGUTS_H_
13 #define MOZZIGUTS_H_
14 
15 //#define F_CPU 8000000 // testing
16 
17 #if ARDUINO >= 100
18  #include "Arduino.h"
19 #else
20  #include "WProgram.h"
21 #endif
22 
23 #include "hardware_defines.h"
24 
25 #if IS_TEENSY3()
26 // required from http://github.com/pedvide/ADC for Teensy 3.*
27 #include <ADC.h>
28 #endif
29 
30 #include "mozzi_analog.h"
31 
32 #if not defined (CONTROL_RATE)
33 /** @ingroup core
34 Control rate setting.
35 Mozzi's CONTROL_RATE sets how many times per second updateControl() is called.
36 CONTROL_RATE has a default of 64 Hz, but it can be changed at the top of your sketch,
37 (before the \#includes), for example: \#define CONTROL_RATE 256.
38 It is useful to have CONTROL_RATE set at a power of 2 (such as 64,128,256 etc),
39 to have exact timing of audio and control operations.
40 Non-power-of-2 CONTROL_RATE can cause glitches due to audio and control
41 events not lining up precisely. If this happens a power of two CONTROL_RATE might solve it.
42 Try to keep CONTROL_RATE low, for efficiency, though higher rates up to about 1000
43 can sometimes give smoother results, avoiding the need to interpolate
44 sensitive variables at audio rate in updateAudio().
45 */
46 #define CONTROL_RATE 64
47 #endif
48 
49 
50 
51 /** @ingroup core
52 Used to set AUDIO_MODE to STANDARD, STANDARD_PLUS, or HIFI.
53 
54 STANDARD / STANDARD_PLUS
55 ---------------
56 Use \#define AUDIO_MODE STANDARD_PLUS in Mozzi/config.h to select this
57 output configuration, which is nearly 9 bit sound (-244 to 243) at 16384 Hz sample rate (AUDIO_RATE) and
58 32768 Hz PWM rate. It uses Timer 1 for PWM and the sample updating routine (as an interrupt).
59 
60 STANDARD is obsolete now, replaced by STANDARD_PLUS which is the default audio mode.
61 STANDARD mode uses 16384 Hz PWM rate with an output interrupt at the same frequency.
62 Some people can hear the PWM carrier frequency as an annoying whine.
63 
64 STANDARD_PLUS mode uses 32768 Hz PWM rate, so the PWM carrier is out of hearing range.
65 In this mode every alternate interrupt is used for the sample update (unless you /#define AUDIO_RATE 32768 in mozzi_config.h),
66 which makes it slightly less efficient than STANDARD, but almost always better.
67 
68 Advantages: Only uses one timer for audio, and one output pin.
69 Disadvantages: low dynamic range.
70 
71 Below is a list of the Digital Pins used by Mozzi for STANDARD and STANDARD_PLUS audio out on different boards.
72 Those which have been tested and reported to work have an x.
73 Feedback about others is welcome.
74 
75 x....9........Arduino Uno \n
76 x....9........Arduino Duemilanove \n
77 x....9........Arduino Nano \n
78 x....9........Arduino Leonardo \n
79 x....9........Ardweeny \n
80 x....9........Boarduino \n
81 x...11.......Freetronics EtherMega *broken since Jan 2015 \n
82 x...11.......Arduino Mega *broken since Jan 2015 \n
83 ....14........Teensy \n
84 x..B5........Teensy2 \n
85 x..B5(25)..Teensy2++ \n
86 x..A14.....Teensy 3.0, 3.1 and 3.2 \n
87 ....13 .......Sanguino \n
88 
89 On Teensy 3.* STANDARD and STANDARD_PLUS are the same, providing 16384Hz sample rate and 12 bit resolution on pin A14/ADC.
90 The Teensy 3.* DAC output does not rely on PWM.
91 
92 
93 @ingroup core
94 
95 Used to set AUDIO_MODE to HIFI.
96 
97 HIFI for AVR and STM32 (not for Teensy 3.*)
98 ----
99 Use \#define AUDIO_MODE HIFI in Mozzi/config.h to set the audio mode to HIFI for output 14 bit sound at 16384 Hz sample rate and 125kHz PWM rate.
100 The high PWM rate of HIFI mode places the carrier frequency beyond audible range.
101 
102 Also, 14 bits of dynamic range in HIFI mode provides more definition than the nearly 9 bits in STANDARD_PLUS mode.
103 HIFI mode takes about the same amount of processing time as STANDARD_PLUS mode, and should sound clearer and brighter.
104 However, it requires an extra timer to be used on the Arduino, which could increase the chances of
105 conflicts with other libraries or processes if they rely on Timer 2.
106 
107 Timer 1 is used to provide the PWM output at 125kHz.
108 Timer 2 generates an interrupt at AUDIO_RATE 16384 Hz, which sets the Timer1 PWM levels.
109 HIFI mode uses 2 output pins, and sums their outputs with resistors, so is slightly less convenient for
110 rapid prototyping where you could listen to STANDARD_PLUS mode by connecting the single output pin
111 directly to a speaker or audio input (though a resistor of about 100 ohms is recommended).
112 
113 The resistors needed for HIFI output are 3.9k and 499k, with 0.5% or better tolerance.
114 If you can only get 1% resistors, use a multimeter to find the most accurate.
115 Use two 1M resistors in parallel if you can't find 499k.
116 
117 On 328 based Arduino boards, output is on Timer1, with the high byte on Pin 9 and low byte on Pin 10.
118 Add the signals through a 3.9k resistor on high byte pin (9) and 499k resistor on low byte pin (10).
119 Also, a 4.7nF capacitor is recommended between the summing junction of the resistors and ground.
120 
121 This dual PWM technique is discussed on http://www.openmusiclabs.com/learning/digital/pwm-dac/dual-pwm-circuits/
122 Also, there are higher quality output circuits are on the site.
123 
124 Advantages: should be higher quality sound than STANDARD_PLUS mode. Doesn't need a notch filter on
125 the audio signal (like STANDARD which is now obsolete) because the carrier frequency is out of hearing range.
126 
127 Disadvantages: requires 2 pins, 2 resistors and a capacitor, so it's not so quick to set up compared
128 to a rough, direct single-pin output in STANDARD_PLUS mode.
129 
130 Pins and where to put the resistors on various boards for HIFI mode.
131 Boards tested in HIFI mode have an x, though most of these have been tested in STANDARD_PLUS mode
132 and there's no reason for them not to work in HIFI (unless the pin number is wrong or something).
133 Any reports are welcome. \n
134 
135 resistor.....3.9k......499k \n
136 x................9..........10...............Arduino Uno \n
137 x................9..........10...............Arduino Duemilanove \n
138 x................9..........10...............Arduino Nano \n
139 x................9..........10...............Arduino Leonardo \n
140 x................9..........10...............Ardweeny \n
141 x................9..........10...............Boarduino \n
142 x...............11.........12...............Freetronics EtherMega \n
143 .................11.........12...............Arduino Mega \n
144 .................14.........15...............Teensy \n
145 .............B5(14)...B6(15)...........Teensy2 \n
146 x...........B5(25)...B6(26)...........Teensy2++ \n
147 .................13.........12...............Sanguino \n
148 
149 HIFI is not available/not required on Teensy 3.* or ARM.
150 */
151 
152 //enum audio_modes {STANDARD,STANDARD_PLUS,HIFI};
153 #define STANDARD 0
154 #define STANDARD_PLUS 1
155 #define HIFI 2
156 
157 #include "mozzi_config.h" // User can change the config file to set audio mode
158 
159 #if (AUDIO_MODE == STANDARD) && (AUDIO_RATE == 32768)
160 #error AUDIO_RATE 32768 does not work when AUDIO_MODE is STANDARD, try setting the AUDIO_MODE to STANDARD_PLUS in Mozzi/mozzi_config.h
161 #endif
162 
163 
164 #define CLOCK_TICKS_PER_AUDIO_TICK (F_CPU / AUDIO_RATE)
165 
166 
167 #if AUDIO_RATE == 16384
168 #define AUDIO_RATE_AS_LSHIFT 14
169 #define MICROS_PER_AUDIO_TICK 61 // 1000000 / 16384 = 61.035, ...* 256 = 15625
170 #elif AUDIO_RATE == 32768
171 #define AUDIO_RATE_AS_LSHIFT 15
172 #define MICROS_PER_AUDIO_TICK 31 // = 1000000 / 32768 = 30.518, ...* 256 = 7812.6
173 #endif
174 
175 // for compatibility with old (local) versions of mozzi_config.h
176 #if !defined(EXTERNAL_AUDIO_OUTPUT)
177 #define EXTERNAL_AUDIO_OUTPUT false
178 #endif
179 
180 #if (EXTERNAL_AUDIO_OUTPUT != true)
181 #if IS_TEENSY3()
182 #include "AudioConfigTeensy3_12bit.h"
183 #elif IS_STM32()
184 #include "AudioConfigSTM32.h"
185 #elif IS_ESP8266()
186 #include "AudioConfigESP.h"
187 #elif IS_ESP32()
188 #include "AudioConfigESP32.h"
189 #elif IS_SAMD21()
190 #include "AudioConfigSAMD21.h"
191 #elif IS_AVR() && (AUDIO_MODE == STANDARD)
192 #include "AudioConfigStandard9bitPwm.h"
193 #elif IS_AVR() && (AUDIO_MODE == STANDARD_PLUS)
194 #include "AudioConfigStandardPlus.h"
195 #elif IS_AVR() && (AUDIO_MODE == HIFI)
196 #include "AudioConfigHiSpeed14bitPwm.h"
197 #endif
198 #else // EXTERNAL_AUDIO_OUTPUT==true
199 #if !defined(EXTERNAL_AUDIO_BITS)
200 #define EXTERNAL_AUDIO_BITS 16
201 #endif
202 #define AUDIO_BITS EXTERNAL_AUDIO_BITS
203 #define AUDIO_BIAS (1 << (AUDIO_BITS - 1))
204 #endif
205 
206 #if (STEREO_HACK == true)
207 extern int audio_out_1, audio_out_2;
208 #endif
209 
210 #include "AudioOutput.h"
211 
212 // common numeric types
213 typedef unsigned char uchar;
214 typedef unsigned int uint;
215 typedef unsigned long ulong;
216 
217 #if defined(__AVR__)
218 typedef unsigned char byte; // for arduino ide
219 typedef unsigned char uint8_t;
220 typedef signed char int8_t;
221 typedef unsigned int uint16_t;
222 typedef signed int int16_t;
223 typedef unsigned long uint32_t;
224 typedef signed long int32_t;
225 #else
226 // Other supported arches add typedefs, here, unless already defined for that platform needed
227 #endif
228 
229 
230 /** @ingroup core
231 Sets up the timers for audio and control rate processes, storing the timer
232 registers so they can be restored when Mozzi stops. startMozzi() goes in your sketch's
233 setup() routine.
234 
235 Contrary to earlier versions of Mozzi, this version does not take over Timer 0, and thus Arduino
236 functions delay(), millis(), micros() and delayMicroseconds() remain usable in theory. That said,
237 you should avoid these functions, as they are slow (or even blocking). For measuring time, refer
238 to mozziMircos(). For delaying events, you can use Mozzi's EventDelay() unit instead
239 (not to be confused with AudioDelay()).
240 
241 In STANDARD mode, startMozzi() starts Timer 1 for PWM output and audio output interrupts,
242 and in STANDARD_PLUS and HIFI modes, Mozzi uses Timer 1 for PWM and Timer2 for audio interrupts.
243 
244 The audio rate defaults to 16384 Hz, but you can experiment with 32768 Hz by changing AUDIO_RATE in mozzi_config.h.
245 
246 @param control_rate_hz Sets how often updateControl() is called. It must be a power of 2.
247 If no parameter is provided, control_rate_hz is set to CONTROL_RATE,
248 which has a default value of 64 (you can re-\#define it in your sketch).
249 The practical upper limit for control rate depends on how busy the processor is,
250 and you might need to do some tests to find the best setting.
251 
252 @note startMozzi calls setupMozziADC(), which calls setupFastAnalogRead() and adcDisconnectAllDigitalIns(),
253 which disables digital inputs on all analog input pins. All in mozzi_analog.h and easy to change if you need to (hack).
254 They are all called automatically and hidden away because it keeps things simple for a STANDARD_PLUS set up,
255 but if it turns out to be confusing, they might need to become visible again.
256 */
257 void startMozzi(int control_rate_hz = CONTROL_RATE);
258 
259 
260 
261 /** @ingroup core
262 Stops audio and control interrupts and restores the timers to the values they
263 had before Mozzi was started. This could be useful when using sensor libraries
264 which depend on the same timers as Mozzi.
265 
266 A potentially better option for resolving timer conflicts involves using
267 non-blocking methods, such as demonstrated by the twowire_nonblock code in the
268 forked version of Mozzi on github, so sound production can continue while
269 reading sensors.
270 
271 As it is, stopMozzi restores all the Timers used by Mozzi to their previous
272 settings. Another scenario which could be easily hacked in MozziGuts.cpp could
273 involve individually saving and restoring particular Timer registers depending
274 on which one(s) are required for other tasks. */
275 void stopMozzi();
276 
277 
278 /** @ingroup core
279 Obsolete function, use stopMozzi() instead.
280 */
281 void pauseMozzi();
282 
283 //TB2017-19
284 /** @ingroup core
285 Obsolete function, use startMozzi() instead.
286 Restores Mozzi audio and control interrupts, if they have been temporarily
287 disabled with pauseMozzi().
288 */
289 void unPauseMozzi();
290 
291 
292 /** @ingroup core
293 This is where you put your audio code. updateAudio() has to keep up with the
294 AUDIO_RATE of 16384 Hz, so to keep things running smoothly, avoid doing any
295 calculations here which could be done in setup() or updateControl().
296 @return an audio sample. In STANDARD modes this is between -244 and 243 inclusive.
297 In HIFI mode, it's a 14 bit number between -16384 and 16383 inclusive.
298 */
300 
301 /** @ingroup core
302 This is where you put your control code. You need updateControl() somewhere in
303 your sketch, even if it's empty. updateControl() is called at the control rate
304 you set in startMozzi(). To save processor load, avoid any calculations here
305 which could be done in setup().
306 */
307 void updateControl();
308 
309 
310 /** @ingroup core
311 This is required in Arduino's loop(). If there is room in Mozzi's output buffer,
312 audioHook() calls updateAudio() once and puts the result into the output
313 buffer. Also, if \#define USE_AUDIO_INPUT true is in Mozzi/mozzi_config.h,
314 audioHook() takes care of moving audio input from the input buffer so it can be
315 accessed with getAudioInput() in your updateAudio() routine.
316 If other functions are called in loop() along with audioHook(), see if
317 they can be called less often by moving them into updateControl(),
318 to save processing power. Otherwise it may be most efficient to
319 calculate a block of samples at a time by putting audioHook() in a loop of its
320 own, rather than calculating only 1 sample for each time your other functions
321 are called.
322 */
323 void audioHook();
324 
325 
326 
327 /** @ingroup analog
328 This returns audio input from the input buffer, if
329 \#define USE_AUDIO_INPUT true is in the Mozzi/mozzi_config.h file.
330 The pin used for audio input is set in Mozzi/mozzi_config.h with
331 \#define AUDIO_INPUT_PIN 0 (or other analog input pin).
332 The audio signal needs to be in the range 0 to 5 volts.
333 Circuits and discussions about biasing a signal
334 in the middle of this range can be found at
335 http://electronics.stackexchange.com/questions/14404/dc-biasing-audio-signal
336 and
337 http://interface.khm.de/index.php/lab/experiments/arduino-realtime-audio-processing/ .
338 A circuit and instructions for amplifying and biasing a microphone signal can be found at
339 http://www.instructables.com/id/Arduino-Audio-Input/?ALLSTEPS
340 @return audio data from the input buffer
341 */
342 #if (USE_AUDIO_INPUT == true)
343 int getAudioInput();
344 #endif
345 
346 
347 /** @ingroup core
348 An alternative for Arduino time functions like micros() and millis(). This is slightly faster than micros(),
349 and also it is synchronized with the currently processed audio sample (which, due to the audio
350 output buffer, could diverge up to 256/AUDIO_RATE seconds from the current time).
351 audioTicks() is updated each time an audio sample
352 is output, so the resolution is 1/AUDIO_RATE microseconds (61 microseconds when AUDIO_RATE is
353 16384 Hz).
354 @return the number of audio ticks since the program began.
355 */
356 unsigned long audioTicks();
357 
358 
359 
360 /** @ingroup core
361 An alternative for Arduino time functions like micros() and millis(). This is slightly faster than micros(),
362 and also it is synchronized with the currently processed audio sample (which, due to the audio
363 output buffer, could diverge up to 256/AUDIO_RATE seconds from the current time).
364 audioTicks() is updated each time an audio sample
365 is output, so the resolution is 1/AUDIO_RATE microseconds (61 microseconds when AUDIO_RATE is
366 16384 Hz).
367 @return the approximate number of microseconds since the program began.
368 @todo incorporate mozziMicros() in a more accurate EventDelay()?
369 */
370 unsigned long mozziMicros();
371 
372 
373 
374 
375 // internal use
376 #if (AUDIO_MODE == HIFI)
377 static void setupTimer2();
378 #endif
379 
380 #endif /* MOZZIGUTS_H_ */
unsigned long mozziMicros()
An alternative for Arduino time functions like micros() and millis().
Definition: MozziGuts.cpp:768
void stopMozzi()
Stops audio and control interrupts and restores the timers to the values they had before Mozzi was st...
Definition: MozziGuts.cpp:704
#define AUDIO_MODE
AUDIO_MODE holds the audio mode setting.
Definition: mozzi_config.h:28
#define HIFI
Definition: MozziGuts.h:155
#define STEREO_HACK
This sets an option for stereo output, a hack which requires variables audio_signal_1 and audio_signa...
Definition: mozzi_config.h:92
#define IS_SAMD21()
AudioOutput_t updateAudio()
This is where you put your audio code.
void updateControl()
This is where you put your control code.
#define AUDIO_RATE
Holds the audio rate setting.
Definition: mozzi_config.h:62
#define IS_STM32()
#define STANDARD_PLUS
Definition: MozziGuts.h:154
void audioHook()
This is required in Arduino&#39;s loop().
Definition: MozziGuts.cpp:325
#define IS_AVR()
#define IS_TEENSY3()
void unPauseMozzi()
Obsolete function, use startMozzi() instead.
unsigned long audioTicks()
An alternative for Arduino time functions like micros() and millis().
Definition: MozziGuts.cpp:752
#define AudioOutput_t
Definition: AudioOutput.h:59
void pauseMozzi()
Obsolete function, use stopMozzi() instead.
void startMozzi(int control_rate_hz=CONTROL_RATE)
Sets up the timers for audio and control rate processes, storing the timer registers so they can be r...
Definition: MozziGuts.cpp:689
#define STANDARD
Used to set AUDIO_MODE to STANDARD, STANDARD_PLUS, or HIFI.
Definition: MozziGuts.h:153
#define EXTERNAL_AUDIO_OUTPUT
Defining this option as true in mozzi_config.h allows to completely customize the audio output...
Definition: mozzi_config.h:99
#define IS_ESP8266()
#define IS_ESP32()