|
| 1 | +/* |
| 2 | + pulse.c - wiring pulseIn implementation for esp8266 |
| 3 | + Copyright (c) 2015 Hristo Gochkov. All rights reserved. |
| 4 | + This file is part of the esp8266 core for Arduino environment. |
| 5 | + This library is free software; you can redistribute it and/or |
| 6 | + modify it under the terms of the GNU Lesser General Public |
| 7 | + License as published by the Free Software Foundation; either |
| 8 | + version 2.1 of the License, or (at your option) any later version. |
| 9 | + This library is distributed in the hope that it will be useful, |
| 10 | + but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 12 | + Lesser General Public License for more details. |
| 13 | + You should have received a copy of the GNU Lesser General Public |
| 14 | + License along with this library; if not, write to the Free Software |
| 15 | + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
| 16 | +*/ |
| 17 | +//#include <limits.h> |
| 18 | +#include "wiring_private.h" |
| 19 | +#include "pins_arduino.h" |
| 20 | + |
| 21 | + |
| 22 | +extern uint32_t xthal_get_ccount(); |
| 23 | + |
| 24 | +#define WAIT_FOR_PIN_STATE(state) \ |
| 25 | + while (digitalRead(pin) != (state)) { \ |
| 26 | + if (xthal_get_ccount() - start_cycle_count > timeout_cycles) { \ |
| 27 | + return 0; \ |
| 28 | + } \ |
| 29 | + } |
| 30 | + |
| 31 | +// max timeout is 27 seconds at 160MHz clock and 54 seconds at 80MHz clock |
| 32 | +unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout) |
| 33 | +{ |
| 34 | + const uint32_t max_timeout_us = clockCyclesToMicroseconds(UINT_MAX); |
| 35 | + if (timeout > max_timeout_us) { |
| 36 | + timeout = max_timeout_us; |
| 37 | + } |
| 38 | + const uint32_t timeout_cycles = microsecondsToClockCycles(timeout); |
| 39 | + const uint32_t start_cycle_count = xthal_get_ccount(); |
| 40 | + WAIT_FOR_PIN_STATE(!state); |
| 41 | + WAIT_FOR_PIN_STATE(state); |
| 42 | + const uint32_t pulse_start_cycle_count = xthal_get_ccount(); |
| 43 | + WAIT_FOR_PIN_STATE(!state); |
| 44 | + return clockCyclesToMicroseconds(xthal_get_ccount() - pulse_start_cycle_count); |
| 45 | +} |
| 46 | + |
| 47 | +unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout) |
| 48 | +{ |
| 49 | + return pulseIn(pin, state, timeout); |
| 50 | +} |
0 commit comments