I have written 3 codes for led toggling and checked the delay on osciloscope to find that the delay of these three codes was not same .
#include <Arduino.h>
void setup() {
cli();
DDRB = (1 << DDB5);
//TCNT2=5;
TIMSK2 |= (1 << TOIE2);
TCCR2B = (1<<CS22);
sei();
}
ISR(TIMER2_OVF_vect) {
static short short_cnt= 0;
//TCNT2=5;
short_cnt++;
//if(short_cnt==500)
{
PORTB ^= (1 << PORTB5);
short_cnt=0;
}
}
void loop() {
}
in this code the led is toggled every 2ms rather than the expected 1 ms.
Similar behavior is seen in the following code :-
void setup() {
TCNT2=5;
TCCR2B = (1<<CS22);
DDRB=B00100000;
}
void loop() {
// put your main code here, to run repeatedly:
long counter = 0;
//while(counter<1000){
while((TIFR2&(1<<TOV2))==0);
counter++;
TCNT2=5;
TIFR2|=(1<<TOV2);
//}
PORTB ^= (1<<5);
}
but in the following code the delay is found to be 1ms as expected : -
#include <Arduino.h>
void setup() {
cli();
DDRB = (1 << DDB5);
TCCR2A=(1<<WGM21);
TIMSK2 |= (1 << OCIE2A);
OCR2A = 250;
TCCR2B = (1<<CS22);
sei();
}
ISR(TIMER2_COMPA_vect) {
PORTB ^= (1 << PORTB5);
}
void loop() {
}