1 | // pulseIn.c |
2 | // Reads pulse width on input GPIO pin |
3 | // Copyright (c) Joshua 'joshuas3' Stockin 2019 |
4 |
|
5 | #include "driver/gpio.h" |
6 |
|
7 | #define WAIT_FOR_PIN_STATE(state) \ |
8 | while (gpio_get_level(pin) != (state)) { \ |
9 | if (xthal_get_ccount() - func_start > 5000000) return 0; \ |
10 | } |
11 |
|
12 | unsigned int pulseIn(unsigned char pin, unsigned char state) { |
13 | const unsigned int func_start = xthal_get_ccount(); |
14 | WAIT_FOR_PIN_STATE(!state); |
15 | WAIT_FOR_PIN_STATE(state); // wait until pin reaches state |
16 | const unsigned int pulse_start = xthal_get_ccount(); |
17 | WAIT_FOR_PIN_STATE(!state); // pin leaves state, record clock time elapsed |
18 | return xthal_get_ccount() - pulse_start; |
19 | } |
20 |
|