How to measure pulse width using interrupts or hardware timers in Arduino Uno

Hello y'all , iam new to the arduino forums. I'm in a bit of a pickle. I want to measure the pulse width of my smartphone flashlight pulses. The circuit has a photodiode, which is connected to an op-amp and from the op-amp, i connected its output to arduino analog pin A0. The pulse width is around 750 us. I used a simple software snippet to measure pulse width, but it is missing pulses below 1 ms width. Basically my pulse is high when it has a voltage of above 19.52 mV , else it is a Low pulse. I want to measure the pulse width of the high pulses. Requesting help from the pros here. Let me Share my Sketch

Sketch:

#define cellpin A0
const float mvc=4.88;
float counts=0;
float mv=0;
int ctr=0;
long int t1,t2;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); }

void loop() {
// put your main code here, to run repeatedly:
counts=analogRead(cellpin);
mv=counts*mvc; // this is the output voltage

if(mv>19.52 && ctr==0){

t1 = micros();
ctr=1; // ctr is used for detecting edges
}
if(mv<19.52 && ctr==1){
t2=micros();
Serial.print("The on-pulse duration in microsecond is "); /* if the output voltage(mv) is higher than 19.52 mV, consider it a high, else consider it a Low pulse.*/
Serial.println(t2-t1); // the pulse width in us

ctr=0;
t1=0;
t2=0;
}
}

What Arduino are you using ?
You probably have to use an external interrupt.
Maybe also, if available, the built in comparator.
Do the heavy (float) calculations in the loop after detecting a falling edge.
micros(), with its 4us resolution, should be good enough for the timing. If not, then consider input capture.

If using an ATmega328p, try this faster implementation ....

#define cellpin A0
word adcValue = 0;
float mv = 0;
byte ctr = 0;
unsigned long t1, t2;

void setup() {
  Serial.begin(115200);
}

void loop() {
  // faster 13μs analogRead (was 100μs)
  byte ADCSRAoriginal = ADCSRA;
  ADCSRA = (ADCSRA & B11111000) | 4; // 16 prescaler
  adcValue = analogRead(cellpin);
  ADCSRA = ADCSRAoriginal;

  if (adcValue >= 4 && ctr == 0) {
    t1 = micros();
    ctr = 1; // ctr is used for detecting edges
  }
  if (adcValue < 4 && ctr == 1) {
    t2 = micros();
   // Serial.print("The on-pulse duration in microsecond is "); /* if the output voltage(mv) is >= 19.52 mV (adcVal >= 4), consider it a high, else consider it a Low pulse.*/
    Serial.println(t2 - t1); // the pulse width in us
    ctr = 0;
    t1 = 0;
    t2 = 0;
  }
}

Sorry guys, edited the title, iam using an arduino Uno here

Ahh, no problem because ...
"Arduino/Genuino Uno is a microcontroller board based on the ATmega328P"

Hey , @dlloyd , tried your method , but it still misses pulses, okay let me elucidate me problem a bit deep here. Basically i wrote a linux bash script to control the on and offs of my smartphone-flashlight, so there should be 100 ons and 100 offs basically toggling after one another. ( without a delay, if i used sleep function ,it imposes too large of a period to my clock pulses, i wanna clock in 1 Khz flashlight signal, so without a delay works best!)

Now a basic thing is the width of the flashlight pulses is not constant! This is a fundamental problem to smartphone flashlight due to OS introduced delays which are variable. i tried your code and let me attach the pulse widths that i had obtained in us (even here the number of on pulses should be 100 , but are not 100)

pulse width output=[12956
1024
376
384
328
292
284
292
208
316
292
124
716
652
528
488
380
328
292
344
276
276
276
396
208
156
196
20
40
360
224
208
852
376
344
292
612
380
276
140
120
136
20
88
88
104
140
56
20
204
124
56
428
632
312
324
292
448
224
140
124
88
72
20
140
444
208
124
72
52
72
56
56
52
60
88
272
224
240
460
260
568
308
272
156
140
120
68
20
136
72
]

Your code works like a charm if i use a programmed pulse width or delay of about 1 ms or higher, let me attach some of the pulse widths(i dont wanna crowd all the 100 data here)

Some of the data:
[4300
4264
4048
3704
4540
5120
5104
4948
]

even here, you can clearly see the diversity in clock pulse width, even though i programmed the width to be 1 ms! This is due to the OS introduced delay , makes the clock pulse width variable in nature!

Now my guess is it is missing pulses (for the no programmed delay case) coz some of the pulse widths are too low , that the code fails to read those , correct me if iam wrong here
PS : pulse on is anuthing above 19.5 mv, else it is a pulse off

The example was just to speed things up, but printing is interfering and causing some missed readings.

@6v6gt's suggestion to use an external interrupt with the built in analog comparator should work. It'll take some research (check the ATmega328P datasheet and forum) and it take some significant modifications to the code.

Otherwise, could try saving 100 measurements to an array first, then print the results after capturing the 100 readings has completed.

Will do, thanks!

Maybe also show the circuit which interfaces to the photo diode. There may be scope there for improving the signal so that it can directly drive an external interrupt pin.

How, incidentally, have you come to such a precise voltage measurement of 19.52 mV ?

EDIT

It is possible to use a single transistor to condition a photodiode output so it can be used directly by an Arduino digital pin.
You simply bias the base of the transistor near its tipping point and the voltage generated by the diode's photovoltaic effect just tips the transistor into the desired state.

Here is an extract from a circuit from a learning IR remote control project which also uses the same diode (D1) for its transmitting and receiving operation. Just the receiving part is shown.

You're getting beats in the data. Both are digital processes running on asynchronous clocks. They're going to beat unless you synch the clocks. The tighter the timing the worse the beats. I think its one of those Hiesenberg uncertainty things.
Average, average, average, but that impacts your sample rate.

Whoops ... I commented out line #24 in post #3. At 115200 baud (11520 characters per sec), this line unnecessarily adds 41 characters (3559μs) between each measurement. Give this another test?

Attached below is my reciever circuit, the op-amp is a LM-358 dual op-amp , with a 10 V Vcc. The Vout in the last stage is connected to arduino pin A0 , this is my setting

An observation, whenever my flashlight is on , the output i get is above 19.52 mV like it starts from 24 mV and goes all the way to 200mV, whenever off , it gets like upto 14 mV. So i just choose 19.52 mV as a safe bet threshold to distinguish flash-on(1) from flash-off(0) state.

Already tried commenting it out, but not a great response yet, it still misses pulses

Here's an improved pulse detection and polling method you could try (unaffected by print) ...

#define cellpin A0
word pulseWidth[100];
word reading = 0;
word prevReading = 0;
byte ctr = 0;
byte pwi = 0;
unsigned long t1, t2;

void setup() {
  Serial.begin(115200);
  ADCSRA = (ADCSRA & B11111000) | 4; // 16 prescaler for ADC (13μs)
  for (int i = 0; i < 100; i++) {
    pulseWidth[i] = 0; // clears the array
  }
}

void loop() {
  prevReading = reading;
  reading = analogRead(cellpin);

  if (reading >= 4 && prevReading < 4 && ctr == 0) {  // rising edge detected
    t1 = micros();
    ctr = 1; // ctr is used for detecting edges
  }
  if (prevReading >= 4 && reading < 4  && ctr == 1) {  // falling edge detected
    t2 = micros();
    pulseWidth[pwi] = t2 - t1;
    pwi++;
    ctr = 0;
    t1 = 0;
    t2 = 0;
  }
  if (pwi == 100) { // print 100 results
    for (int i = 0; i < 100; i++) {
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(t2 - t1); // the pulse width in μs
      Serial.println(" μs");
    }
    for (int i = 0; i < 100; i++) {
      pulseWidth[i] = 0; // clears the array
    }
    pwi = 0;
  }
}

You meant Serial.print(pulseWidth[i]) right, else it just prints 0 all the way , as t1, t2 both are 0 finally

Yes.

So it starts from 24mV/4.88 = 5, the max is 200mV/4.88 = 41 and the min is 14mV/4.88 = 3

  • Try increasing the threshold of 4 (lines 21 and 25) to higher values until no pulses are missed.

It would be good to get a scope trace of your pulses.

Have you tried a higher gain (i.e. change Rf from 2.2K to 10K to get about 910mV max? Then using a higher detection threshold should be more reliable and accurate.

Will do it as the first thing tomm mornin, when i get to the lab.

Sounds good, will try and give an update!

image

Hi, @dlloyd there is some problem with my oscilloscope to give you an idea, Let me attach the past snapshot that i took( when my programmed delay is 1 ms) . You can see a near square wave here.

When i remove the delay, i get a graph something like this

image

no more a square wave and the time period is much shorter (in the order of us).

I have attached the clock pulse width values corresponding to the 2 graphs in post #6.

Going back to post #1 ...

What is the application?
Why is the pulse width important?

Regarding the poor signal you get when the delay is removed, inability to capture this on the scope could mean wrong scope settings, probe loading, photodiode circuit Cf value or filter value or even missing pulses.

I wonder how the signal would look on the serial plotter (with 13μs resolution) ...

const byte probePin = A0;
const word readings = 500;
word capture[readings];

void setup() {
  Serial.begin(115200);
  ADCSRA = (ADCSRA & B11111000) | 4; // 16 prescaler for ADC (13μs)
}

void loop() {
  if (analogRead(probePin) >= 4) {
    for (int i = 0; i < readings; i++) {  // record the readings
      capture[i] = analogRead(probePin);
    }
    for (int i = 0; i < readings; i++) {  // print the readings
      Serial.println(capture[i]);
    }
    delay(6000);
  }
}

An excellent question indeed, as i indicated earlier i wanna transmit 0s and 1s through smartphone flashlight. As indicated in post #6 , even when i program a delay(or a programmed pulse width for the clock signal, the pulse width varies due to OS introduced delay) , now how can i transmit 1s and 0s? Clock width varies so there will be a problem with reciever synchronisation . Let me elucidate, say you send 100 clock pulses or bits of width 1ms (1010.......like that you send 100 bits) , now at the reciever i will sample at the rate of 1 ms and get back the 1010.... information and this is a normal thing, but if the clock pulse width varies and is not the programmed 1 ms, then the reciever continues to sample at 1 ms and it would basically spit out wrong bit sequence! (say a high pulse comes at 2 ms width and my reciever would estimate it as 11 , but it should be only 1) . To overcome this problem, encoding bits in the form of pulse width is a viable solution. Thus, making me care so much about pulse width