1
\$\begingroup\$

I have AVR MCU.
I am playing with timer now.
What I need ? I have timer counting up with some frequency. In each interrupt I am incrementing variable, and somewhere I need to check value of this variable and if equals 100, I need to stop timer count, set new value for frequency and continue counting down.
I cannot get how to stop timer and set new value to compare.
I have tried to select no clock source using mux selector register, but it continue to count up.
What is correct way to do this. Here is my code

// Arduino timer CTC interrupt example
// www.engblaze.com

// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define LEDPIN_UP 9
#define LEDPIN_DOWN 8
int current_value = 0;
void setup()
{
   Serial.begin(9600);  
   // pinMode(LEDPIN_UP, OUTPUT);

    // initialize Timer1
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
   // OCR1A = 3123;
    OCR1A = 1562;
    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler:
    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);
    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);
    // enable global interrupts:
    sei();
}

void loop()
{
    //digitalWrite(LEDPIN_UP, current_value);
  Serial.println(current_value);
       if(current_value==255) {
      TCCR1B |= (0 << CS10);
      TCCR1B |= (0 << CS12);
      Serial.println("Reseting timer");
    }
}

ISR(TIMER1_COMPA_vect)
{
    current_value++;

}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

To stop the timer you have to clear the three bits CS10, CS11 and CS12.

 TCCR1B |= (0 << CS10);
 TCCR1B |= (0 << CS12);

Those two lines has no effect on the register. Instead, use the following lines (Assuming CS11 stays cleared).

TCCR1B &= ~(1 << CS10);
TCCR1B &= ~(1 << CS12);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.