Sunday, 21 August 2016

While Loops - Arduino

 While loops

Allows more flexibility than a for loop.
A while loop will loop continuously, and infinitely, until the expression 
inside the parenthesis, () becomes false. 
 

Syntax

while (condition) {
  // statement(s)
}
 
 -----------------------------------------------------------------

Example Code

var = 0;
while (var < 200) {
  // do something repetitive 200 times
  var++;
}
 -----------------------------------------------------------------------
 

 
//This code will print the numbers 1 to 10
//print a space
//then loop

int j; // counter
int delayTime=100;

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  j=1;
  while (j<=10){
    Serial.println(j);
    delay(delayTime);
    j=j+1;
  }
  Serial.println(); // prints a gap
    
}
 
 ----------------------------------------------------
 example 2
while the voltage at the pot is less than 1023 (5V)
the LED is off.
Any voltage above this turns the LED on.
 


int j; // counter
int potVal; // 0 to 1023(5V).. value of pot
int delayTime=100;
int potPin=A0;
int redPin=7;


void setup()
{
  Serial.begin(9600);
  pinMode(potPin,INPUT);
  pinMode(redPin,OUTPUT);
 
}

void loop()
{
  potVal=analogRead(potPin);
  Serial.println(potVal);
  delay(delayTime);
 
  while (potVal>1000) {
    digitalWrite(redPin,HIGH);
    potVal=analogRead(potPin);
    Serial.println(potVal);
    delay(delayTime);
    
    
    
  }
 digitalWrite(redPin,LOW);
    
}

 
 Links
 
 ---------------------------------
------------------------------------- 

No comments:

Post a Comment