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