# pulseIn() and pulseInLong() in Arduino

ArduinoHardwareSoftware & Coding

If there is an incoming pulse on a pin, and you need to measure the duration of the pulse then the pulseIn() function comes in handy.

## Syntax

The syntax is −

pulseIn(pin, value)

Where pin is the number of the pin on which you wish to measure the pulse. The value is the level of the pulse. It can be HIGH or LOW.

For example, if you set the value to HIGH, it means that as soon as the voltage on the pin goes from LOW to HIGH, the measurement of the time will start. It will stop when the voltage on the pin goes from HIGH to LOW.

The pin returns the time of the pulse in microseconds.

You can also use an alternate form of the function, which takes in a 3rd argument: timeout

pulseIn(pin, value, timeout)

The timeout indicates the number of microseconds to wait for the pulse to start. If you don’t specify this argument, the default timeout is 1 second. In other words, if, after the call to the pulseIn function, the pulse doesn’t start within 1 second (or timeout), this function will give up and return 0.

If you have a very long pulse that needs to be measured, and have interrupts enabled in your code, you could use pulseInLong() instead of pulseIn. The syntax is similar, and the timeout argument is optional over here as well. This function can be used for measuring pulses from 10 microseconds to 3 minutes in length, and can be used only if interrupts are enabled.It is prone to errors for shorter pulses and gives the highest resolution for larger pulses.

## Example

An example implementation is given below −

int pulsePin = 6;
unsigned long pulseDuration;

void setup() {
Serial.begin(9600);
pinMode(pulsePin, INPUT);
}
void loop() {
pulseDuration = pulseIn(pulsePin, HIGH);
Serial.println(pulseDuration);
}

The syntax for pulseInLong remains the same; only the function name changes from pulseIn() to pulseInLong().

Published on 30-Jul-2021 12:47:56