Correcting output of micros() when changing the frequency

I need a different PWM frequency for pins 5/6, which can be achieved as follows

TCCR0B = TCCR0B & B11111000 | B00000001; // for a PWM frequency of 62500.00 Hz
TCCR0B = TCCR0B & B11111000 | B00000010; // for a PWM frequency of 7812.50 Hz
TCCR0B = TCCR0B & B11111000 | B00000011; // for a PWM frequency of 976.56 Hz (the DEFAULT)
TCCR0B = TCCR0B & B11111000 | B00000100; // for a PWM frequency of 244.14 Hz
TCCR0B = TCCR0B & B11111000 | B00000101; // for a PWM frequency of 61.04 Hz

This of course messes up the results of micros() as they all use the same Timer0.

Is it possible to solve this problem by multiplying the result of micros by the opposite factor or changing micros() to Timer2?

What MCU? For what purpose?

ATmega328P, DCC decoder.

Multiplying the result will cause problems if you rely on the counter wrapping, e.g. with code like micros()-last_time > timer_period

The builtin micros() is not override-able (at least on AVR), but if you create your own micros() function, you can use whatever timer you want.

Thanks. I don't know what a

is, but I believe you when you say you need another frequency. I'm not saying it can or can't be done what you ask, but have you looked into other Arduino boards / solutions?

The micros() function is used by several other Arduino functions like delay and Wire and may be used by external libraries. Messing with it will probably cause many problems.
Bett0r to use different PWM pins.

I was thinking of micros()-last_time > 64*timer_period for 62.5kHz. Would that work?

I think that is ok.

I am aware of this solution. But I have already made PCBs and don't want to start from scratch. I only use NmraDCC library, which only has the micros() call, so I was thinking of editing the library manually.

Are you sure you don't use any Arduino functions or any other libraries that use micros()?

Well I just tested and replacing micros() by micros()/64 for 62.5kHz worked.

1 Like

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