_wait.h 3.2 KB

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