Electronic – Why does the Atmega328 clock seem to be off by a factor of 2

atmegaclockfuse-bitsmicrocontroller

I have an Atmega328 chip I am trying to debug. I have a sketch that blinks an LED and echoes back things received over the RX/TX pins. I am using the "Import Arduino Sketch" feature in Atmel Studio 7. I want to use the internal 8 MHz clock.

The timer seems to be too slow by a factor of 2. I tell the LED to blink every second, but it takes two seconds. When I send text over the serial port I receive back gibberish, which is probably due to the baud rate not being the 9600 I want it to be.

I looked at the memory fuse to verify that I am using the internal clock. I also tried setting the clock prescaler to 1 in the sketch code.

Here is the section of the data sheet related to the clock frequency:
http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf

enter image description here

My fuse settings seem to be OK, I disabled the 8x divisor and specified to use the 8MHz internal clock:
enter image description here

The clock prescaler information is on page 47, essentially it says I need to make the most significant bit a 1 to allow changes to the rest of the bits, then I change the other bits to 0 to set a prescale factor of 1. If I try setting it to a factor of 2 the time delay is made worse by a factor of 2 and has a total of 4 seconds delay when the code wants 1 second.

void setup() {
CLKPR = (1 << CLKPCE); // enable a change to CLKPR
CLKPR = 0; // set the prescale factor to 1 
pinMode(greenLED, OUTPUT);
Serial.begin(9600);
analogWrite(greenLED, 15);
delay(1000);
analogWrite(greenLED, 0);
}

void loop() {
    analogWrite(blueLED, 15);
    delay(1000);
    analogWrite(blueLED, 0);
    delay(1000);
    String text;
    if (Serial.available()) {
    text = Serial.readString();
    Serial.println("Echo: " + text);
    }  
delay(30);
}

What other settings could be affecting the internal clock?

Best Answer

Arduino code expects Arduino clocks. If it has 16 MHz clock, it will run half as fast as it does not know that you are in fact using 8MHz clock. Apparently the boards.txt file contains board build configurations including the board clock that gets passed on as F_CPU define for building all libraries, so adding a new custom board entry should be enough for making it work with user clock rates.