Program Flow Control in C

The microcontroller or microprocessor must be supplied with a well planned program to be useful. It must interact with the user realtime. A microcontroller can check the environmental changes thousands of times per second with optional devices attached to it. Syntax for these operations is presented here.

if if-else

if (condition)
{
     body
}
else
{
     body
}

If the condition is met it will execute the body under “if” and if the condition is not met it will execute the body under “else”.

Example

if (PORTA.B0 == 0)
PORTA.B3 = 0;
else
PORTA.B3 = 1;

“==” is a logical expression that checks whether the right operand equals to the left operand and gives the result true or false. This logical expression does not equal to normal “=” symbol which we use to set some value to a variable.

If portA RA0 pin is logic low, it will execute the next statement PORTA.B3 = 0; causing RA3 pin to be logic low.

If portA RA0 pin is logic high, it will skip the next statement PORTA.B3 = 0; and will execute the statement PORTA.B3 = 1; causing RA3 pin to be logic high.

while loop

while(condition)
{
Body…
}

This will keep executing the body whenever the condition is met.

Example

while(PORTA.B3 == 0)
{
    PORTA.B3 = 0;
    PORTA.B3 = 1;
}

Result is there will be square wave present at RA3 since RA3 is continuously becomes logic low and high.

Also remember “while(1)” makes an infinite loop.

do – while Loop

do
{
Body…
}
while (condition);

do – while loop is same as a while loop but this executes the body at least once even if the condition is not met.

break

Sometimes you need to break your loop.

use keyword “break”

See mikro C help for continue statement.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: