Control Statements and Loops in Arduino

 What are the Control Structure and Control Statements in Arduino?

  • The control structure describes how the program's codes are organised to allow it to perform actions in response to certain conditions. 
  • For example, if you want your programme to turn on an LED only when a sensor registers 60°C, you'll need to structure your code in such a way that it can accurately execute such a command.
  • Program control structuring, often known as "control structure," is a way of enforcing such operations in a programme.
  • Control statements are elements (functions) in a source code that control the flow of program execution, wait, jump, repeat, etc.

Control statements in arduino are as....

If statement:
  • The conditional statement, known as the if (), is the base for all programming languages.
  • If the condition in the code is true, the job or function that corresponds is executed. If a program's condition is true, it returns one value. If the condition is false, it also returns another value.
  • The if () statement checks for a condition before executing a statement or a series of statements.
  • Let's use a flow chart to help us understand the topic.
If statement in arduino

  • It shows the process of executing a statement in detail. If the condition is False, the if () expression is exited. The function is run if the condition is true.
  • The if () condition is expressed as follows:
if ( condition)  
{  
// include statements
// if the condition is true
// then performs the function.   

Examples:

int a = 6; // initialization of values to variables a and b  
int b = 4;  
void setup()  
{  
Serial.begin(9600);   
}  
void loop()  
{  
  if (a > b )  
  {  
    Serial.println( " a is greater than b ");   
  }  
  if (b > a )  
  {  
    Serial.println( " b is greater than a ");   
  }  
}  

Expected Output: 
a is greater than b

Example 2:

const int LED1 = 2;  
const int LED2 = 13;  
int x = 80 ;  
void setup ( )  
{   
Serial.begin( 9600 );  
pinMode ( LED1, OUTPUT);  
pinMode ( LED2, OUTPUT);  
}  
void loop ( )  
{   
if ( x > 100 )  
{  
digitalWrite(LED1, HIGH);  
delay (500);  
}  
if ( x < 100 )  
{  
digitalWrite(LED2, HIGH);  
delay (500);  
}  
}  

The example is of two LEDs.

Post a Comment

Previous Post Next Post