]> git.donarmstrong.com Git - qmk_firmware.git/blob - quantum/audio/audio_pwm.c
[Keyboard] add geekboards 8key macro-pad tester (#5940)
[qmk_firmware.git] / quantum / audio / audio_pwm.c
1 /* Copyright 2016 Jack Humbert
2  *
3  * This program is free software: you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation, either version 2 of the License, or
6  * (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  */
16 #include <stdio.h>
17 #include <string.h>
18 //#include <math.h>
19 #include <avr/pgmspace.h>
20 #include <avr/interrupt.h>
21 #include <avr/io.h>
22 #include "print.h"
23 #include "audio.h"
24 #include "keymap.h"
25
26 #include "eeconfig.h"
27
28 #define PI 3.14159265
29
30 #define CPU_PRESCALER 8
31
32
33 // Timer Abstractions
34
35 // TIMSK3 - Timer/Counter #3 Interrupt Mask Register
36 // Turn on/off 3A interputs, stopping/enabling the ISR calls
37 #define ENABLE_AUDIO_COUNTER_3_ISR TIMSK3 |= _BV(OCIE3A)
38 #define DISABLE_AUDIO_COUNTER_3_ISR TIMSK3 &= ~_BV(OCIE3A)
39
40
41 // TCCR3A: Timer/Counter #3 Control Register
42 // Compare Output Mode (COM3An) = 0b00 = Normal port operation, OC3A disconnected from PC6
43 #define ENABLE_AUDIO_COUNTER_3_OUTPUT TCCR3A |= _BV(COM3A1);
44 #define DISABLE_AUDIO_COUNTER_3_OUTPUT TCCR3A &= ~(_BV(COM3A1) | _BV(COM3A0));
45
46
47 #define NOTE_PERIOD ICR3
48 #define NOTE_DUTY_CYCLE OCR3A
49
50
51 #ifdef PWM_AUDIO
52     #include "wave.h"
53     #define SAMPLE_DIVIDER 39
54     #define SAMPLE_RATE (2000000.0/SAMPLE_DIVIDER/2048)
55     // Resistor value of 1/ (2 * PI * 10nF * (2000000 hertz / SAMPLE_DIVIDER / 10)) for 10nF cap
56
57     float places[8] = {0, 0, 0, 0, 0, 0, 0, 0};
58     uint16_t place_int = 0;
59     bool repeat = true;
60 #endif
61
62 void delay_us(int count) {
63   while(count--) {
64     _delay_us(1);
65   }
66 }
67
68 int voices = 0;
69 int voice_place = 0;
70 float frequency = 0;
71 int volume = 0;
72 long position = 0;
73
74 float frequencies[8] = {0, 0, 0, 0, 0, 0, 0, 0};
75 int volumes[8] = {0, 0, 0, 0, 0, 0, 0, 0};
76 bool sliding = false;
77
78 float place = 0;
79
80 uint8_t * sample;
81 uint16_t sample_length = 0;
82 // float freq = 0;
83
84 bool     playing_notes = false;
85 bool     playing_note = false;
86 float    note_frequency = 0;
87 float    note_length = 0;
88 uint8_t  note_tempo = TEMPO_DEFAULT;
89 float    note_timbre = TIMBRE_DEFAULT;
90 uint16_t note_position = 0;
91 float (* notes_pointer)[][2];
92 uint16_t notes_count;
93 bool     notes_repeat;
94 float    notes_rest;
95 bool     note_resting = false;
96
97 uint16_t current_note = 0;
98 uint8_t rest_counter = 0;
99
100 #ifdef VIBRATO_ENABLE
101 float vibrato_counter = 0;
102 float vibrato_strength = .5;
103 float vibrato_rate = 0.125;
104 #endif
105
106 float polyphony_rate = 0;
107
108 static bool audio_initialized = false;
109
110 audio_config_t audio_config;
111
112 uint16_t envelope_index = 0;
113
114 void audio_init() {
115
116     // Check EEPROM
117     if (!eeconfig_is_enabled())
118     {
119         eeconfig_init();
120     }
121     audio_config.raw = eeconfig_read_audio();
122
123     #ifdef PWM_AUDIO
124
125         PLLFRQ = _BV(PDIV2);
126         PLLCSR = _BV(PLLE);
127         while(!(PLLCSR & _BV(PLOCK)));
128         PLLFRQ |= _BV(PLLTM0); /* PCK 48MHz */
129
130         /* Init a fast PWM on Timer4 */
131         TCCR4A = _BV(COM4A0) | _BV(PWM4A); /* Clear OC4A on Compare Match */
132         TCCR4B = _BV(CS40); /* No prescaling => f = PCK/256 = 187500Hz */
133         OCR4A = 0;
134
135         /* Enable the OC4A output */
136         DDRC |= _BV(PORTC6);
137
138         DISABLE_AUDIO_COUNTER_3_ISR; // Turn off 3A interputs
139
140         TCCR3A = 0x0; // Options not needed
141         TCCR3B = _BV(CS31) | _BV(CS30) | _BV(WGM32); // 64th prescaling and CTC
142         OCR3A = SAMPLE_DIVIDER - 1; // Correct count/compare, related to sample playback
143
144     #else
145
146         // Set port PC6 (OC3A and /OC4A) as output
147         DDRC |= _BV(PORTC6);
148
149         DISABLE_AUDIO_COUNTER_3_ISR;
150
151                 // TCCR3A / TCCR3B: Timer/Counter #3 Control Registers
152                 // Compare Output Mode (COM3An) = 0b00 = Normal port operation, OC3A disconnected from PC6
153                 // Waveform Generation Mode (WGM3n) = 0b1110 = Fast PWM Mode 14 (Period = ICR3, Duty Cycle = OCR3A)
154                 // Clock Select (CS3n) = 0b010 = Clock / 8
155         TCCR3A = (0 << COM3A1) | (0 << COM3A0) | (1 << WGM31) | (0 << WGM30);
156         TCCR3B = (1 << WGM33)  | (1 << WGM32)  | (0 << CS32)  | (1 << CS31) | (0 << CS30);
157
158     #endif
159
160     audio_initialized = true;
161 }
162
163 void stop_all_notes() {
164     if (!audio_initialized) {
165         audio_init();
166     }
167     voices = 0;
168     #ifdef PWM_AUDIO
169             DISABLE_AUDIO_COUNTER_3_ISR;
170     #else
171         DISABLE_AUDIO_COUNTER_3_ISR;
172         DISABLE_AUDIO_COUNTER_3_OUTPUT;
173     #endif
174
175     playing_notes = false;
176     playing_note = false;
177     frequency = 0;
178     volume = 0;
179
180     for (uint8_t i = 0; i < 8; i++)
181     {
182         frequencies[i] = 0;
183         volumes[i] = 0;
184     }
185 }
186
187 void stop_note(float freq)
188 {
189     if (playing_note) {
190         if (!audio_initialized) {
191             audio_init();
192         }
193         #ifdef PWM_AUDIO
194             freq = freq / SAMPLE_RATE;
195         #endif
196         for (int i = 7; i >= 0; i--) {
197             if (frequencies[i] == freq) {
198                 frequencies[i] = 0;
199                 volumes[i] = 0;
200                 for (int j = i; (j < 7); j++) {
201                     frequencies[j] = frequencies[j+1];
202                     frequencies[j+1] = 0;
203                     volumes[j] = volumes[j+1];
204                     volumes[j+1] = 0;
205                 }
206                 break;
207             }
208         }
209         voices--;
210         if (voices < 0)
211             voices = 0;
212         if (voice_place >= voices) {
213             voice_place = 0;
214         }
215         if (voices == 0) {
216             #ifdef PWM_AUDIO
217                 DISABLE_AUDIO_COUNTER_3_ISR;
218             #else
219                 DISABLE_AUDIO_COUNTER_3_ISR;
220                 DISABLE_AUDIO_COUNTER_3_OUTPUT;
221             #endif
222             frequency = 0;
223             volume = 0;
224             playing_note = false;
225         }
226     }
227 }
228
229 #ifdef VIBRATO_ENABLE
230
231 float mod(float a, int b)
232 {
233     float r = fmod(a, b);
234     return r < 0 ? r + b : r;
235 }
236
237 float vibrato(float average_freq) {
238     #ifdef VIBRATO_STRENGTH_ENABLE
239         float vibrated_freq = average_freq * pow(vibrato_lut[(int)vibrato_counter], vibrato_strength);
240     #else
241         float vibrated_freq = average_freq * vibrato_lut[(int)vibrato_counter];
242     #endif
243     vibrato_counter = mod((vibrato_counter + vibrato_rate * (1.0 + 440.0/average_freq)), VIBRATO_LUT_LENGTH);
244     return vibrated_freq;
245 }
246
247 #endif
248
249 ISR(TIMER3_COMPA_vect)
250 {
251     if (playing_note) {
252         #ifdef PWM_AUDIO
253             if (voices == 1) {
254                 // SINE
255                 OCR4A = pgm_read_byte(&sinewave[(uint16_t)place]) >> 2;
256
257                 // SQUARE
258                 // if (((int)place) >= 1024){
259                 //     OCR4A = 0xFF >> 2;
260                 // } else {
261                 //     OCR4A = 0x00;
262                 // }
263
264                 // SAWTOOTH
265                 // OCR4A = (int)place / 4;
266
267                 // TRIANGLE
268                 // if (((int)place) >= 1024) {
269                 //     OCR4A = (int)place / 2;
270                 // } else {
271                 //     OCR4A = 2048 - (int)place / 2;
272                 // }
273
274                 place += frequency;
275
276                 if (place >= SINE_LENGTH)
277                     place -= SINE_LENGTH;
278
279             } else {
280                 int sum = 0;
281                 for (int i = 0; i < voices; i++) {
282                     // SINE
283                     sum += pgm_read_byte(&sinewave[(uint16_t)places[i]]) >> 2;
284
285                     // SQUARE
286                     // if (((int)places[i]) >= 1024){
287                     //     sum += 0xFF >> 2;
288                     // } else {
289                     //     sum += 0x00;
290                     // }
291
292                     places[i] += frequencies[i];
293
294                     if (places[i] >= SINE_LENGTH)
295                         places[i] -= SINE_LENGTH;
296                 }
297                 OCR4A = sum;
298             }
299         #else
300             if (voices > 0) {
301                 float freq;
302                 if (polyphony_rate > 0) {
303                     if (voices > 1) {
304                         voice_place %= voices;
305                         if (place++ > (frequencies[voice_place] / polyphony_rate / CPU_PRESCALER)) {
306                             voice_place = (voice_place + 1) % voices;
307                             place = 0.0;
308                         }
309                     }
310                     #ifdef VIBRATO_ENABLE
311                     if (vibrato_strength > 0) {
312                         freq = vibrato(frequencies[voice_place]);
313                     } else {
314                     #else
315                     {
316                     #endif
317                         freq = frequencies[voice_place];
318                     }
319                 } else {
320                     if (frequency != 0 && frequency < frequencies[voices - 1] && frequency < frequencies[voices - 1] * pow(2, -440/frequencies[voices - 1]/12/2)) {
321                         frequency = frequency * pow(2, 440/frequency/12/2);
322                     } else if (frequency != 0 && frequency > frequencies[voices - 1] && frequency > frequencies[voices - 1] * pow(2, 440/frequencies[voices - 1]/12/2)) {
323                         frequency = frequency * pow(2, -440/frequency/12/2);
324                     } else {
325                         frequency = frequencies[voices - 1];
326                     }
327
328
329                     #ifdef VIBRATO_ENABLE
330                     if (vibrato_strength > 0) {
331                         freq = vibrato(frequency);
332                     } else {
333                     #else
334                     {
335                     #endif
336                         freq = frequency;
337                     }
338                 }
339
340                 if (envelope_index < 65535) {
341                     envelope_index++;
342                 }
343                 freq = voice_envelope(freq);
344
345                 if (freq < 30.517578125)
346                     freq = 30.52;
347                 NOTE_PERIOD = (int)(((double)F_CPU) / (freq * CPU_PRESCALER)); // Set max to the period
348                 NOTE_DUTY_CYCLE = (int)((((double)F_CPU) / (freq * CPU_PRESCALER)) * note_timbre); // Set compare to half the period
349             }
350         #endif
351     }
352
353     // SAMPLE
354     // OCR4A = pgm_read_byte(&sample[(uint16_t)place_int]);
355
356     // place_int++;
357
358     // if (place_int >= sample_length)
359     //     if (repeat)
360     //         place_int -= sample_length;
361     //     else
362     //         DISABLE_AUDIO_COUNTER_3_ISR;
363
364
365     if (playing_notes) {
366         #ifdef PWM_AUDIO
367             OCR4A = pgm_read_byte(&sinewave[(uint16_t)place]) >> 0;
368
369             place += note_frequency;
370             if (place >= SINE_LENGTH)
371                 place -= SINE_LENGTH;
372         #else
373             if (note_frequency > 0) {
374                 float freq;
375
376                 #ifdef VIBRATO_ENABLE
377                 if (vibrato_strength > 0) {
378                     freq = vibrato(note_frequency);
379                 } else {
380                 #else
381                 {
382                 #endif
383                     freq = note_frequency;
384                 }
385
386                 if (envelope_index < 65535) {
387                     envelope_index++;
388                 }
389                 freq = voice_envelope(freq);
390
391                 NOTE_PERIOD = (int)(((double)F_CPU) / (freq * CPU_PRESCALER)); // Set max to the period
392                 NOTE_DUTY_CYCLE = (int)((((double)F_CPU) / (freq * CPU_PRESCALER)) * note_timbre); // Set compare to half the period
393             } else {
394                 NOTE_PERIOD = 0;
395                 NOTE_DUTY_CYCLE = 0;
396             }
397         #endif
398
399
400         note_position++;
401         bool end_of_note = false;
402         if (NOTE_PERIOD > 0)
403             end_of_note = (note_position >= (note_length / NOTE_PERIOD * 0xFFFF));
404         else
405             end_of_note = (note_position >= (note_length * 0x7FF));
406         if (end_of_note) {
407             current_note++;
408             if (current_note >= notes_count) {
409                 if (notes_repeat) {
410                     current_note = 0;
411                 } else {
412                     #ifdef PWM_AUDIO
413                         DISABLE_AUDIO_COUNTER_3_ISR;
414                     #else
415                         DISABLE_AUDIO_COUNTER_3_ISR;
416                         DISABLE_AUDIO_COUNTER_3_OUTPUT;
417                     #endif
418                     playing_notes = false;
419                     return;
420                 }
421             }
422             if (!note_resting && (notes_rest > 0)) {
423                 note_resting = true;
424                 note_frequency = 0;
425                 note_length = notes_rest;
426                 current_note--;
427             } else {
428                 note_resting = false;
429                 #ifdef PWM_AUDIO
430                     note_frequency = (*notes_pointer)[current_note][0] / SAMPLE_RATE;
431                     note_length = (*notes_pointer)[current_note][1] * (((float)note_tempo) / 100);
432                 #else
433                     envelope_index = 0;
434                     note_frequency = (*notes_pointer)[current_note][0];
435                     note_length = ((*notes_pointer)[current_note][1] / 4) * (((float)note_tempo) / 100);
436                 #endif
437             }
438             note_position = 0;
439         }
440
441     }
442
443     if (!audio_config.enable) {
444         playing_notes = false;
445         playing_note = false;
446     }
447 }
448
449 void play_note(float freq, int vol) {
450
451     if (!audio_initialized) {
452         audio_init();
453     }
454
455         if (audio_config.enable && voices < 8) {
456             DISABLE_AUDIO_COUNTER_3_ISR;
457
458             // Cancel notes if notes are playing
459             if (playing_notes)
460                 stop_all_notes();
461
462             playing_note = true;
463
464             envelope_index = 0;
465
466             #ifdef PWM_AUDIO
467                 freq = freq / SAMPLE_RATE;
468             #endif
469             if (freq > 0) {
470                 frequencies[voices] = freq;
471                 volumes[voices] = vol;
472                 voices++;
473             }
474
475             #ifdef PWM_AUDIO
476                 ENABLE_AUDIO_COUNTER_3_ISR;
477             #else
478                 ENABLE_AUDIO_COUNTER_3_ISR;
479                 ENABLE_AUDIO_COUNTER_3_OUTPUT;
480             #endif
481         }
482
483 }
484
485 void play_notes(float (*np)[][2], uint16_t n_count, bool n_repeat, float n_rest)
486 {
487
488     if (!audio_initialized) {
489         audio_init();
490     }
491
492         if (audio_config.enable) {
493
494             DISABLE_AUDIO_COUNTER_3_ISR;
495
496                 // Cancel note if a note is playing
497             if (playing_note)
498                 stop_all_notes();
499
500             playing_notes = true;
501
502             notes_pointer = np;
503             notes_count = n_count;
504             notes_repeat = n_repeat;
505             notes_rest = n_rest;
506
507             place = 0;
508             current_note = 0;
509
510             #ifdef PWM_AUDIO
511                 note_frequency = (*notes_pointer)[current_note][0] / SAMPLE_RATE;
512                 note_length = (*notes_pointer)[current_note][1] * (((float)note_tempo) / 100);
513             #else
514                 note_frequency = (*notes_pointer)[current_note][0];
515                 note_length = ((*notes_pointer)[current_note][1] / 4) * (((float)note_tempo) / 100);
516             #endif
517             note_position = 0;
518
519
520             #ifdef PWM_AUDIO
521                 ENABLE_AUDIO_COUNTER_3_ISR;
522             #else
523                 ENABLE_AUDIO_COUNTER_3_ISR;
524                 ENABLE_AUDIO_COUNTER_3_OUTPUT;
525             #endif
526         }
527
528 }
529
530 #ifdef PWM_AUDIO
531 void play_sample(uint8_t * s, uint16_t l, bool r) {
532     if (!audio_initialized) {
533         audio_init();
534     }
535
536     if (audio_config.enable) {
537         DISABLE_AUDIO_COUNTER_3_ISR;
538         stop_all_notes();
539         place_int = 0;
540         sample = s;
541         sample_length = l;
542         repeat = r;
543
544         ENABLE_AUDIO_COUNTER_3_ISR;
545     }
546 }
547 #endif
548
549
550 void audio_toggle(void) {
551     audio_config.enable ^= 1;
552     eeconfig_update_audio(audio_config.raw);
553 }
554
555 void audio_on(void) {
556     audio_config.enable = 1;
557     eeconfig_update_audio(audio_config.raw);
558 }
559
560 void audio_off(void) {
561     audio_config.enable = 0;
562     eeconfig_update_audio(audio_config.raw);
563 }
564
565 #ifdef VIBRATO_ENABLE
566
567 // Vibrato rate functions
568
569 void set_vibrato_rate(float rate) {
570     vibrato_rate = rate;
571 }
572
573 void increase_vibrato_rate(float change) {
574     vibrato_rate *= change;
575 }
576
577 void decrease_vibrato_rate(float change) {
578     vibrato_rate /= change;
579 }
580
581 #ifdef VIBRATO_STRENGTH_ENABLE
582
583 void set_vibrato_strength(float strength) {
584     vibrato_strength = strength;
585 }
586
587 void increase_vibrato_strength(float change) {
588     vibrato_strength *= change;
589 }
590
591 void decrease_vibrato_strength(float change) {
592     vibrato_strength /= change;
593 }
594
595 #endif  /* VIBRATO_STRENGTH_ENABLE */
596
597 #endif /* VIBRATO_ENABLE */
598
599 // Polyphony functions
600
601 void set_polyphony_rate(float rate) {
602     polyphony_rate = rate;
603 }
604
605 void enable_polyphony() {
606     polyphony_rate = 5;
607 }
608
609 void disable_polyphony() {
610     polyphony_rate = 0;
611 }
612
613 void increase_polyphony_rate(float change) {
614     polyphony_rate *= change;
615 }
616
617 void decrease_polyphony_rate(float change) {
618     polyphony_rate /= change;
619 }
620
621 // Timbre function
622
623 void set_timbre(float timbre) {
624     note_timbre = timbre;
625 }
626
627 // Tempo functions
628
629 void set_tempo(uint8_t tempo) {
630     note_tempo = tempo;
631 }
632
633 void decrease_tempo(uint8_t tempo_change) {
634     note_tempo += tempo_change;
635 }
636
637 void increase_tempo(uint8_t tempo_change) {
638     if (note_tempo - tempo_change < 10) {
639         note_tempo = 10;
640     } else {
641         note_tempo -= tempo_change;
642     }
643 }
644
645
646 //------------------------------------------------------------------------------
647 // Override these functions in your keymap file to play different tunes on
648 // startup and bootloader jump
649 __attribute__ ((weak))
650 void play_startup_tone()
651 {
652 }
653
654 __attribute__ ((weak))
655 void play_goodbye_tone()
656 {
657 }
658 //------------------------------------------------------------------------------