Skip to main content
Arduino

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Adjust time calculation after Timer0 frequency change

I have an Arduino Nano with an 328P and need all 6 PWM pins.

Thus, I had to adjust the prescaler and WGM Mode of Timer0.

It is now in phase correct PWM mode with a prescaler of 1.

TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
TCCR0B = _BV(CS00);

Now I need a working time calculation for other libraries, but since Timer0 had that duty everything is out of order now.

I tried adjusting the wiring.c

// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

to this

#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 510))

But it's like I didn't change anything. (tested other settings that were changed so it was compiled anew )

Whole Code:

void setup() {
 // Set Timer 0, 1 and 2
 // Register A: Output A and B to non-inverted PWM and PWM mode to phase correct.
 // Register B: Pre Scaler to 1.
 TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
 TCCR0B = _BV(CS00);
 TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
 TCCR1B = _BV(CS10);
 TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
 TCCR2B = _BV(CS20);
 pinMode(8, OUTPUT);
}
void loop() {
 digitalWrite(8, LOW);
 delay(65000);
 digitalWrite(8, HIGH);
 delay(65000);
}

Answer*

Draft saved
Draft discarded
Cancel
8
  • You wrote: "I believe in phase correct mode the timer overflows every 510 counts, not 512 as indicated by Edgar". Please, read my answer again, and do not misquote me. Commented Oct 12, 2016 at 14:27
  • Sorry, I was refering to this line "#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))" - I have updated my comment, correct me if I am wrong here, I didn't intend to misquote Commented Oct 13, 2016 at 12:13
  • There is a very good reason for having 512 instead of 510 in this line. Read my answer and you will understand. Commented Oct 13, 2016 at 12:28
  • Okay, so you are adding two timer counts, each being 62.5ns, to account for the error caused by the forced round-down? Commented Oct 13, 2016 at 12:38
  • 1
    Edgar, if you would like to continue helping me I decided that instead of answering a question with questions of my own and potential misinformation I would ask a question Commented Oct 13, 2016 at 14:48

AltStyle によって変換されたページ (->オリジナル) /