Why does arduino init() break timers?

This program toggles an LED on pin PB7 (pin 13 on Arduino with ATMega2560) every 50 000 clock cycles. It doesn’t use any interrupts.

This works when it is defined as int main() but as void setup() TCNT1 seems to randomly bounce up and down without ever reaching the threshold. This does not change if we use e.g. timer 4 instead of timer 1.

int main() {
  // Set pin PB7 to output
  // equivalent to pinMode(LED_BUILTIN,OUTPUT);
  DDRB |= 1 << 7;
  
  // Timer/Counter Control Register for timer 1: set Clock Source to clk/1 no prescaling
  TCCR4B |= (1 << CS10);

  for (;;)
  {
    // TODO if the counter/timer has reached the threshold
    if(TCNT4 >= 50000) {
      // Toggle PB7: if it was high, make it low, and if it was low, make it high
      PORTB ^= (1 << 7); 
      // TODO reset timer
      TCNT4 = 0;
    }
  }
}

How do I do this with Arduino?

Init sets up the hardware. No doubt some of the timers are set up so that things like millis and micros work correctly. I suspect that you have established that timer one is an example of this.

So you are setting one bit in one register and expect the other 7 bits in that register and the 8 bits in TCCR4A to already be the way you want them? How do you expect the Arduino core to provide you with analogWrite() capability without setting up the timers?

When you use a timer, be sure to set ALL of the bits you want set. If you change TCCR4B |= (1 << CS10); to

TCCR4A = 0;
TCCR4B = 1 << CS40;

You shoud get the result you hoped for but didn’t code for. :slight_smile:

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.