Let us see some codes on the applications of loop command with reference to the following diagram.
Program codes to check that the button K1 of the above circuit has been closed and then turn-non (ignite) L (built-in LED of UNO).
1. Using Flow Chart
2. Using goto statement
void setup()
{
pinMode(13, OUTPUT); //IO line of DPin-13 will work as output line
pinMode(2, INPUT_PULLUP); //IO line of DPin-2 will work as input with internal pull-up
digitalWrite(13, LOW); //initially L is OFF
L1: bool statusK1 = digitalRead(2); //reading ope/close status of K1
if (statusK1 == LOW) //K1 is closed
{
digitalWrite(13, HIGH); //ignite L
while(1); //wait here for ever; there is no halt instruction for AVR?
}
else
{
goto L1; //K1 is not closed
}
}
void loop()
{
}
3. Using do-while Structure
void setup()
{
pinMode(13, OUTPUT); //IO line of DPin-13 will work as output line
pinMode(2, INPUT_PULLUP); //IO line of DPin-2 will work as input with internal pull-up
digitalWrite(13, LOW); //initially L is OFF
do
{
;
}
while(digitalRead(2)!=LOW);
digitalWrite(13, HIGH); //ignite L
}
void loop()
{
}
4. Using while-do Structure
void setup()
{
pinMode(13, OUTPUT); //IO line of DPin-13 will work as output line
pinMode(2, INPUT_PULLUP); //IO line of DPin-2 will work as input with internal pull-up
digitalWrite(13, LOW); //initially L is OFF
while(digitalRead(2)!=LOW)
;
digitalWrite(13, HIGH); //ignite L
}
void loop()
{
}
5. Using for() Loop
void setup()
{
pinMode(13, OUTPUT); //IO line of DPin-13 will work as output line
pinMode(2, INPUT_PULLUP); //IO line of DPin-2 will work as input with internal pull-up
digitalWrite(13, LOW); //initially L is OFF
for (; digitalRead(2)==HIGH; )
{
;
}
digitalWrite(13, HIGH); //ignite L
}
void loop()
{
}