c - Longer Time Delay When More Then One "while" Polling Instruction -


microcontroller : atmega328p in arduino uno
clock frequency : 16mhz

void timedelay_ctc(float sec, unsigned char times)          //0.1 <= sec <= 4 {     ocr1a = (sec / 0.000064f) - 1;     tccr1a = 0b00000000;     tccr1b = 0b00001101;     for( unsigned char = 1; <= times; i++ )     {         while( (tifr1 & (1<<ocf1a)) == 0 );         tifr1 |= (1<<ocf1a);     }     tccr1a = 0;     tccr1b = 0; } 

the above function used calculating number of time delay cycles , implement in ctc mode. works well. now, want write similar function in normal mode. folowing code.

void timedelay_norm(float sec, unsigned char times) {     unsigned int cycle = (sec / 0.000064f);     tcnt1 = 65534 - cycle;     tcnt1 = 49910;     tccr1a = 0b00000000;     tccr1b = 0b00000101;     for( unsigned char x = 1; x <= 2; x++ )     {         while( (tifr1 & (1<<tov1)) == 0 );         tifr1 |= (1<<tov1);     }     tccr1a = 0;     tccr1b = 0; } 

however, normal mode function argument "times" > 1, time delay longer expected. so, tried following code.

void timedelay_norm(float sec, unsigned char times) {     //unsigned int cycle = (sec / 0.000064f);     //tcnt1 = 65534 - cycle;     tcnt1 = 49910;                              //cycles 0.5sec     tccr1a = 0b00000000;     tccr1b = 0b00000101;     //for( unsigned char x = 1; x <= 2; x++ )     //{         while( (tifr1 & (1<<tov1)) == 0 );      //run 0.5sec 2 times delay 1sec         tifr1 |= (1<<tov1);         while( (tifr1 & (1<<tov1)) == 0 );         tifr1 |= (1<<tov1);     //}     tccr1a = 0;     tccr1b = 0; } 

i found when run following instruction 2 times, time delay longer expected. delay around 5s instead of 1s.

while( (tifr1 & (1<<tov1)) == 0 ); tifr1 |= (1<<tov1); 

can teach me how make work? or give me hints.

thank help!

you not reset tcnt1 between loop iterations.

on first loop count (uint16_max - 49910) cycles. after tov1 set, tcnt1 rolls on 0 (overflow) , counts way uint16_max causes longer delay.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -