PulseIn
Syntax
Variable = PulseIn Pin, State
Overview
Change the specified pin to input and measure an input pulse.
Parameters
Variable is a user defined variable. This may be a word variable with a range of 1 to 65535, or a byte variable with a range of 1 to 255. Pin is a Port.Pin constant that specifies the I/O pin to use. State is a constant (0 or 1) or name High - Low that specifies which edge must occur before beginning the measurement.
Example
Device = 18F25K40
' Select the device to compile for
Declare Xtal = 16 ' Tell the compiler the device will be operating at 16MHz
Declare Hserial_Baud = 9600 ' Set the Baud rate for HRsoutLn
Dim MyByte as Byte
Do
MyByte = PulseIn PORTB.0, 1
' Measure a pulse on pin 0 of PORTB.
HRsoutLn Dec MyByte, " "
' Display the reading
Loop
' Repeat the process.
Notes
PulseIn acts as a fast clock that is triggered by a change in state (0 or 1) on the specified pin. When the state on the pin changes to the state specified, the clock starts counting. When the state on the pin changes again, the clock stops. If the state of the pin doesn't change (even if it is already in the state specified in the PulseIn instruction), the clock won't trigger. PulseIn waits a maximum of 0.65535 seconds for a trigger, then returns with 0 in variable.
The variable can be either a Word or a Byte . If the variable is a word, the value returned by PulseIn can range from 1 to 65535 units.
The units are dependant on the frequency of the crystal used. If a 4MHz crystal is used, then each unit is 10us, while a 20MHz crystal produces a unit length of 2us.
If the variable is a byte and the crystal is 4MHz, the value returned can range from 1 to 255 units of 10µs. Internally, PulseIn always uses a 16-bit timer. When your program specifies a byte, PulseIn stores the lower 8 bits of the internal counter into it. Pulse widths longer than 2550µs will give false, low readings with a byte variable. For example, a 2560µs pulse returns a reading of 256 with a word variable and 0 with a byte variable.