# MegaCoreX on ATMega4808 getting milis/micros to work with 20MHz clock

#### riccardo

##### Member
Hello,

I have a 4808 running Arduino code using the MegaCoreX library. If I run the chip with its internal 20MHz oscillator, millis and micros run too fast. I have tried setting a #define F_CPU value, but it doesn't help.

It works fine if I set the clock to 16MHz, but it would be great if I could use that extra bit of speed the chip is capable of. Does anyone know if this is possible?

#### Nigel Goodwin

##### Super Moderator

The highlighted line suggests that millis() only works properly for 8 or 16MHz due to the shift right.

#### Pommie

##### Well-Known Member
Looking at that code suggests that the delayMicroseconds works with a 20MHz clock.

Mike.

#### alyf80

##### New Member
Just spent some hours on the same issue, so in case anyone else stumbles into this:

The base frequency of the internal RC oscillator can only be controlled via the OSCCFG fuse, therefore changing F_CPU between a 16MHz-derived value and a 20MHz-derived value (see the table here) requires reprogramming the fuses.

If you flash a firmware compiled with F_CPU based on a different oscillator frequency, and forget updating OSCCFG, only the clock prescaler will be set -- so you get a +/- 25% error in timekeeping.

Wish this was documented somewhere...

#### riccardo

##### Member
The problem is that you get a timekeeping error even if you have both the fuse and F_CPU set to 20MHz. I don't understand well enough the code Nigel posted in order to see if there's any way to compensate other than doing it in the main program anywhere a timer is used.

#### alyf80

##### New Member
Then I guess we're having different problems....

I tested the example below with MegaCoreX 1.0.9 and F_CPU set to 8, 10, 16 and 20MHz:

C:
void setup() {
pinMode(PIN_PA7, OUTPUT);
}

void loop() {
static unsigned long savedSecond = 0;
static bool l = true;

unsigned long second = millis() / 1000;

if (second != savedSecond) {
digitalWriteFast(PIN_PA7, l = !l);
savedSecond = second;
}

}

In all cases I'm getting a 0.501 Hz square wave on PA7, well within the accuracy of the internal RC oscillator.

The code linked above is in the Arduino AVR core, it has nothing to do with MegaCoreX

How much fast is "too fast"?

Replies
1
Views
2K
Replies
2
Views
1K
Replies
6
Views
2K
Replies
5
Views
2K
Replies
3
Views
6K