00001 /* 00002 * Copyright (c) 2005-2006 David A. Mellis 00003 * 00004 * This program is free software: you can redistribute it and/or modify 00005 * it under the terms of the GNU Lesser General Public License as published by 00006 * the Free Software Foundation, either version 2.1 of the License, or 00007 * (at your option) any later version. 00008 00009 * This program is distributed in the hope that it will be useful, 00010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00012 * GNU Lesser General Public License for more details. 00013 00014 * You should have received a copy of the GNU Lesser General Public License 00015 * along with this program. If not, see <http://www.gnu.org/licenses/>. 00016 */ 00017 00018 00019 #include "wiring_private.h" 00020 #include "pins_waspmote.h" 00021 00022 /* Measures the length (in microseconds) of a pulse on the pin; state is HIGH 00023 * or LOW, the type of pulse to measure. Works on pulses from 10 microseconds 00024 * to 3 minutes in length, but must be called at least N microseconds before 00025 * the start of the pulse. */ 00026 unsigned long pulseIn(uint8_t pin, uint8_t state) 00027 { 00028 // cache the port and bit of the pin in order to speed up the 00029 // pulse width measuring loop and achieve finer resolution. calling 00030 // digitalRead() instead yields much coarser resolution. 00031 uint8_t bit = digitalPinToBitMask(pin); 00032 uint8_t port = digitalPinToPort(pin); 00033 uint8_t stateMask = (state ? bit : 0); 00034 unsigned long width = 0; // keep initialization out of time critical area 00035 00036 // wait for the pulse to start 00037 while ((*portInputRegister(port) & bit) != stateMask) 00038 ; 00039 00040 // wait for the pulse to stop 00041 while ((*portInputRegister(port) & bit) == stateMask) 00042 width++; 00043 00044 // convert the reading to microseconds. The loop has been determined 00045 // to be 10 clock cycles long and have about 12 clocks between the edge 00046 // and the start of the loop. There will be some error introduced by 00047 // the interrupt handlers. 00048 return clockCyclesToMicroseconds(width * 10 + 12); 00049 }
1.5.6