Issue related to delay in ATmega4809 Curiosity Nano Board

63 Views Asked by At

I'm new to "ATmega4809 Curiosity Nano Board", I was trying the simple Blinking of LED with a delay of 1second. But the delay which i achieved is 1.24seconds.

How do I regulate this ? Please suggest how to regulate the delay exactly?

#include "mcc_generated_files/system/system.h"
#include <util/delay.h>
#include <avr/delay.h>
#include <avr/io.h>
#include <stdio.h>
/*
    Main application
*/

int main(void)
{
    SYSTEM_Initialize();
    LED0_SetDigitalOutput();

    while(1)
    {
        LED0_SetLow();
        _delay_ms(1000);
        LED0_SetHigh();
        _delay_ms(1000);

    }    
}
1

There are 1 best solutions below

5
Clifford On

That would depend entirely on the implementation of _delay_ms(). No doubt the clock frequency that is defined for is not the clock frequency you are running at.

The solution is to set the correct value for F_CPU as described in the documentation. The ATMega4809 datasheet shows clock options for either 16 or 20 MHz. Yours is clearly running slower than F_CPU used to calculate delays (20/16 = 1.25 - your measured 1.24 is within the +/-2% precision for the internal oscillator). Either select the higher clock rate option or modify F_CPU. Noting that the actual frequency is subject to a prescaler in MCLKCTRLB that defaults to 6, (see MegaAVR 0-series manual section 9.3.3) so the correct F_CPU value is either 16000000/6 or 20000000/6.

So to correct for 16MHz internal oscillator and default prescaler:

#include "mcc_generated_files/system/system.h"

#undef F_CPU
#define F_CPU (16000000 / 6)

#include <util/delay.h>
#include <avr/delay.h>
#include <avr/io.h>
#include <stdio.h>
/*
    Main application
*/

int main(void)
{
    ...

It is possible that F_CPU is set in system.h where you should probably correct it in preference to the brute force override as above. I guess the file is generated by some project configuration where you should correct it rather than the file itself. It may alternatively be set using a -D command-line definition. Wherever it is defined, correct it.

A note of caution should you consider increasing the frequency by changing the prescaler. The maximum permitted frequency is supply voltage dependent according to Table 4-3 in the datasheet. Further the Curiosity Nano is factory set to 3.3V, so you should not exceed 10MHz, without first selecting the 5V supply. If you exceed the "safe" frequency, your part may fail to start.