How to Generate Accurate Delays with New Tang Microcontrollers

Recently, I’ve been working with New Tang microcontrollers, so I’m documenting this part of the content.

Previous related articles

Hey, do you know how to achieve accurate delays with the 51 microcontroller?

If the user wants to generate precise delay times, it is recommended to use the __nop() function in combination. The __nop() function can produce a precise delay of one CPU clock cycle. However, due to the flash speed being lower than the CPU frequency, there are cache optimization techniques within the CPU, and the compiler will also automatically optimize the program, causing the time generated by the __nop() function to differ from the expected time. Therefore, it is advised to place the program code in SRAM to avoid unexpected delay issues caused by optimization.

For example, to generate a 2 us delay:

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

(2) 2 us delay = 2000 ns / 31.25 ns = 64 CPU clock cycles

1. Add a new .c file to the KEIL project

2. Specify the file location to SRAM

How to Generate Accurate Delays with New Tang Microcontrollers

How to Generate Accurate Delays with New Tang Microcontrollers

3. Set the Linker

How to Generate Accurate Delays with New Tang Microcontrollers

4. Write the delay program code

Since executing a single for loop takes 5 CPU clock cycles, the following method can be used to achieve a 2 us delay:

(1) Executing one for loop takes 5 CPU clock cycles

(2) Executing one __NOP() instruction takes 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 2 microseconds. * /
    {
        __NOP();
        __NOP();
        __NOP();
    }
}

5. Testing

Users can use the following program code to test the delay time, measuring the I/O toggle time with an oscilloscope to observe whether the delay function is accurate. Since the CPU needs to issue instructions to change the I/O state, the observed time must include the instruction time for state change (PA0 = 0).

Executing once PA = 0 takes 11 CPU instruction cycles, which means the I/O will remain in state for (64+11) * 31.25 ns = 2343.75 ns before changing state.

void Delay_Test_Function(void)
{
    uint32_t i, DelayCNTofCPUClock = 8;
    PA0 = 1;
    for(i = 0; i < DelayCNTofCPUClock; i++) / * Delay 2 microseconds. * /
    {
        __NOP();
        __NOP();
        __NOP();
    }
    PA0 = 0;
}

How to Generate Accurate Delays with New Tang Microcontrollers

Recommended Reading: Collection | Summary of Linux Articles Collection | Programming Life Collection | C Language My Knowledge Sharing Circle Follow the public account, reply “1024” to get the link to learning materials.Thank you for liking, following, sharing, and viewing. I will remember every encouragement you give!

How to Generate Accurate Delays with New Tang Microcontrollers

Leave a Comment