From bcdb428aa1f123b279a0c222724a93a7cb9bfe7e Mon Sep 17 00:00:00 2001 From: Konstantin Kondrashov Date: Fri, 18 Jul 2025 14:19:24 +0300 Subject: [PATCH] fix(ulp_riscv): Fix a delay function to handle small delays correctly Fixed ulp_riscv_delay_cycles function Closes https://github.com/espressif/esp-idf/issues/16891 --- .../ulp_riscv/ulp_core/include/ulp_riscv_utils.h | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/components/ulp/ulp_riscv/ulp_core/include/ulp_riscv_utils.h b/components/ulp/ulp_riscv/ulp_core/include/ulp_riscv_utils.h index acc47a28bf..df41829884 100644 --- a/components/ulp/ulp_riscv/ulp_core/include/ulp_riscv_utils.h +++ b/components/ulp/ulp_riscv/ulp_core/include/ulp_riscv_utils.h @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD + * SPDX-FileCopyrightText: 2015-2025 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ @@ -92,15 +92,19 @@ void ulp_riscv_timer_resume(void); /** * @brief Makes the co-processor busy wait for a certain number of cycles * + * @note This function is not accurate for delays shorter than 20 cycles, + * as the function's own overhead may exceed the requested delay. + * * @param cycles Number of cycles to busy wait */ void static inline ulp_riscv_delay_cycles(uint32_t cycles) { - uint32_t start = ULP_RISCV_GET_CCOUNT(); - /* Off with an estimate of cycles in this function to improve accuracy */ - uint32_t end = start + cycles - 20; - - while (ULP_RISCV_GET_CCOUNT() < end) { + if (cycles <= 20) { // the estimate of cycles for this function + return; + } + /* Off with the estimate of cycles to improve accuracy */ + uint32_t end = ULP_RISCV_GET_CCOUNT() + cycles - 20; + while (ULP_RISCV_GET_CCOUNT() < end) { /* Wait */ } }