Arduino pulseIn experiments

Hi All,

I have been doing a simple experiment with PulseIn function in Arduino programming. Now It works pretty consistently (from 2us and above) independent of baud rate or any IO pin. Now I noticed that once in a while I get a offset of up to 6us.

I have created a 1000 cycle loop and got the data for 10us pulse, 100us, 500us, 1ms (using a function generator). I plotted the data into histogram as shown below for 10us, it shows that small number of time pulse duration read value is 4us.

6us is very consistent across other higher pulse inputs. Interesting thing is there no value of 7, 8 or 9us in between. It seem to point out Arduino is doing some internal task once in a while during pulseIn function execution. Now question: what is causing this 6us offset?

In case you are interested, I have attached data in excel for other 100us, 500us, and 1ms.

Here is 10us Pulse input from FunGen:

Here is code I used. Note: it loop 1000 times to read pulseIn duration:

int pin = 7;

unsigned long duration;
void setup()
** pinMode(pin, INPUT);**
** Serial.begin(115200);**
** for (int i=0;i<1000;i++)**
** duration = pulseIn(pin, HIGH);**
** Serial.println(duration);**


Have you considered timer interrupts?

pulseIn() uses looping to measure pulse lengths. If an interrupt happens during the loop, some time will be lost. You can try disabling interrupts to see if that helps. I would recommend a timeout no longer than 500 microseconds or you might lose millis() interrupts.

Timer1 has an Input Capture Register feature that will store the current timer count on a signal edge. You should be able to get 1/8th microsecond accuracy if you use this feature to measure pulses.