常见问答

FAQ

How to generate an accurate delay time?  Issue Date:2020-02-07

If user wants to generate an accurate delay time, it is recommended to use the __nop() to get the accurate one CPU clock cycle delay. However, because the speed of Flash is lower than CPU, some optimization and cache technology will make the __nop() delay not accurate. Hence, it is recommended to put the source code of delay function on SRAM to avoid inaccurate delay time of __nop().

 

Example: to generate a 2 us delay time accurately.

(1) CPU clock= 32MHz: 1 CPU clock cycle takes 1/32000000 sec = 31.25 ns

(2) 2 us delay time = 2000 ns / 31.25 ns = 64 times of CPU clock cycle

 

1. Open a new .c file in KEIL project.

2. Specify the file destination on SRAM.

283-1

283-2

3. Set up Linker.

283-3

4. Write the delay function.

 

Since it takes 5 CPU clock cycles to execute one for loop, user can use the following function code to achieve 2 us delay.

 

(1) Execute one for loop: 5 CPU clock cycles

(2) Execute one __NOP(): 1 CPU clock cycle

(3) 64 CPU Clock Cycles = 8 ( 5(for loop) + 3 * 1( __NOP() ) )

 

void Delay_Test_Function(void)

{

    for(i = 0; i < 8 ; i++)     /* Delay for 2 micro seconds. */

    {

        __NOP();

        __NOP();

        __NOP();

    }

}

 

5. Test

User can take the following function code to test the delay timing. It is recommended to use an oscilloscope to measure the I/O toggle delay time. However, the command executing time (PA0 = 0) needs to be added to the delay time.

 

Execute one PA = 0: 11 CPU clock cycles

 

Hence, it will take 64+11 clock cycles. It means that it will take the time:
(64+11) * 31.25 ns = 2343.75 ns.

 

void Delay_Test_Function(void)

{

    uint32_t i, DelayCNTofCPUClock = 8;

    PA0 = 1;

    for(i = 0; i < DelayCNTofCPUClock ; i++)     /* Delay for 2 micro seconds. */

    {

        __NOP();

        __NOP();

        __NOP();

    }

    PA0 = 0;

}

283-4

Products: Microcontrollers ,8bit 8051 MCUs ,Arm Cortex-M0 MCUs ,Arm Cortex-M23 MCUs ,Arm Cortex-M4 MCUs
Applications:
Function: