Skip to content

Commit 1e616ee

Browse files
fix(newlib): Fixed an issue where usleep() could consume more CPU cycles
The following changes are made in this commit: 1. This commit updates the implementation of usleep() to now always yield CPU time if undergoing a multi-tick sleep. This reduces the accuracy of usleep() but in turn allows the scheduler to schedule different tasks. 2. The commit also updates the MCPWM unit test which fails due to the change in the behavior of usleep(). Closes: #15132
1 parent bdf0cca commit 1e616ee

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

components/driver/test_apps/legacy_mcpwm_driver/main/test_legacy_mcpwm.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ static uint32_t pcnt_get_pulse_number(pcnt_unit_handle_t pwm_pcnt_unit, int capt
172172
int count_value = 0;
173173
TEST_ESP_OK(pcnt_unit_clear_count(pwm_pcnt_unit));
174174
TEST_ESP_OK(pcnt_unit_start(pwm_pcnt_unit));
175-
usleep(capture_window_ms * 1000);
175+
vTaskDelay(pdMS_TO_TICKS(capture_window_ms));
176176
TEST_ESP_OK(pcnt_unit_stop(pwm_pcnt_unit));
177177
TEST_ESP_OK(pcnt_unit_get_count(pwm_pcnt_unit, &count_value));
178178
printf("count value: %d\r\n", count_value);

components/newlib/src/time.c

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -219,12 +219,13 @@ int usleep(useconds_t us)
219219
do {
220220
vTaskDelay((((target_us - now_us) + us_per_tick - 1) / us_per_tick));
221221
now_us = esp_time_impl_get_time();
222-
/* If the time left until the target is less than 1 tick, then we use ROM delay to fill the gap */
223-
uint64_t time_left = target_us - now_us;
224-
if (time_left != 0 && time_left < us_per_tick) {
225-
esp_rom_delay_us(time_left);
226-
break;
227-
}
222+
/* It is possible that the time left until the target time is less
223+
* than a tick period. However, we let usleep() to sleep for an
224+
* entire tick period. This, could result in usleep() sleeping for
225+
* a longer time than the requested time but that does not violate
226+
* the spec of usleep(). Additionally, it allows FreeRTOS to schedule
227+
* other tasks while the current task is sleeping.
228+
*/
228229
} while (now_us < target_us);
229230
}
230231
return 0;

0 commit comments

Comments
 (0)