Coding Basics 201

Start 

This section will go over some additional computer programming topics.

Loops 

Loops are used when you want to do the same instruction or a set of instructions multiple times. There are two main types of loops a for loop and a while loop.

For

A for loop repeats for a set number of times. Its basic design looks like this.

Download file Copy to clipboard
1
2
3
for (initial condition; stopping condition; incrementing value) {
  // Code goes here
}

Let's say I have 10 leds that I want to turn on. They are pins 1 to 10. I could write this piece of code.

Download file Copy to clipboard
1
2
3
4
5
6
7
8
9
10
digitalWrite(1, HIGH);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
digitalWrite(10, HIGH);

Or I could use a for loop.

Download file Copy to clipboard
1
2
3
for(int i = 1; i <= 10; i++) {
  digitalWrite(i, HIGH);
}

Lets go over this code line by line:

int i = 1

We need a counting variable to keep track of where we are in our loop. That's what the integer i is doing.

i <= 10

We only want the loop to run if i is less than or equal to 10. We don't want to try and turn an led on pin 11 on.

i++

i starts at 1 and at the end of each loop i++ runs and add one to i.

digitalWrite(i, HIGH);

There is no led pin i. The variable i changes it's value with each run of the loop. Starting at 1 then 2 and all the way to 10.

While

A while loop runs while some condition is true. You use it when you're not sure how many loops you'll need. The basic design looks like this.

Download file Copy to clipboard
1
2
3
while (condition) {
  // Code goes here
}

Let's say you want to take a reading with a sensor. You send it a signal to take a reading and must wait for its answer but the time you have to wait is different with each measurement. You'd want to use a while loop.

Download file Copy to clipboard
1
2
3
4
5
6
7
digitalWrite(sensorSignal, HIGH);

while (analogRead(sensorReading) == 0) {
  // Do nothing
}

reading = analogRead(sensorReading);

Our mystery sensor reports back 0 when it's taking a reading. The code above keeps running that empty while loop while the sensor is doing it's job. Once it is finished it reports back a non-zero number. That makes the condition of analogRead(sensorReading) == 0 false, and the loop is over.

Arduino void loop()

In every Arduino sketch there is something called the void loop() . So is it a while loop or for loop? It's a different kind of loop. It will repeat as long as the Arduino is powered on, it never stops.