01 - What Is A For Loop - MMB - v009

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

What Is a For Loop?

1. Let’s review the basics of a for loop. A for loop executes a block of code for a set number of
iterations and is formatted as follows:

for ( control ; condition ; update )


{
// Do something here
}

control initializes a variable that will be used to iterate through the loop.

The for loop will continue iterating so long as condition is true.

Finally, update will update the control variable after every iteration by performing some type of
operation on it.

2. Here is a more specific example of a program with a for loop that iterates 10 times.

As the loop runs, the variable, x, is added to another variable during each iteration. Therefore, we
would expect y would have a value of:

y = 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

main()
{
int x, y; // Create two variables, x and y

y = 0; // Set y to be 0

for (x=0 ; x<10 ; x=x+1) // The FOR loop has 3 parts


{ // 1) Sets control variable, x=0
// 2) Loop as long as x<10
// 3) After every iteration add 1 to x

y = y + x; // In each iteration, add the value of x to y


}

while(1); // When for loop ends, stay here

3. First, this program creates two variables, x and y, and assigns the value 0 to variable y.

Copyright © 2012-2015 Page 1 of 25


Valparaiso University
4. Next comes the for loop.

control assigns the value 0 to variable x.

condition is then set to x<10. This means that the block of code inside of the for loop’s
brackets will evaluate over and over again (iterate) as long as x is less than 10. When x is not
longer less than 10, the for loop will stop and the program will move on to the next line of code.

update has been set to x=x+1. Therefore, if the condition is true, after the code inside of the
curly braces is executed, x will be incremented by 1 before the for loop tests the condition again.

5. After the for loop ends, the program comes to a while(1); infinite loop. Effectively, this
stops the program from executing any more instructions, but we will learn more about while
loops in an upcoming lesson.

6. Create a new CCS project by selecting New / CCS Project from the File menu.

Copyright © 2012-2015 Page 2 of 25


Valparaiso University
7. In the New CCS Project window, create a project called Loops_For.

Specify the MSP430FRxxx Family and the MSP430FR6989 microcontroller.

Also, make sure you select Empty Project (with main.c) from the
Project templates and examples pane before clicking Finish.

Copyright © 2012-2015 Page 3 of 25


Valparaiso University
8. Copy the program from above and paste it into the main.c file in the CCS Editor.

9. Save your program, but DO NOT Build it yet.

10. In the Project Explorer pane, right click on your project name and select Properties from
the pop-up menu.

Copyright © 2012-2015 Page 4 of 25


Valparaiso University
11. In the Properties window, select Optimization under Build / MSP430 Compiler.

12. On the right side of the window, for the Optimization level, select off.

Copyright © 2012-2015 Page 5 of 25


Valparaiso University
13. Your Properties window should now look like this.

We just told CCS that we did not want its help during the Build process. Like a lot of other
software programs out there, CCS has some wonderful features to help expert users, but for now,
we are going to stick with just the basics.

14. When you are ready, go ahead and click OK. This will take you back to the CCS Editor.

15. Build your project. If you have any errors, make sure you did not accidentally modify your
program.

16. After successfully Building your project, launch the CCS Debugger.

Copyright © 2012-2015 Page 6 of 25


Valparaiso University
17. As the Debugger is loading, you may see a window similar to this flash once or twice.

Launching the Debugger can take a few moments. Do not forget, in addition to opening the
Debugger portion of CCS, the process is automatically programming your microcontroller, too.

18. If you see an error message like this, it probably means that you forgot to plug-in your Launchpad
board. Connect your Launchpad board to your PC with the USB cable and click Retry.

Copyright © 2012-2015 Page 7 of 25


Valparaiso University
19. When it is ready, your screen should look something like this. You should see both x and y in the
Variables pane, although their values may be different.

20. If your Variables pane is not open, or if you accidentally close it, it is easy to fix. Just select
Variables from the View menu.

Copyright © 2012-2015 Page 8 of 25


Valparaiso University
21. Now, we are going to step through the program, line-by-line with the Step Into button.

In my example below, the highlighted light in the program window is at the top of the program.

22. Click the Step Into button. In my example below, the y=0 instruction is now highlighted.
Recall, the highlighted instruction is the next to be performed. There is also a small, blue arrow
at the highlighted line to indicate the same thing.

Copyright © 2012-2015 Page 9 of 25


Valparaiso University
23. After completing the instruction on line 5, the value stored in the variable y will be 0.

24. The next line to be performed will be to start the for loop. Click Step Into again.

Copyright © 2012-2015 Page 10 of 25


Valparaiso University
25. Two things just happened. First, the for loop began by storing the value of 0 in the variable x.

26. Second, because x=0 is less than 10, you have entered the for loop and are prepared to do the
next instruction.

Copyright © 2012-2015 Page 11 of 25


Valparaiso University
27. Click Step Into again. Again, two things just happened.

First, the value of x (presently 0) was added to the value of y (also 0). The result is stored in the
variable y.

Second, you reached the end of the first loop iteration. Therefore, the loop has returned to the top
of the for loop.

Copyright © 2012-2015 Page 12 of 25


Valparaiso University
28. Click Step Into again. Again, two things just happened. First, after returning to the top of a
for loop, the variable, x, is immediately updated with the condition, x=x+1. We see that this has
been updated in the Variable pane.

Second, the variable was tested by the condition, x<10. Since the condition is still true, the
program goes back into the loop to perform next.

Copyright © 2012-2015 Page 13 of 25


Valparaiso University
29. Click Step Into again. The variable y is now equal to 1 (0+1). Also, the next instruction to be
performed will update x and test if it is still less than 10.

30. Click Step Into again. x has been updated to 2. We are now ready to add the updated value of
x to the variable y.

Copyright © 2012-2015 Page 14 of 25


Valparaiso University
31. Click Step Into again. The variable y is now equal to 3 (1+2). Also, the next instruction to be
performed will update x and test if it is still less than 10.

32. Continue clicking Step Into until you reach this point in the program.

x is now 9, and we are getting ready to add it again to y.

Copyright © 2012-2015 Page 15 of 25


Valparaiso University
33. Click Step Into again. The variable y is now equal to 45 (36+9). Also, the next instruction to
be performed will update x and test if it is still less than 10.

Copyright © 2012-2015 Page 16 of 25


Valparaiso University
34. Click Step Into again. The variable x is now equal to 10. Therefore, it fails the condition.
CCS then shows you that the program execution will not continue back into the for loop, but
instead, moves on to the next instruction.

If you continue clicking Step Into at this time, the program will stay in the infinite loop.

35. If you want to do this again, or at any time start over, click the Soft Reset icon.

Copyright © 2012-2015 Page 17 of 25


Valparaiso University
36. When you are ready to continue, click the Terminate button to return to the CCS Editor.

37. Take a look at this program. It is another example of a for loop.

#include <msp430.h>

#define RED_ON 0x0001 // Enable and turn on the red LED


#define RED_OFF 0x0000 // Turn off the red LED
#define DEVELOPMENT 0x5A80 // Stop the watchdog timer
#define ENABLE_IO 0xFFFE // Used to ensure outputs are ready

main()
{
WDTCTL = DEVELOPMENT; // Stop the watchdog timer

PM5CTL0 = ENABLE_IO; // Enable to turn on LED


P1DIR = RED_ON; // Red LED pin will be an output
P1OUT = RED_OFF; // Start with red LED off

long x; // Creates variable

for(x=0; x<30000; x=x+1) // Loop 30,000 times


{
P1OUT = P1OUT ^ RED_ON; // Toggle LED when x<30,000
}

P1OUT = RED_OFF; // Ensures LED is off

while(1); // Stay here when complete


}

Copyright © 2012-2015 Page 18 of 25


Valparaiso University
38. The program begins by putting the microcontroller into a development mode:

WDTCTL = DEVELOPMENT;

39. The next three instructions prepare the microcontroller to use one of its pins to turn on and off the
red LED. We will learn more about these instructions a little bit later.

PM5CTL0 = ENABLE_IO; // Enable to turn on LED


P1DIR = RED_ON; // Red LED pin will be an output
P1OUT = RED_OFF; // Start with red LED off

40. Next, we create the variable x that will be used in the for loop.

long x; // Creates variable

Note, this only creates a variable called x. No value has been assigned to it yet. We say it has
not yet been initialized. Its value will be a random number that we cannot predict.

Anytime, you create a variable like this, you need to make sure you initialize it to a known value
before it is used. We will take care of that in the next line of the program.

41. We then come to the for loop. This loop will initialize x to be zero, and will increment x after
each loop iteration as long as x is less than 30000.

for(x=0; x<30000; x=x+1) // Loop 30,000 times


{
P1OUT = P1OUT ^ RED_ON; // Toggle LED as long as x<30,000
}

Copyright © 2012-2015 Page 19 of 25


Valparaiso University
42. Inside the for loop, we have an instruction that uses the XOR instruction (^) we learned about in
the previous section. This instruction will toggle the state of the red LED:

If the red LED was off, it will turn the light on.

If the red LED was on, it will turn the light off.

P1OUT = P1OUT ^ RED_ON; // Toggle LED when x<30,000

After the loop is complete, the program ensures that the red LED is turned off.

P1OUT = RED_OFF; // Ensures LED is off

43. Finally, the program enters an infinite loop to prevent anything else from happening.

while(1); // Stay here when complete

44. In the CCS Editor, delete all of the text inside your main.c file.

45. Paste the new program into your main.c file. Save and Build it.

Copyright © 2012-2015 Page 20 of 25


Valparaiso University
46. Launch the Debugger. The screen should look like this.

47. Click the Resume button to run your program. The red LED at the bottom of the board should
turn on for about one second and then turn off.

Copyright © 2012-2015 Page 21 of 25


Valparaiso University
48. Your microcontroller just executed the for loop 30,000 times in that one second. That means,
even though it looked light the light was on, it was actually turning on and off through those
30,000 iterations.

49. Right now, your program is still running, but it is stuck in the infinite loop.

50. Now, click the Soft Reset button again to prepare your microcontroller to run again.

51. Try clicking Step Into 15-20 times and watch the board and Variables pane change as you step
through the code.

52. When you are ready, click Terminate to leave the Debugger and return to the Editor.

Copyright © 2012-2015 Page 22 of 25


Valparaiso University
53. Alright, we want to take a look at a small modification to the program you presently have open in
the CCS Editor.

Here, you are going to turn on the red LED before the loops starts, and you are going to do
nothing in the for loop. The for loop will simply increment x to 30,000 creating a delay.

#include <msp430.h>

#define RED_ON 0x0001 // Enable and turn on the red LED


#define RED_OFF 0x0000 // Turn off the red LED
#define DEVELOPMENT 0x5A80 // Stop the watchdog timer
#define ENABLE_IO 0xFFFE // Used to ensure outputs are ready

main()
{
WDTCTL = DEVELOPMENT; // Stop the watchdog timer

PM5CTL0 = ENABLE_IO; // Enable to turn on LED


P1DIR = RED_ON; // Red LED pin will be an output
P1OUT = RED_ON; // Start with red LED off

long x; // Creates variable

for(x=0; x<30000; x=x+1) // Loop 30,000 times


{

P1OUT = RED_OFF; // Ensures LED is off

while(1); // Stay here when complete


}

54. Modify your program. Save and Build it. When you are ready, launch the Debugger.

55. Click Resume to run your program. Again, the light on your board lights up and turns off after
approximately 1 second. However, since we eliminated everything inside of the loop, the LED
remained on the entire time instead of toggling on and off.

Copyright © 2012-2015 Page 23 of 25


Valparaiso University
56. Click Terminate to return to the Editor.

57. In some programs, you may see empty for loops written differently.

Here, we have:

for(x=0; x<30000; x=x+1) // Loop 30,000 times


{

58. This can be rewritten as this – without the curly braces, but including a semicolon at the end of
the for loop.

for(x=0; x<30000; x=x+1); // Loop 30,000 times

59. You can Save, Build, and Debug your program to verify this method also works.

Copyright © 2012-2015 Page 24 of 25


Valparaiso University
All tutorials and software examples included herewith are intended solely for
educational purposes. The material is provided in an “as is” condition. Any
express or implied warranties, including, but not limited to the implied warranties
of merchantability and fitness for particular purposes are disclaimed.

The software examples are self-contained low-level programs that typically


demonstrate a single peripheral function or device feature in a highly concise
manner. Therefore, the code may rely on the device's power-on default register
values and settings such as the clock configuration and care must be taken when
combining code from several examples to avoid potential side effects.
Additionally, the tutorials and software examples should not be considered for use
in life support devices or systems or mission critical devices or systems.

In no event shall the owner or contributors to the tutorials and software be liable
for any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services; loss of
use, data, or profits; or business interruption) however caused and on any theory
of liability, whether in contract, strict liability, or tort (including negligence or
otherwise) arising in any way out of the use of this software, even if advised of
the possibility of such damage.

Copyright © 2012-2015 Page 25 of 25


Valparaiso University

You might also like