I'm trying to measure short delay, around 5-50us to generate a single pulse.
I tried a while loop with micros(), but time spent in each iteration takes too much time to ensure an accurate measure.
So I tried to use Timer1 to improve accuracy. Here is the code:
The strange behaviour is this works only for half of the loop iteration:
iteration n: pin0: blink, pin1: blink
iteration n+1: pin0: blink, pin1: -
iteration n+2: pin0: blink, pin1: blink
iteration n+3: pin0: blink, pin1: -
I want to generate a pulse with an good accuracy using Timer1:
I set PB1
I enable Timer1, configured to clear PB1 when TCNT1 reach OCR1A.
The only "unpredictable" time is how many cycles it takes between 1 and 2. I will do more investigation later, this is not the purpose on my post (but if you have a clue, please send it!).
My problem comes with the following implementation:
Problem: This does not work, output PB1 is always on.
I suspect the problem from the two last lines: incorrect TIFR read so the counter to stopped to early before clear PB1. But if remove them, the output is always off. It looks like the counter TCNT1 immediately reaches OCR1A.
First code: I do not understand why led controlled by timer1 works only for half of the main loop iteration:
What do you mean by that? What happens? What do you expect to happen?
while(TIFR & ocf1amask==0); // Wait for comparison
Personally I wouldn't be sitting there waiting for a match.
You don't seem to be in CTC mode. Is this intentional?
I'm not sure if you can manually enable port B1 and then have the timer turn it off. I may be wrong, but once you assign control of the port to the timer, the timer may control its on/off state.