fauxclicky.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. Copyright 2017 Priyadi Iman Nurcahyo
  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. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <avr/interrupt.h>
  15. #include <avr/io.h>
  16. #include <timer.h>
  17. #include <fauxclicky.h>
  18. #include <stdbool.h>
  19. #include <musical_notes.h>
  20. __attribute__ ((weak))
  21. float fauxclicky_pressed_note[2] = MUSICAL_NOTE(_F3, 2);
  22. __attribute__ ((weak))
  23. float fauxclicky_released_note[2] = MUSICAL_NOTE(_A3, 2);
  24. __attribute__ ((weak))
  25. float fauxclicky_beep_note[2] = MUSICAL_NOTE(_C3, 2);
  26. bool fauxclicky_enabled = true;
  27. uint16_t note_start = 0;
  28. bool note_playing = false;
  29. uint16_t note_period = 0;
  30. void fauxclicky_init()
  31. {
  32. // Set port PC6 (OC3A and /OC4A) as output
  33. DDRC |= _BV(PORTC6);
  34. // TCCR3A / TCCR3B: Timer/Counter #3 Control Registers
  35. TCCR3A = (0 << COM3A1) | (0 << COM3A0) | (1 << WGM31) | (0 << WGM30);
  36. TCCR3B = (1 << WGM33) | (1 << WGM32) | (0 << CS32) | (1 << CS31) | (0 << CS30);
  37. }
  38. void fauxclicky_stop()
  39. {
  40. FAUXCLICKY_DISABLE_OUTPUT;
  41. note_playing = false;
  42. }
  43. void fauxclicky_play(float note[2]) {
  44. if (!fauxclicky_enabled) return;
  45. if (note_playing) fauxclicky_stop();
  46. FAUXCLICKY_TIMER_PERIOD = (uint16_t)(((float)F_CPU) / (note[0] * FAUXCLICKY_CPU_PRESCALER));
  47. FAUXCLICKY_DUTY_CYCLE = (uint16_t)((((float)F_CPU) / (note[0] * FAUXCLICKY_CPU_PRESCALER)) / 2);
  48. note_playing = true;
  49. note_period = (note[1] / 16) * (60 / (float)FAUXCLICKY_TEMPO) * 100; // check this
  50. note_start = timer_read();
  51. FAUXCLICKY_ENABLE_OUTPUT;
  52. }
  53. void fauxclicky_check() {
  54. if (!note_playing) return;
  55. if (timer_elapsed(note_start) > note_period) {
  56. fauxclicky_stop();
  57. }
  58. }