Grumpy_Mike:
Hint, look at your sei() and cli() in both codes. Spot anything about them?
Do you just mean that i have them swapped in my AVR code?
GolamMostafa:
@OP
Many things are wrong in your codes, which are due to your incomplete understanding of the principles of CTC Mode operation of TC1 Module.
1. Your Arduino sketch is uploaded in my UNO but not running. The problem has disappeared when I have included and deleted the following codes:
TCCR1A = 0x00; //included in the setup()
cli(); //deleted from the ISR()
sei(); //deleted from the ISR()
**2.** The L (built-in LED) blinks at about 1.05 sec interval; whereas, you are expecting to see it blinking at 1-sec interval. The problem is the wrong value you have loaded into OCR1A register. How much should you load into OCR1A Register?
**(1)** The following is the Mode-4 CTC (you have set Mode-4 in your sketch) timing diagram of TC1.
![tc1ctcx.png|547x157](upload://nng7e4kXfHB6QACoyIOIwU9y5Pc.png)
Figure-1: Mode-4 CTC timing diagram of TC1
**(2)** TCNT1 begins counting up alone path AB of Fig-1 with initial value of 0. You want that match with the content of OCR1A register should happen after 1-sec time period. The TCNT1 is being driven by a clock frequency of 62500 Hz (16000000/256). Therefore, the OCR1A Regsister must be loaded with 62500 (0xF424) and not with 0xFFFF (~~65536~~ 65535 Edit: vide @Post6) for the L to blink (state change) at 1-sec interval. (~~65536~~ 65535 gives ~~65536~~ 65535/62500 ~= 1.05 sec time delay.)
**3.** The corrected program of your's
static bool flag =0;
void setup() {
// put your setup code here, to run once:
TCCR1A = 0x00; //this register contains WGM11, WGM10 bits
TCCR1B = (1<<WGM12)|(1<<CS12);
//OCR1A = 0xFFFF;
OCR1A = 0xF424;
TIMSK1 = (1<<OCIE1A);
sei();
TCNT1 =0;
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
}
ISR(TIMER1_COMPA_vect){
//cli(); no need; the interrupt has already been disabled by the MCU
if(flag == 0)
{
digitalWrite(LED_BUILTIN,HIGH);
flag =1;
}
else
{
digitalWrite(LED_BUILTIN,LOW);
flag=0;
}
//sei(); no need; the interrupt logic will be automatically enabled while returning form ISR
}
Thanks for taking the time to write all that. I didn't bother calculating the value since 1.05 s was close enough.
cattledog:
TCCR1A = 0x00; //included in the setup()
The reason to add this to setup with the Arduino IDE code is that the timers are preset for PWM outputs. If you don't clear the presets, you will not be in the mode you are trying to set.
Does Arduino document this?