What is the purpose of the delay() function, and how can it affect performance?

 The delay() function is commonly used in embedded systems (e.g., Arduino, STM32 HAL, etc.) to pause program execution for a specified amount of time.




Purpose of delay()

  • Timing control: Wait for a fixed period (e.g., for sensor stabilization, LED blinking).

  • Debouncing: Simple method to avoid bouncing effects in mechanical buttons.

  • Synchronization: Temporarily pause until an external device or event is ready.

Example in Arduino:

cpp

digitalWrite(LED_BUILTIN, HIGH); delay(1000); // wait 1 second digitalWrite(LED_BUILTIN, LOW);

Impact on Performance

1. Blocking Behavior

  • delay() is a blocking function.

  • The CPU does nothing useful during the delay—it simply waits.

  • It halts all other processing (unless using interrupts).

2. Wastes CPU Cycles

  • In real-time applications, blocking delays can cause:

    • Missed events

    • Poor responsiveness

    • Reduced system throughput

3. Not Scalable

  • Long delays make it hard to maintain precise timing for multiple tasks.

  • Complex systems require non-blocking alternatives (e.g., timers or RTOS-based scheduling).


Best Practices

  • Use delay() only for simple applications or initial prototyping.

  • For multitasking or real-time control:

    • Use non-blocking delays (e.g., millis() or timer counters).

    • Use hardware timers or RTOS tasks with vTaskDelay() (in FreeRTOS).


 Non-Blocking Example (Arduino-style)

cpp

unsigned long previousMillis = 0; const long interval = 1000; void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; toggleLED(); } }

 Summary

  • delay() pauses execution but blocks the CPU.

  • It’s useful for simple timing but hurts performance in multitasking or real-time systems.

  • Prefer non-blocking timing methods for scalable, responsive designs.

评论

此博客中的热门博文

Detailed Explanation of STM32 HAL Library Clock System

How To Connect Stm32 To PC?

How to add a GPS sensor to ESP32 for Wokwi?