Skip to content

High precision microsecond delay instructions*

1. Precise delay precautions*

Because the commonly used delay interface gx_udelay has a fixed time, the error decreases with the increase of delay time. When doing precise delay, the error will be large. This paper provides high-precision microsecond delay. The following describes how to use high-precision microsecond delay.

2. Precise delay instruction*

2.1 Delay interface*

  • Obtain the delay factor interface according to mcu frequency: gx_udelay_fine_config
  • Incoming delay time and delay factor delay interface: gx_udelay_fine

    lvp/lvp_tws/include/driver/gx_delay.h
    /**
    * @brief Precise us delay configuration
    * @param cpu_fre CPU frequency (Hz)
    * @return configuration
    * - -1        Configuration failure
    * - Others    Get the exact delay factor
    */
    static inline unsigned int gx_udelay_fine_config(unsigned int cpu_fre)
    
    /**
    * @brief Accurate us delay
    * @param us    Delay time
    *        coeff gx_udelay_fine_config() Coefficient returned
    */
    static inline void gx_udelay_fine(unsigned int us, unsigned int coeff)
    

2.2 Use procedure*

  • Adjust cpu frequency

    LvpDynamiciallyAdjustCpuFrequency(CPU_FREQUENCE_24M);       // Set the cpu frequency to higher. If the default cpu frequency is 24 MB or greater, you do not need to adjust the CPU frequency
    
  • Acquisition delay factor

    int coeff = gx_udelay_fine_config(gx_clock_get_module_frequence(CLOCK_MODULE_SCPU));    // The delay factor is obtained by the cpu frequency
    
  • Close interrupt

    unsigned int irq = gx_lock_irq_save();          // Save interrupts and close interrupts. Interrupts affect latency
    
  • Delay time

    gx_udelay_fine(1, coeff);          // Delay 1us, incoming delay time and delay coefficient
    
  • Resume interrupt

    gx_unlock_irq_restore(irq);                     // Open the interrupt when the operation is complete
    
  • Recovery frequency

    LvpDynamiciallyAdjustCpuFrequency(CPU_FREQUENCE_DEFAULT);   // Restore the default cpu frequency and adjust the previous cpu frequency
    

2.3 Delay 1sec at different cpu frequencies*

  • Delay 1us using the precise delay interface

    CPU frequency
    (LvpDynamiciallyAdjustCpuFrequency)
    Delay 1us
    CPU_FREQUENCE_50M 1.2
    CPU_FREQUENCE_24M 1.3
    CPU_FREQUENCE_16M 1.3
    CPU_FREQUENCE_12M 1.8

3. Precise delay example*

This section uses GPIO simulation infrared as an example. For details, seeGPIO Analog Infrared - Example