user6161
user6161

Reputation: 289

infinite While loop without statement

What it does mean? I saw below part of a code in embedded c program.I know this is a infinite loop, but for what purpose this part of a code is using in embedded c.

while(1)
{       
}

Thanks..

Upvotes: 3

Views: 3174

Answers (3)

Bruce
Bruce

Reputation: 2310

Some operating systems, like uC/OS, require an idle task to run when no other task is running. This would be at the lowest priority and would be preempted by a timer (scheduler) tick if it ever got a chance to run. The case you describe could be such a task.

Upvotes: 0

harper
harper

Reputation: 13690

This construct is used for two different purposes.

  1. When you detect an error condition or the termination of your task you have to put the micro-controller in a definit state. The while(1) { } construct stalls further execution until the (watchdog) reset restarts the micro-controller.
    As krambo mentions in his comment this can be used to attach a JTAG debugger to examine the state of the micro-controller, variables, registers, and so on.
  2. You can implement all the logic in interrupt handler. The main function performs the initialization and goes sleeping. While the main function can "sleep" the CPU can't. It just loops forever. Some micro-controller supports low-energy modes. This would be an alternative.

Upvotes: 10

Lundin
Lundin

Reputation: 214475

All embedded systems need an endless loop, because they must continue to execute for as long as the power is on. It doesn't make any sense for an embedded program to just execute and then return, as that would leave the processor dead and idle. This is likely the sole purpose of that loop.

I would guess your code comes from a bare metal microcontroller application, so you can safely disregard all PC programmer comments about sleeping and multi-threading; for a microcontroller application it doesn't make any sense not to consume 100% of the CPU, since nobody else is using it but you.

If you sleep on an embedded system you put the actual microcontroller hardware to sleep, if it supports it. You do so to save power, not to save CPU cycles.

Upvotes: 2

Related Questions