I
guess I forgot to say I was operating at 16MHZ. 16us is probably close enough.
So I hook the sensor to PIND4 and set timer1 to a prescale of 256 Then I need to
enable the TICIE1 interrupt in TIMSK. But I still do not
understand how I time the "high" part. In the interrupt routine, I guess I
disable interrupts and save ICR1 to a variable and reenable
interrupts. Then the variable holds the elapsed time but how do I know
it it the "high" time and not the low time. On page 115 under Input Capture Unit
it mentions "and this change conforms to the setting of the edge detector, a
capture is triggerred." But I do not see anything about how to set the "edge
detector." Ideally it should start timing on the rising edge and trigger the
capture on the falling edge.
Also
what happens if the input capture exceed the timer
resolution?
-----Original Message-----
From: AVR-Chat@yahoogroups.com [mailto:AVR-Chat@yahoogroups.com] On Behalf Of Ned Konz
Sent: Tuesday, March 07, 2006 10:35 AM
To: AVR-Chat@yahoogroups.com
Subject: Re: [AVR-Chat] How to measure a pulse width
On Mar 6, 2006, at 8:14 PM, wbounce wrote:
I need to measure how long a pulse is. I have a m128. The pulse goes +5V for 1ms to 36.9ms and then goes 0v for a fixed 65ms. I need to time how long the +5V part is in 10us increments. How would I do that? I will wire the sensor generating the pulse to a pin. I seem to remember something about a capture ability but I do not understand how it works or how to set it up. The fact that the pulse is assymetrical probably does not help.I am already using timer0 fir a ms timer and timer3 (a and b) for pwm output. so I guess I would have to use timer1 or 2.Well, 10usec is 1/3690 th of 36.9 msec, so you're going to need a 16-bit timer.You have Timer1 and Timer3 to choose from.You're already using Timer3.That narrows it down.Look in the Atmega128 datasheet under "16-bit Timer/Counter / Input Capture Unit" to find the gory details of how you'd use Timer1 to do pulse timing.The asymmetry doesn't matter, as you're only measuring the high part.As far as 10usec resolution, this would depend on how fast your system clock was. At (say) 16MHz, your system clock would be 62.5nsec; you could then clock the timers at systemClock/256 to get 16usec resolution. Or systemClock/128 to get 8usec resolution.At systemClock/128, your maximum pulse width would be (65535*(128/16e6)), or about 524msec. You could even go for a faster clock.The pin you'd use would be ICP1, a/k/a PD4.And, above all, don't panic. For it says in the datasheet:The Input Capture unit is easy to use in normal mode. However, observe that the maximuminterval between the external events must not exceed the resolution of the counter.If the interval between events are too long, the timer overflow interrupt or the prescalermust be used to extend the resolution for the capture unit.Good luck,
--Ned Konz