How to delay() easily when you don't have delay()?

I wanted to have some delay between I2C read/write functions. Ended up using this. How good/bad is it and any pitfalls? float temperature = readTemperature(); printf("Temperature: %.2f °C\n", temperature); for(int i=0; i<29999; i++); //some delay float humidity = readHumidity(); printf("Humidity: %.2f %\n", humidity); printf("\n"); for(int i=0; i<29999; i++); //some more delay
Solution:
@Navadeep there are many disadvantages for using a for loop as you just did like, The actual delay duration can vary depending on the compiler optimization settings and the CPU speed. this means the delay might not be consistent across different systems or even different runs on the same system, The for loop delay is a busy-wait loop, meaning the CPU is doing nothing useful during this time but still consuming power. this can be inefficient, especially in battery-powered or resource-constrained environments, ...
Jump to solution
5 Replies
ZacckOsiemo
ZacckOsiemo6mo ago
Only bad is it's blocking. Perhaps you have a timer you can use to wait? And let your uC do other things?
Solution
RED HAT
RED HAT6mo ago
@Navadeep there are many disadvantages for using a for loop as you just did like, The actual delay duration can vary depending on the compiler optimization settings and the CPU speed. this means the delay might not be consistent across different systems or even different runs on the same system, The for loop delay is a busy-wait loop, meaning the CPU is doing nothing useful during this time but still consuming power. this can be inefficient, especially in battery-powered or resource-constrained environments, External factors like interrupts or other high-priority tasks can affect the timing, making this method non-deterministic in real-time applications and This approach is not scalable for longer delays or more complex timing requirements.
RED HAT
RED HAT6mo ago
you can use alternatives like usleep or nanosleep in C (POSIX Systems), HAL_Delay in STM32 HAL Library, and std::this_thread::sleep_for in C++1 depending on which is more compatible with your program sorry for some of the blunders english is not my first language
Navadeep
NavadeepOP6mo ago
Thanks for the inputs. I have switched to a timer generated delay now from the 4MHz clock freq. It is included under the microchip code configurator generation.
No description
ZacckOsiemo
ZacckOsiemo6mo ago
We talked about this thew othet day, Decided to do a discussion and implementation in case you care to join or watch https://youtube.com/live/To5x1zY2t8w?feature=share
YouTube
Escaping Busy wait with Non Blocking Delays | STM32 | ARM | Embedded
In this part of the STM32 Series we use the Systick timer to run delays that way we can avoid busy-waiting or rather blocking delays in your system. We con...
Want results from more Discord servers?
Add your server