Hello and thanks in advance for your consideration,
I'm writing a program that is intended to record data I'm capturing while performing an algorithm. I'd like to be able to maintain consistent write frequency between the different states of the high-level state machine but getting minor deviations in frequency.
Each state of course has a different number of instructions so I've created a timer in each state that I wait to expire before writing the data as the means to maintain the write frequency between states.
The simplified architecture is as follows:
State 1:
while(in state 1){
// Gather data
// Perform algorithm, if algorithm is completed this will exit the while loop in the state and return to the next state
// Use timer to maintain consistent write frequency - actual timer code below
while((TIFR & 0x04) == 0); // wait here until timer expires (the timer was started before entering state 1)
TCNT0 = 0x00; // Reset counter, starting timer again immediately
TIFR |= (1<<OCF0B); // clear the flag
// write data
}
State 2:
// In this state I just wait for a second timer (timer1) to expire before moving to the next state, all while continuing to record data
// Start timer1
while(Timer1_Expired == false){
// gather data
// wait for timer0 to expire to maintain consistent write frequency - actual timer code below
while((TIFR & 0x04) == 0); // wait here until timer expires
TCNT0 = 0x00; // Reset counter, starting timer again immediately
TIFR |= (1<<OCF0B); // clear the flag
// write data
}
return state3;
State 3:
// In this state I perform a few unrelated actions and then stay in a loop until the end of available memory, continuing to sample and record data
while(Address < Max_Address){
// gather data
// wait for timer0 to expire in order to maintain consistent write frequency - actual timer code below
while((TIFR & 0x04) == 0); // wait here until timer expires
TCNT0 = 0x00; // Reset counter, starting timer again immediately
TIFR |= (1<<OCF0B); // clear the flag
// write data
Address++;
}
There is no variation in each state, but there is variation between states.
The frequency in state 1 is 48.31kHz
The frequency in state 2 is 47.95kHz
The frequency in state 3 is 48.48kHz
Any thoughts or guidance would be greatly appreciated.
Thanks!