Thursday 21 July 2016

For Loops - Arduino

 The "for loop".
 
This repeats a block of statements.

Syntax

for (initialization; condition; increment) {
  
}
 eg
for (int x = 0 ; x<100; x++) {
  
} 
The initialization only happens once.
The condition is tested each time we loop. 
If it's true,the increment is executed.
Then the condition is tested again. 
When the condition becomes false, the loop ends.
 
  -----------------------------------------------------------------------------------
You will need a red and yellow LED.
Don't use the blue or green.
330 ohm resistors x2
 
we are going to blink the yellow 3 times & the red 3 times.
 

The anode of the LEDs connects to the resistors.

Here is a very long winded way to write this code.
 
----------------------------------------------------------------------

// variables
  int yellowPin=6;
  int redPin=9;
  int yellowTime=100;
  int redTime=100;



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

void loop()
{
  //we are going to blink the yellow 3 times
  digitalWrite(yellowPin, HIGH);
  delay(yellowTime);
   digitalWrite(yellowPin, LOW);
  delay(yellowTime);
 
  digitalWrite(yellowPin, HIGH);
  delay(yellowTime);
   digitalWrite(yellowPin, LOW);
  delay(yellowTime);
 
  digitalWrite(yellowPin, HIGH);
  delay(yellowTime);
   digitalWrite(yellowPin, LOW);
  delay(yellowTime);
 
  //we are going to blink the red LED 3 times
  digitalWrite(redPin, HIGH);
  delay(redTime);
  digitalWrite(redPin, LOW);
  delay(redTime);
 
  digitalWrite(redPin, HIGH);
  delay(redTime);
  digitalWrite(redPin, LOW);
  delay(redTime);
 
  digitalWrite(redPin, HIGH);
  delay(redTime);
  digitalWrite(redPin, LOW);
  delay(redTime);
}
 ---------------------------------------------
 
code 2 - the better way using loops
 

we are going to blink the yellow 3 times & the red 5 times.
 
 
--------------------------------
 // variables
  int yellowPin=6;
  int redPin=9;
  int yellowTime=100;
  int redTime=100;

  int yellowBlink=3; // these are for the for loop.
  int redBlink=5;
  int j;


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

void loop()
{
  for(j=1;j<=yellowBlink;j=j+1)
    //we are going to blink the yellow 3 times
  {
  digitalWrite(yellowPin, HIGH);
  delay(yellowTime);
   digitalWrite(yellowPin, LOW);
  delay(yellowTime);
  }
 for(j=1;j<=redBlink;j=j+1)
    //we are going to blink the red LED 5 times
  {
  digitalWrite(redPin, HIGH);
  delay(redTime);
  digitalWrite(redPin, LOW);
  delay(redTime);
  }
 
}
 
-------------------------------------
Thanks to Paul McWhorter for his excellent tutorials.
Much of the info is from tut 15.
 

 ---------------------------------
-------------------------------------

No comments:

Post a Comment