Hello everyone.
I have developed an algorithm through which I am measuring pulse width by giving the pulses to the digital pin D8, my code takes one count after every 4 microseconds and then I have applied a formula in my code through which I am measuring pulse widths but the problem I am facing is that I have to measure pulse width of 10 microsecond but when I applied 10 microsecond pulse to arduino it either measures 8 microsecond or 12 microsecond. I would be extremely greatful if someone can help me out with detecting the pulse widths accurately. Here is my code
#define ICP PINB0
//Variables holding three timestamps
volatile uint16_t ov_counter, rising, falling;
//capture Flag
volatile unsigned int flag = 0;
volatile uint32_t counts;
volatile uint16_t time;
int val = 0; // variable to store the read value
int lastPulse = LOW;
//Initialize timer
float pulse_width= 0.0;
//capture ISR
ISR(TIMER1_CAPT_vect)
{
//if(ICP)
if (digitalRead(8) == HIGH)
{
//save start time
rising=ICR1;
//set to trigger on falling edge
//TCCR1B&=~(1<<ICES1);
TCCR1B &= 0xBF;
//reset overflow counter
ov_counter=0;
}
else
{
//save falling time
falling=ICR1;
TCNT1 = 0;
//rising edge triggers next
//TCCR1B|=(1<<ICES1);
TCCR1B |= 0x40;
counts=(uint32_t)falling-(uint32_t)rising + (uint32_t)ov_counter;
/you can convert coutns to seconds and send to LCD/
}
}
//Overflow ISR
ISR(TIMER1_OVF_vect)
{
//increment overflow counter
ov_counter++;
}
void setup()
{
Serial.begin(9600) ;
delay(100);
Serial.println("test");
//Set Initial Timer value
TCNT1=0;
//First capture on rising edge
TCCR1B|=(1<<ICES1)| (1<<CS10) | (1<<ICNC1);
//TCCR1B|=(1<<ICES1)| (1<<CS10);
//Enable input capture and overflow interrupts
TIMSK1|=(1<<ICIE1)|(1<<TOIE1);
//Enable global interrutps
sei();
}
void loop()
{
val = digitalRead(8); // read the input pin
if (val != lastPulse)
{
lastPulse = val;
if (val == LOW)
{
// cli();
pulse_width = counts*4;
Serial.print("width = ");
Serial.println(pulse_width);
//clear overflow counters;
ov_counter=0;
//clear interrupt flags to avoid any pending interrupts
// TIFR1=(1<<ICF1)|(1<<TOV1);
//enable input capture and overflow interrupts
// TIMSK1|=(1<<ICIE1)|(1<<TOIE1);
// highCounter++;
// sei();
}
}
}