3.3.2 pulseIn(pin,state,timeout)

本文详细介绍了Arduino中的pulseIn函数,该函数用于测量指定引脚上脉冲信号的持续时间。文章解释了函数的工作原理,包括如何等待脉冲信号的开始与结束,并提供了具体的实现代码。此外还列举了两个应用实例,帮助读者更好地理解如何使用pulseIn函数。

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

转载于:https://www.cnblogs.com/jikexianfeng/p/6242642.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值