Search code examples
c++microcontrolleratmegaplatformio

PlatformIO ATMega324P util/delay.h not accurate


I am using PlatformIO and CLion to program an ATMega324P Microcontroller. The project is created with PlatformIO on a mac and opened in CLion. I can successfully build the program and run it on the ATMega324p. I run the following code successfully.

main.cpp

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB |= 1 << PINB0; 

    while (true)
    {
        PORTB ^= 1 << PINB0; 
        _delay_ms(100);
    }
}

Platformio.ini

[env:mightycore324]
platform = atmelavr
board = mightycore324
framework = arduino
upload_protocol = usbtiny
board_f_cpu = 16000000L

Although this code run the delay seems noticeably inaccurate. Do I have do anything to make sure the delay is working properly?


Solution

  • Your MCU is probably running off its internal RC oscillator. This oscillator isn't particularly precise -- it's specified as 8 MHz, but individual parts may run anywhere from 7.3 to 8.1 MHz.

    To get more accurate timing, you'll need to attach an external crystal and program the clock fuses accordingly.