Home > database >  atmega328 ctc mode timer
atmega328 ctc mode timer

Time:11-01

So i wanted to make a timer on the atmega328p µC using the CTC Modus. The idea was, that every 10milliseconds when the interrupt function is called , in that function i schould increase a variable millisekunden by 10. and once it reaches 1000 it schould be printed out . The datasheet can be found here: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf With registers i can change the Mode to the CTC Mode and set up the right Prescaler on the timer. It is a 16Mhz CPU. So the formula is : T_clock * Prescaler * OCR0A = time( unit is seconds) So i calculated: (1/ 1610^6) * 1024 * x = 1010^-3(i wanted 10 milli seconds). and x is then 155. With the bits CS00 and CS02 i set up the prescaler to 1024. OCR0A was then set to 155 as the formula says. CTC mode was enabled by setting the BIT WGM01. And the last thing was that i increase the variable millisekunden in the interrupt function. For some reason it doesnt want to work. Can anyone pease help me?

   #include "Arduino.h"

volatile unsigned long int millisekunden;
unsigned long int last_msg;
char buffer[128];

void setup() {

  TCCR0A |= (1 << WGM01);                // CTC Modus
  TCCR0B |= (1 << CS02) | (1 << CS00);  // Prescaler 1024
  
  OCR0A = 155;

  // Compare Interrupt
  TIMSK0 |= (1 << OCIE0A);

  Serial.begin(9600);
}

void loop() {
  if (millisekunden - last_msg >= 1000) {
    sprintf(buffer, "t=[%lu]", millisekunden);

    Serial.println(buffer);
    last_msg = millisekunden;
  }


}

// Timer-Interrupt-Routine
ISR(TIMER0_COMPA_vect) {
  millisekunden = millisekunden   10;
}


  

CodePudding user response:

You forgot to globally enable interrupts. Add sei() at the end of setup()

  • Related