2

I want to change timer0 frequency because I need to use 4 PWM pins at a frequency lower than 500Hz and the SPI on an ATmega328. So I changed timer2 to Fast PWM with 64 divisor, enabled the overflow interrupt for timer2 and disabled the overflow interrupt for timer0:

 TCCR2A = _BV(WGM21) | _BV(WGM20);
 TCCR2B = _BV(CS22);
 TIMSK2 |= (1 << TOIE2); // enable overflow interrupt for timer2
 TIMSK0 &= ~(1 << TOIE0); // disable overflow interrupt for timer0

and changed the ISR vector in wiring.c from ISR(TIMER0_OVF_vect) to ISR(TIMER2_OVF_vect).

But delay doesn't work. What can be the problem?

asked Jan 23, 2018 at 16:15
4
  • I would guess Serial and delay rely on timer 2 and you have just changed it. Commented Jan 24, 2018 at 11:38
  • HardwareSerial does not use timers. delay uses Timer 0. Commented Feb 9, 2018 at 5:13
  • Please post a Minimal, Complete, and Verifiable example. Commented Feb 9, 2018 at 5:13
  • I don't know if millis() and micros() work - why not? Write a "blink" sketch and find out. Commented Feb 9, 2018 at 5:13

1 Answer 1

1

Now everything works except for delay()

delay() uses micros() and micros() reads the hardware registers, like this:

unsigned long micros() {
 unsigned long m;
 uint8_t oldSREG = SREG, t;
 cli();
 m = timer0_overflow_count;
#if defined(TCNT0)
 t = TCNT0;
#elif defined(TCNT0L)
 t = TCNT0L;
#else
 #error TIMER 0 not defined
#endif
#ifdef TIFR0
 if ((TIFR0 & _BV(TOV0)) && (t < 255))
 m++;
#else
 if ((TIFR & _BV(TOV0)) && (t < 255))
 m++;
#endif
 SREG = oldSREG;
 return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

You would need to change all those references (TCNT0, TIFR0, TOV0 etc.) to use the Timer 2 equivalents.

answered Feb 9, 2018 at 5:18
2
  • This fixed it. Strange that micros() works fine without the fix? Commented Feb 14, 2018 at 5:07
  • Appeared to work. I'm sure over a longer interval you would have seen anomalies. Commented Feb 14, 2018 at 8:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.