Hacker News new | ask | show | jobs
by MuffinFlavored 2265 days ago
Is there a better way to sleep/delay other than what basically seems like 100% CPU usage in a subtraction loop?
5 comments

On ARM Cortex M4 devices like the STM32 there is a simple timer called SysTick used for exactly this type of purpose! You only need to set up a clock divider and you start it up- now you have a regular interrupt at whatever frequency you need!
Nearly every microcontroller has at least one free-running timer that can be used to either reset or wake the processor, if you care about power.
The other approach to delay's (keep in mind, that there is no other process to yield the CPU too) is to use a timer (a peripheral of the micro controller).

This would take a fair bit more code to configure the timer, and setup an interrupt to handle the timer.

How do multiple processes usually 'share' a timer?
Microcontrollers (assuming no RTOS in use), typically don't have multiple processes, they have the main thread of execution (which in the article is the entire program) and have interrupt routines that a run in response to an external event (in this case, the timer has expired).

Using the interrupt driven approach, can led to better performance both in CPU time (async communication with slower periphials etc) and battery life (sleep states).

by either having the timer fire regularly and have run code to figure out what needs to be done now, or having code to set it to the time to the next needed interrupt
Jokes aside one of the easiest ways (for developer) to do so is just run JS on it since it have sleepy event loop built in. Works wonderfully with Espruino. So sad that it is not as widespread as should be.
I think you missed the point, which in this case would be "how does that js engine does it". If it does it the same way then it doesn't answer him at all.
if you have an OS, yes
You don't need an OS to do more advanced or efficient sleeping. You could have one of the timer peripherals generate an interrupt on a regular basis, and then put the chip in a lower power sleep mode in between interrupts.
Isn't that what an OS would do, essentially?
Yes, probably! But you can do it yourself without one.

Here is an example in C using libopencm3, that uses timers to trigger an interrupt used to flash LEDs https://github.com/libopencm3/libopencm3-examples/tree/maste...

that is basically a mini-os :)
You can set up a wakeup interrupt using a timer by moving a few values into a few registers. It doesn't require anything like an OS. Even tiny 8-bit microcontrollers can do this.
Sure, but putting the chip to sleep is one instruction, and programming the timer interval is only about a dozen instructions. So you don't really need an OS in this context.
There is a blurry line on the edges of "library" and "OS"; most people would put this particular example on the "library" side.