2

I'm finding that when I'm using Timer 1 that the micros() function stops functioning correctly. I thought that:

  1. Arduino internal functions (except PWM on pins 9. 10 which i'm not using) use timer 0
  2. micros() function doesn't actually rely on a timer (but millis does)

If i call TCCR1B |= (1 << CS11) | (1 << CS10); in setup().

The micros function will start reporting sporadic values after about 0.25s. E.g. the micros() will increase at a very low rate after that, and often go backwards.

I'm testing on an Arduino Uno.

I'm also trying to check if the timer interrupt being called might be too heavy. It's not doing anything much except some integer maths and one digitalWrite.

Elliot Woods
  • 834
  • 11
  • 20

1 Answers1

1

According to the datasheet, "”8-bit Timer/Counter0 with PWM” on page 93 and ”16-bit Timer/Counter1 with PWM” on page 111 share the same prescaler module, but the Timer/Counters can have different prescaler settings. The description below applies to both Timer/Counter1 and Timer/Counter0."

So it's likely not an interaction with clock select, but you have only 64 clocks to perform the interrupt and exit it. There's some overhead in entering and exiting the interrupt. And DigitalWrite isn't as fast as you think. So without counting instruction clock cycles, I think I'd pursue the line of thought from your last statement -- lighten the load in that interrupt by just setting a flag and then exit. Handle the flag in the main loop. When you're talking microseconds, it's especially important to get out of that ISR quickly. Pseudocode:

volatile uint8_t timerflag = 0;
ISR <timer1_whatever>
{
     timerflag = 1;
}

back in main loop:
if (timerflag == 1)
{
    <do something>

    timerflag = 0; // reset for next interrupt
}

Make sure your timeflag is declared as volatile since it's being changed inside an interrupt and checked outside the interrupt.

TomServo
  • 7,248
  • 5
  • 30
  • 47
  • Thanks JLH! In the mean time I also discovered it was an issue with the interrupt being too heavy. Actually even if i stick a `return` in to break out of the function after just a few if statements, it still overflows. I want to use the timer for stepper motor control (I want to have something like `tone` but also be able to know the exact number of steps performed). Trying to trim fat (and can consider quicker digitalWrite).. – Elliot Woods Jun 02 '17 at 13:06
  • 1
    I managed to fix my issue by switching to the FlexiTimer2 library which uses Timer2 instead. – Elliot Woods Jun 03 '17 at 04:25