_wait.h 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* Copyright 2021 QMK
  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 3 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. #pragma once
  17. #include <util/delay.h>
  18. // http://ww1.microchip.com/downloads/en/devicedoc/atmel-0856-avr-instruction-set-manual.pdf
  19. // page 22: Table 4-2. Arithmetic and Logic Instructions
  20. /*
  21. for (uint16_t i = times; i > 0; i--) {
  22. __builtin_avr_delay_cycles(1);
  23. }
  24. .L3: sbiw r24,0 // loop step 1
  25. brne .L4 // loop step 2
  26. ret
  27. .L4: nop // __builtin_avr_delay_cycles(1);
  28. sbiw r24,1 // loop step 3
  29. rjmp .L3 // loop step 4
  30. */
  31. #define AVR_sbiw_clocks 2
  32. #define AVR_rjmp_clocks 2
  33. #define AVR_brne_clocks 2
  34. #define AVR_WAIT_LOOP_OVERHEAD (AVR_sbiw_clocks + AVR_brne_clocks + AVR_sbiw_clocks + AVR_rjmp_clocks)
  35. #define wait_ms(ms) \
  36. do { \
  37. if (__builtin_constant_p(ms)) { \
  38. _delay_ms(ms); \
  39. } else { \
  40. for (uint16_t i = ms; i > 0; i--) { \
  41. _delay_ms(1); \
  42. } \
  43. } \
  44. } while (0)
  45. #define wait_us(us) \
  46. do { \
  47. if (__builtin_constant_p(us)) { \
  48. _delay_us(us); \
  49. } else { \
  50. for (uint16_t i = us; i > 0; i--) { \
  51. __builtin_avr_delay_cycles((F_CPU / 1000000) - AVR_WAIT_LOOP_OVERHEAD); \
  52. } \
  53. } \
  54. } while (0)
  55. #define wait_cpuclock(n) __builtin_avr_delay_cycles(n)
  56. #define CPU_CLOCK F_CPU
  57. /* The AVR series GPIOs have a one clock read delay for changes in the digital input signal.
  58. * But here's more margin to make it two clocks. */
  59. #ifndef GPIO_INPUT_PIN_DELAY
  60. # define GPIO_INPUT_PIN_DELAY 2
  61. #endif
  62. #define waitInputPinDelay() wait_cpuclock(GPIO_INPUT_PIN_DELAY)