No matter what type programming languages you are using, e.g. C/C++, Visual Basic, PHP and etc, there are always some logic paths you want your software to decide how it should react based on certain criteria. This is where control structure needed.
if and if…else… statements
if and if…else… are the most straight forward condition checking control statement. The syntax of the if statement should be as below:
if (myVar > 0) { // do something here if myVar is greater than 0 }
Sometime you may need an if…else… control statement for more than 1 condition.
if (myVar < 10) { // do Thing A } else if (myVar >= 100) { // do Thing B } else { // do Thing C }
for statement
Another useful control structure is the for loop. It is used to repeat a block of statements between its curly braces. An increment/decrement counter is usually used to increment/decrement and terminate the loop. Normally the for statement is used in combination with arrays to operate on collections of data/pins in Arduino.
for (int iBright=0; iBright <= 255; iBright++){ analogWrite(PWMpin, iBright); delay(50); }
The above for loop Arduino programming example fades a LED up slowly from off to full brightness.
Switch…case… statement
Another control statement for Arduino programming that quite similar to if…else… is switch…case… statement. Like if statements, switch…case… controls the flow of programs by allowing programmers to specify code that should be executed in various conditions. Below is the syntax example go the Arduino programming switch…case… statement.
switch (MyVar) { case 1: //do something when MyVar equals 1 break; case 2: //do something when MyVar equals 2 break; default: // if nothing else matches, do the default // default is optional }
You can see the above switch…case… Arduino codes are very similar to the if…else… statement.
while and do…while… statements
while and do…while… control statements are used to loop a block of code until reach certain conditions. Here is a while loop statement example.
myVar = 0; while(var < 50){ // do something repetitive 50 times myVar=myVar + 1; }
Below is the example of the do…while… loop.
do { delay(50); // wait for sensors to stabilize sensorVal = readSensors(); // check the sensors } while (sensorVal < 100);
The main different between while loop and do…while… loop is while loop check the condition before executes the action, but do…while… loop is executing the action at least once before exiting the loop by meeting the exit condition.
< BACK
Pingback: Arduino Programming: Redirect Statements | Arduino Tutorials