How to count time in interruption and set is as a global variable ? My microcontroller is Atmega8, F_CPU is 16MHz, programming language is C. I know few things, that line below is initialization of clock.
TCCR1B |= (1 << CS10);
And this line do, that global variable "a" get value of cycles divided by "xxx". But what value must be assigned to xxx ?
a = TCNT1/xxx;
PS1: I want to count last turn of my propeller in propelled LED display and give this value to next interrupt to display image in right way.
PS2: To do delays, I use function: _delay_ms().
first using _delay_ms
is not a good way to do proper timing.
I would suggest the following: use timer1 to measure the frequency of your rotor. When you get your positional interrupt (assume one per turn) write the current timer value to a variable. On each of the following interrupts calculate the difference of cycle counter (do correctly consider the overflow).
Now you have the number of cycles per revolution. i would now set up a second timer in a way, that the counters top value (CTC mode) is the same as your measured cycle number divided by the your angular resolution of your display. So in the overflow-interrupt you can latch the new data to the LEDs.
an example:
preconditions/assumptions:
With this values your should get a difference of 29197 Timer-Ticks that translates to 116788.3 CPU-Cycles per revolution. Divided by 200 lines you have 583.94 Cycles per section. That number is too large for an 8-Bit counter. Using prescaler 2 gives 291.97 -still too large. So you have to use the next greater prescaler of (hopefully) 4 to the value gets 145.98. Round up to 146 and -1 because 0 also is counted. So i would suggest to use 145 as top value for this counter. This consideration has to be implemented programmatically. getting the cycle value and increasing the prescaler as long as it does not fit into your 8bit.
the whole program would look like the following:
volatile uint16_t oldTimer=0;
volatile uint16_t newTimer=0;
volatile uint8_t flag=0; // bit 1 = push new data, bit 2 = new revolution measurement
ISR(Postional Interupt){
oldTimer = newTimer;
newTimer = TCNT1;
flag |= 2;
}
ISR(timer2_overflow){
latchDataToOutput();
flag |= 1;
}
int main()
{
while(1){
if(flag & 2){
calcNewTimer2Timing();
flag &= ~2;
}
if(flag & 1){
OutputDataToShiftRegister();
flag &= ~1;
}
}
}