Hello Everyone!
I have posted my code below which I have been using to measure pulse widths for 5 to 15 microsecond pulses. I am giving pulses from function generator with 1 or 2 Hz frequency. But my code makes one count every four microseconds so it measures pulse widths if the pulse is 4 microsecond or 8 or 12 and so on but not the values in between , for example for 10 microsecond pulse it measures either 8 or 12. I thought of using a external fast counter to improve get the accuracy but I have come to know that 16 MHz clock of arduino is more than enough to get the right results so if someone can help me out here with my code I would be extremely grateful to all of you.
Thanks all in advance and 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;
int count = 1;
//Initialize timer
float pulse_width= 0.0;
//capture ISR
ISR(TIMER1_CAPT_vect)
{
//if(ICP)
//if (digitalRead (8) == HIGH)
if ((PINB & B00000001) == B00000001)
{
//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.print(pulse_width);
Serial.print(" count = ");
Serial.println(count++);
//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();
}
}
}