I am trying to use a Pololu POL4079 sensor to measure distances.
I use pulseIn() to read the width of the pulse given by the sensor, and transform it into a distance, following the formula given by Pololu.
But I found that, when I use delay() between two measurements (in the loop(), after Serial.println), I get very different figures. I tried with delay(1000), delay(100), delay(10)...
I must add that no measure seems to be correct: the distance value doesn't make sense and it fluctuates a lot.
How can a delay() change the value of the pulseIn() ?
How about using the demo-code that is provided by the manufacturer itself?
found here
// Example Arduino program for reading the Pololu Distance Sensor with Pulse Width Output, 300cm Max
// Change this to match the Arduino pin connected to the sensor's OUT pin.
const uint8_t sensorPin = 2;
void setup()
{
Serial.begin(115200);
}
void loop()
{
int16_t t = pulseIn(sensorPin, HIGH);
if (t == 0)
{
// pulseIn() did not detect the start of a pulse within 1 second.
Serial.println("timeout");
}
else if (t > 1850)
{
// No detection.
Serial.println(-1);
}
else
{
// Valid pulse width reading. Convert pulse width in microseconds to distance in millimeters.
int16_t d = (t - 1000) * 4;
// Limit minimum distance to 0.
if (d < 0) { d = 0; }
Serial.print(d);
Serial.println(" mm");
}
}
I don't understand how the delay() can have an effect on the pulse measurement. Isn't the pulseIn() just measuring the first pulse width it finds when it is called ? How can it impact the next loop iteration? There must be something I'm missing!
Hi geneha4
In the past, I had the same issue.
After various tests, I had solved it by stopping the interrupts before the pulse-in and reactivating them immediately after.
so try this code:
while (digitalRead(sensorPin) == HIGH) { };
noInterrupts();
t = pulseIn(sensorPin, HIGH);
interrupts();
d = (t - 1000)*4;
Serial.println(d);
delay(1000);
I don't see any reason for this, except when one or more ISRs are active. If the sketch doesn't use any ISR, I can't get why pulseIn should be messed by interrupts. If there's something I don't know, I'm open to enhance my knowledge
As pulseIn() is a blocking function, in your case I suspect one (or more) of included libraries has active hardware interrupts, making pulseIn() to fail its timings. This means your workaround could be the solution, if you are sure it can't make problems to a loaded library.