I am trying to generate LED blink after 4 second using Interrupt but Interrupt is not triggering not even once . Request: if you have arduino uno r3 please check at your end and let me know result. I have read Timer counter section multiple times and applied everything i can for example :-
- Enabled Global Interrupt
- Select CTC Mode
- Enable Interrupt for OCIE0A
- Prescaling to clk/1024
- Initializing OCR0A
- When OCR0A equal TCNT0 ,interrupt will generate
int var;
void setup() {
// put your setup code here, to run once:
SREG = SREG | (1<<7); // Gloval interrupt enable
TCCR0A = TCCR0A | (1<<WGM01); // Clear counter on compare match mode
OCR0A = 255; // when TCNT equal OCR0 interrupt will generate
TIMSK0 = TIMSK0 | (1<<OCIE0A); // Output Compare Match A Interrupt Enable
TCCR0B = TCCR0B | (1<<CS01) | (1<<CS02); // Prescaling by 1024
DDRB = DDRB | (1<<5);
Serial.begin(9600); // Testing
Serial.println("Start"); // Testing
}
void loop() {
// put your main code here, to run repeatedly:
}
ISR(TIMER0_COMPA_vect){
var++;
Serial.print(var); // Testing
volatile long unsigned i;
if(var == 246){
PORTB = PORTB | (1<<5);
for(i=0; i<30000; i++);
PORTB = PORTB & ~(1<<5);
for(i=0; i<30000; i++);
var=0;
}
}
- clock is 16 00 00 00 Hz
- Prescaling by 1024 = 15625
- 1 Tick = 1/15625 = 0.00 00 64 sec
- OCR0 is initialized by 255
- TCNT0 Ticks to 255
- Total time taken to generate one interrupt = 255 * 0.00 00 64 = 0.01632 sec that means after every 0.01632 sec Interrupt supposed to generate
- How many interrupt is required to generate LED after 4 sec => 4/0.01632 = 246
Update working code
int var;
void setup() {
// put your setup code here, to run once:
SREG = SREG | (1<<7); // Gloval interrupt enable
TCCR0A =(1<<WGM01); // Clear counter on compare match mode
OCR0A = 255; // when TCNT equal OCR0 interrupt will generate
TIMSK0 = (1<<OCIE0A); // Output Compare Match A Interrupt Enable
TCCR0B = (1<<CS00) | (1<<CS02); // Prescaling by 1024
DDRB = DDRB | (1<<5);
Serial.begin(9600); // Initialize the USART
Serial.println("Start"); // Write the welcome message
}
void loop() {
// put your main code here, to run repeatedly:
}
ISR(TIMER0_COMPA_vect){
var++;
// Serial.print(var);
volatile long unsigned i;
if(var == 246){
PORTB = PORTB | (1<<5);
for(i=0; i<300000; i++);
PORTB = PORTB & ~(1<<5);
var=0;
}
}