Components of a Program
Commands
Iteration
Conditionals
EventsToday we'll talk about variables and subFunctions.
Compiler -- A software program that translates high-level program code into machine code (i.e., the 0s and 1s the computer understands).
When you download a robot program, a "binary file" containing the machine code is copied to the robot.
Variable -- A name for a memory cell.
The compiler keeps a symbol table mapping variable names to memory cell addresses.
Consider the following sample program:
principal= 10000
rate = .06
newBalance = principal + principal*rate
The variables are 'principal', 'rate', and 'newBalance'. Each one corresponds to a memory cell. The compiler takes care of converting the symbolic names to memory cell addresses. For instance, the compiler might map 'principal' to the memory cell 2000, 'rate' to the memory cell 2004, and newBalance to the memory cell '2008'. Then memory would look something like the following:
2000: 10000 2004: .06 2008: 10600
Question: Why do the memory cells have addresses that are four apart?
The machine level program would look something like:
Load 10000, 2000 // load 10000 into the memory cell 2000
Load .06, 2004 // load .06 into memory cell 2004
Multiply 2000,2004, 2008
Add 2000, 2008
Note that the programmer generally never sees the 'machine' code, but just 'talks' to the computer using the higher level language.
Mechanics of setting, modifying, and checking a variable (demonstrate)
Consider the 'count green lines' program. Could you do it with just a loop and no variables?
Consider the following extension to the "Count greens" problem:
The robot should start on the white and move forward, counting the green lines it crosses, until it hits the black circle at which time it should stop. After stopping, the program should beep n times, where n is the number of green lines that were crossed. The program should work no matter how many green lines it crosses (not just if 4).
In-Class Problem: Code the above.
A sub-function is a reusable body of code that can be used in many programs.
Also known as a function or procedure.
Most software consists of thousands of lines of code, so software engineers must break it down into functions.
Structure Chart
Sub-Functions in Lego Mindstorms: My Blocks
Demonstrate creation of a block that just turns the robot around.
In-Class Problems
1. Write a block "Turn Around" and save it in 'My Blocks'. Then use that block in two different programs.
2. Analyze your 'Count greens' program and select two block sequences that can be turned into reusable blocks. Save the sequences in your My Blocks, then write a new version of count greens that uses those blocks.