The pulseIn() gives the duration of a HIGH or LOW impulse on a digital pin. ..
Can I assume, that it won't block the execution of code in loop() like delay() does?
If this assumption holds, loop() may pass pulseIn() several times before a 'duration' of some size has passed .. in that case, what will pulseIn() deliver if it yet doesn't know how long the pulse might be?
Can I assume, that it won't block the execution of code in loop() like delay() does?
I don't think so. It will block until the pulse has been measured, or the timeout value has passed.
You have all the source for the Arduino functions. The code for pulseIn() is in wiring_pulse.c
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
{
// cache the port and bit of the pin in order to speed up the
// pulse width measuring loop and achieve finer resolution. calling
// digitalRead() instead yields much coarser resolution.
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
// convert the timeout from microseconds to a number of times through
// the initial loop; it takes 16 clock cycles per iteration.
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) {
if (numloops++ == maxloops)
return 0;
width++;
}
// convert the reading to microseconds. The loop has been determined
// to be 20 clock cycles long and have about 16 clocks between the edge
// and the start of the loop. There will be some error introduced by
// the interrupt handlers.
return clockCyclesToMicroseconds(width * 21 + 16);
}
Thanks dxw00d,
Better use the analogRead instead then.
Hi,
Try using interrupts instead, something like this -
Duane B
Hi DuaneB,
I considered that, but there is the additional snag about my setup, that the sensor is 'very' jumpy. But it is an obvious choice once the pulse comes in clean.
Carsten53T:
The pulseIn() gives the duration of a HIGH or LOW impulse on a digital pin. ..
Can I assume, that it won't block the execution of code in loop() like delay() does?
No.