Arduino Programming: Redirect Statements

Normally the redirect statement in the Arduino Programming is used to branch your code to certain location purposely or bypassing the standard loop condition.

 

break statement

When you want to bypass and exit from the normal loop condition of a do, for or while loop, the break statement need to be used. Below is an example of the break statement.

for (varBrightness = 0; varBrightness < 255; varBrightness ++)
{
    digitalWrite(PWMpin, varBrightness);
    sens = analogRead(sensorPin);
    if (sens > threshold){       // bail out on sensor detect
       digitalWrite(PWMpin, 0);  // switch it off and exit the for loop
       break;
    }
    delay(50);
}

 

continue statement

The continue statement is used to skip the remaining code in the do, for or while loop and continues by checking the conditional expression of the standard loop.

for (varBrightness = 0; varBrightness < 255; varBrightness ++)
{
    if (varBrightness > 100 && varBrightness < 150){
       // the led will have a big jump fade up from 100 to 150
        continue;
    }

    digitalWrite(PWMpin, varBrightness);
    delay(50);
}

 

return statement

When a code reach the return statement it will exit from the current function or procedure immediately. It can return nothing on a void return function as below example.

void functionABC(){

     // your codes go here
     return;

     // any code after the return statement
     // will never be executed.
}

Below is another example function that returns value. HIGH and LOW in the follow example is a Arduino build in constant.

int checkSensor(){
    if (analogRead(0) > 300) {
        return HIGH;
    else{
        return LOW;
    }
}

 

goto statement

Redirect program code to a labeled location in the existing Arduino sketch by using the goto statement. goto is always ask to be avoid in most of the C/C++ gurus, but sometimes it is quite useful to simplify your Arduino sketch. Here is the example to demonstrate how to use the goto statement.

for(byte r = 0; r < 255; r++){
    for(byte g = 255; g > -1; g--){
        for(byte b = 0; b < 255; b++){
            if (analogRead(0) > 250){goto somewhere;}
            // more statements ...
        }
    }
}

// more statements ...

somewhere:

 

< BACK

This entry was posted in Software and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>