PULSIN Pin, State, Variable {, Resolution}

Function
Measure the width of a pulse on Pin described by State in units of Resolution and store the result in Variable.

Quick Facts
  Range of Variable    0 (no pulse) to 255 (byte) or 65,535 (word)
  Units in Resolution    10 µs (0.01 ms)
  Minimum pulse width    10 µs
  Maximum pulse width    650.25 ms (byte), 167.11 s (word)

Explanation
PULSIN is like a fast stopwatch that is triggered by a change in state (0 or 1) on the specified pin. The entire width of the specified pulse (high or low) is measured, in units shown above and stored in ByteVar.

Many analog properties (voltage, resistance, capacitance, frequency, duty cycle) can be measured in terms of pulse duration. This makes PULSIN a valuable form of analog-to-digital conversion.

PULSIN will wait for the desired pulse, for up to the maximum pulse width it can measure, shown in the table above. If it sees the desired pulse it measures the time until the end of the pulse and stores the result in Variable. If it never sees the start of the pulse, or the pulse is too long (greater than the Maximum Pulse Width shown above), PULSIN "times out" and store 0 in Variable. This operation keeps your program from locking-up should the desired pulse never occur.

  PULSIN RA.0, 1, pWidth                        ' measure 10 - 2550 us pulse

In the example above, pin RA.0 will be set to input mode, wait for a low-to-high transition, then measure the period that the pin stays high. Using the default Resolution of 10 microseconds, a pulse from 10 microseconds to 2.55 milliseconds in width can be measured (assuming pWidth is a byte).

Since PULSIN uses a byte variable for storage, the Resolution parameter can be used to allow the measurement of wider pulse widths. For the best accuracy, set Resolution to the smallest value that will allow the measurement of the greatest expected pulse width.

Get_Button:
  PULSIN RA.1, 0, btnIn, 100                    ' wait for (low) button press 
  IF btnIn < 50 THEN Get_Button                 ' at least 50 ms?
  RETURN

The subroutine above will monitor the state of RA.1, waiting for it to go low and stay low for at least 50 milliseconds. This is a useful method of debouncing a button input.


Related instruction: PULSOUT
Related project: SIRCS Decoder