harun caliskanoglu
harun caliskanoglu

Reputation: 3

How can I reset timer0?

my microcontroller is attiny85.Actually I have a few questions. I simply turn on the LED 8 seconds later with the code below.

1)Should I turn the interrupts off and on while reading the counter value? I've seen something like this in the wiring.c file, the millis function.

2)How can I safely set the counter variable to 0 whenever I want? Do I have to turn the interrupts off and on here? Should I set the variables TCCR0A, TCCR0A, TCNT0 to zero?How should a safe reset function be?

Actually, all my purpose is to make a safe counter in the main function that can count 8 seconds whenever I want and start from zero whenever I want.

My basic code in below :

#define F_CPU 1000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include <stdio.h>

volatile unsigned int counter = 0;


ISR(TIM0_COMPA_vect){ 
    //interrupt commands for TIMER 0 here
    counter++;
}



void timerprogram_init()     
{
// TIMER 0 for interrupt frequency 1000 Hz:
cli(); // stop interrupts
TCCR0A = 0; // set entire TCCR0A register to 0
TCCR0B = 0; // same for TCCR0B
TCNT0  = 0; // initialize counter value to 0
// set compare match register for 1000 Hz increments
OCR0A = 124; // = 1000000 / (8 * 1000) - 1 (must be <256)
// turn on CTC mode
TCCR0A |= (1 << WGM01);
// Set CS02, CS01 and CS00 bits for 8 prescaler
TCCR0B |= (0 << CS02) | (1 << CS01) | (0 << CS00);
// enable timer compare interrupt
TIMSK0 |= (1 << OCIE0A);
sei(); // allow interrupts

}

int main(void)
{
    /* Replace with your application code */

    timerprogram_init();

    DDRA|=(1<<7);
    PORTA &=~ (1<<7);

    while (1)
    {
        if(counter>8000)
        PORTA |= (1<<7);

    }
  
}

Upvotes: 0

Views: 1499

Answers (1)

Hamid Salehi
Hamid Salehi

Reputation: 101

First, there is no need to check the "counter" value in the super loop; In fact, this variable changes when an interrupt is created, so checking the variable should be done in the interrupt itself and if necessary, take only one flag from it. Secondly, a safe way to reset the counter is to first deactivate the frequency divider(TCCR0B) of the timer section (the counter timer is practically turned off) and then set the TCNT0 value to zero to reset the timer; And if necessary, you can safely force the counter timer to count by returning the divider value. Good luck.

Upvotes: 1

Related Questions