pulseIn函数用于读取引脚脉冲的时间长度,脉冲可以是HIGH或LOW。如果是HIGH,函数将先等引脚变为高电平,然后开始计时,一直到变为低电平为止。返回脉冲持续的时间长短, 单位为ms。如果超时还没有读到的话, 将返回0。
pulseIn函数返回值类型为无符号长整型(unsigned long),3个参数分别表示脉冲输入的引脚、脉冲响应的状态(高脉冲或低脉冲)和超时时间。函数原型在wiring_pulse.c中,如下:
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
{
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
uint8_t stateMask = (state ? bit : 0);
unsigned long width = 0;
// keep initialization out of time critical area
unsigned long numloops = 0;
unsigned long maxloops = microsecondsToClockCycles(timeout) / 16;
// wait for any previous pulse to end
while ((*portInputRegister(port) & bit) == stateMask)
if (numloops++ == maxloops)
return 0;
// wait for the pulse to start
while ((*portInputRegister(port) & bit) != stateMask)
if (numloops++ == maxloops)
return 0;
// wait for the pulse to stop
while ((*portInputRegister(port) & bit) == stateMask)
width++;
return clockCyclesToMicroseconds(width * 10 + 16);
}
可以在开发环境的下列实例程序中找到pulseIn函数的应用:
Memsic2125.pde、Ping.pde