Link

Looping with for

Table of contents

  1. Where are loops useful
  2. An Example: Fading an LED
  3. An Example: Sampling from a Sensor
  4. Build your skills - Independent Exercises

Within the Wiring language, we’ve already encountered some of syntax that allows us to do more than just control power to components or read from components. These include if statements that allow us to make decisions about what code to execute based on the condition of a variable or the status of a sensor or input. In this section, we’re going to look at loops - another element of the Wiring language that’s incredibly useful.

Think back to that blinking LED. We could make it blink on and off 3 times and then stop if a button is pressed by writing some code like this:

if( digitalRead( buttonPin)  == LOW ){

	digitalWrite( ledPin, HIGH );
	delay( 1000 );
	digitalWrite( ledPin, LOW );
	delay( 1000 );

	digitalWrite( ledPin, HIGH );
	delay( 1000 );
	digitalWrite( ledPin, LOW );
	delay( 1000 );

	digitalWrite( ledPin, HIGH );
	delay( 1000 );
	digitalWrite( ledPin, LOW );
	delay( 1000 );

}

Yes, this absolutely works and its one way you could make this happen, but its far from ideal. Why? Because we’ve introduced a lot of redundancy into our code. We’re using the same blocks of code repeatedly. If ever we want to change how the blinking behaves (to make it faster or slower), we’ll need to edit in lots of different places. Because we have to make lots of edits, we also risk introducing errors - by forgetting to change one of the delays for example. Additionally, it’s just verbose. By having to make each action explicit and repeating it over and over, we’re adding a lot of code to our project and that makes it harder to read and figure out what’s really happening.

Thankfully, most coding languages have a trick to help simplify the process of making a set of actions repeatedly occur. This is known as a loop. The most common type of loop is a for loop and this is what we’ll look at in this section.

With a for loop, we can transform this long set of statement into something much more sleek and efficient, like so:

if( digitalRead( buttonPin)  == LOW ){

	for( int i = 0; i < 3; i++ )
	{
		digitalWrite( ledPin, HIGH );
		delay( 1000 );
		digitalWrite( ledPin, LOW );
		delay( 1000 );
	}
}

This is a heck of a lot neater. So what’s happening here. Well the for loop needs three things to operate. This is what happens on the first line:

for( int i = 0; i < 3; i++ )

could be read as:

for( [set up a starting condition]; [condition to check at the end of each loop]; [what happens when each iteration of the loop completes] )

Basically, the loop needs to know three things:

  1. We’ve got to create a variable it’ll use to store the status of the loop e.g. int i = 0; int i = 20; int i = 1. Your starting condition can be whatever you like - you just need to define it.

  2. We’ve got to tell the loop how to check to see if it should stop running. In the example above, it’s going to stop when i gets to 3 i.e. i < 3. You can adjust this condition to be whatever you like but keep in mind how this comparison is going to effect the behavior of the loop. You could use i < 5 and it’ll loop 5 times. You could use i < 100 and it’ll loop 100 times. You can even make this loop dependent on the value of another variable i < numTimes - providing you define that variable elsewhere in your code.

  3. We have to tell the loop what to do when each iteration of the loop finishes. Normally, this will be adding 1 to the loop counter (e.g. i++) or subtracting 1 from our loop counter (i--). This bit will occur when the loop executes the code between the curly brackets {...} and reaches the } containing the loops actions. In this case it’s going to add one to our loop counter, then it backtracks, checks this variable against the completion condition and sees if it should proceed with another iteration or stop the loop entirely.

Of course there’s lots of ways to achieve the same behavior with a loop

for( int i = 3; i > 0; i-- ){ ... }

for( int i = 3; i < 6; i++ ){ ... }

for( int i = 0; i <= 2; i=i++ ){ ... }

for( int i = 0; i <= 10; i=i+5 ){ ... }

All of these loop configurations will execute 3 times. That means you’ve lots of choice in how you set them up

Where are loops useful

Loops are useful in almost every code project. They can be used to:

  • repeat an action like blinking an LED
  • to sample from a sensor (i.e. take rapid repeated readings to average out the values to protect against noisy/bumpy values)
  • to create behaviors like fading up/down an LED or slowly moving a motor a series of steps

An Example: Fading an LED

In the example below, a button push will illuminate the LED and then after the button is released it will fade back down. We’ll look just at the contents of the loop.

To fade it back down, we’re going to create a loop to analogWrite from 255 (full brightness) to 0 (off), with a short delay in between each iteration. This will look like this:

if( buttonState == LOW )
{
  // turn the LED On
  digitalWrite( ledPin, HIGH);
}else{

	for( int j = 255; j > 0; j—- )
	{
		analogWrite( ledPin, j );
		delay( 50 );
	}
}

An Example: Sampling from a Sensor

In this example, we’ll quickly gather 5 samples from a sensor (perhaps a bend sensor, or a gas sensor). We’ll sample 5 times ever 25 milliseconds and then work out the average:

int sensorReading = 0;
int numberOfSamples = 5;
for( int x = 0; x < n numberOfSamples; i++ )
{
	// add each sample into the sensor reading
	sensorReading += analogRead( sensorPin );
	delay( 25 );
}
// finally get the average
sensorReading = sensorReading / numberOfSamples;

Build your skills - Independent Exercises

Exercise 1

Modify the LED example to quickly fade up the LED when the button is pressed but slowly fade the LED down when it is released.


Exercise 2

Take a look at the servo example provided . Change the behavior so that the servo no longer ‘jumps’ to the new value but slowly moves/animates towards the new position over a series of steps.


Table of contents