Chapter 36
Programming Concepts: The Fundamentals

Back in the “olden days,” you built a robot with a couple of motors, some tubes and a relay, and a big ol’ battery. Today, many robots, including the amateur variety, are equipped with a computational brain of one type or another, and the brain is told what to do through software programming.

Why is this progress over tubes and a big ol’ battery? The brain and programming are almost always easier and less expensive to implement than other methods. The nature of the programming depends on what the robot does. All its actions boil down to a relatively small set of instructions in whatever programming language you are using. If you’re new to programming or haven’t practiced it in several years, read through this chapter to learn the basics of programming for controlling your robots. It discusses rudimentary stuff so you can better understand the more technical material in the chapters that follow.

Of course, if you’re already familiar with programming, feel free to skip this chapter.

image
Unless otherwise noted, the programming examples used in this chapter are what’s called pseudo-code. It isn’t fully functioning code, and it’s highly unlikely it’ll work as is in whatever programming environment you’re using. So don’t try. Pseudo-code uses English-like phrases to demonstrate the overall intent of the programming.

If you want to see actual runnable code, refer to the chapters in parts 7 and 8. Additional programming examples are provided on the RBB Online Support site, detailed in Appendix A.

Important Programming Concepts

There are 11 important concepts in understanding programming, whether for robots or otherwise. In this chapter, we’ll talk about each of the following in greater detail:

image Flow control

image Routines

image Variables

image Expressions

image Strings

image Numerical values

image Conditional statements

image Branching

image Looping

image Inputting data

image Outputting data

GOING WITH THE FLOW

You can create simple one-job programs without a predefined blueprint or flowchart. For more complex programs, you may find it helpful to draw a programming flowchart, which includes the basic steps of the program. Each box of the chart contains a complete step; arrows connect the boxes to indicate the progress or sequence of steps throughout the program.

Flowcharts are especially handy when you are creating programs that consist of many self-contained “routines” (see the next section) because the graphical format of the chart helps you visualize the function and flow of your entire program.

THE BENEFIT OF A ROUTINE

Even the longest, most complex program consists of little more than bite-size segments, called routines. The program progresses from one routine to the next in an orderly and logical fashion.

A routine is any self-contained segment of code that performs a basic action. In the context of robot control programs, a routine can be a single command or a much larger action. Suppose your program controls a robot that you want to wander around a room, reversing its direction whenever it bumps into something. Such a program could be divided into three distinct routines:

image Routine 1: Drive forward. This is the default action or behavior of the bot.

image Routine 2: Sense bumper collision. This routine checks to see if one of the bumper switches on the robot has been activated.

image Routine 3: Reverse direction and turn. This occurs after the robot has smashed into an object, in response to a bumper collision.

Figure 36-1 shows how this program might be mapped out in a flowchart. While there’s no absolute need to physically separate these routines within a program, it often helps to think of the program as being composed of these more basic parts.

image
A routine by any other name might be a routine, or it might be a subroutine, sub, method, class, function, or a variety of other terms. It all depends on the programming language and the habit of the programmer. Different terms, but the basic concept is the same.

VARIABLES

A variable is a holding area for information, a kind of shoe box for data. In most programming languages you can make up the name of the variables as you write the program. The content of the variable is either specified by you or filled in from some source when the program is run. Since the information is in a variable, it can be used someplace else in the program as many times as you need.

image

Figure 36-1 Example flowchart showing how a robot software program is broken down into separate actions and reactions. The robot follows either of two prescribed plans, depending on whether its bumper switch has been activated.

Variables can hold different kinds of data, depending on the number of bits or bytes that are needed to store those data. A numeric value from 0 to 255, for example, requires 8 bits, equivalent to 1 byte, of storage space. This means the variable for such a value needs to be at least 1 byte large, or else the number won’t be stored properly.

FYI
Bits, bytes, and other forms of data are discussed in more detail in “Understanding Data Types,” later in this chapter. For now, it’s not critical if you aren’t familiar with these terms.

EXPRESSIONS

An expression is a mathematical or logical “problem” that a program must solve before it can continue. Expressions are often simple math statements, such as 2 + 2. When you ask a program to perform some type of calculation or thinking process, you’re asking it to evaluate an expression.

One of the most common expressions is evaluating whether a statement is True or False (I’ve capitalized the words true and false to show that we’re dealing with logical functions). Here’s a good example of a True/False expression that must be evaluated by a program:

If Number = 10 Then End

This expression reads: “If the content of the Number variable is equal to 10, then end the program.” Before proceeding, your robot must pause, take a peek inside the Number variable, and apply it to the logical expression. If the result is True, then the program ends. If it’s False (Number has a value other than 10), then something else happens.

STRINGS

A common term encountered in programming circles is string. A string is simply a sequence of number and letter characters. These characters are stored within the computer’s memory one right after the other, like beads on a string—hence the name.

In the context of programming languages, strings are most often used to communicate information to human users, such as text on a liquid-crystal display (LCD) panel.

NUMERICAL VALUES

Computers, and the programs that run on them, are designed from the ground up to work with numerical values, ye olde numbers. Numbers differ from strings in one important way, however: the program can perform calculations on two numbers and provide you with the result.

CONDITIONAL STATEMENTS

Programs can be constructed so that they perform certain routines in one instance and other routines in another. Which routine the program performs depends on specific conditions, set either by the programmer, by some sensor on the robot, or by the contents of a variable.

A conditional statement is a fork in the road that offers the program a choice of two directions to take, depending on how it responds to a True/False question. The types and styles of conditional statements differ among robot programming languages, but they all have one thing in common: they activate a certain routine (or group of routines), depending on external forces.

The most common conditional statement is built using the If command. Here’s an example: “If it’s cold outside, I’ll wear my jacket. Otherwise, I’ll leave the jacket at home.” The statement can be broken down into three segments:

1. The condition to be met (if it’s cold).

2. The result if the condition is True (wear the jacket).

3. The result if the condition is False (leave the jacket).

BRANCHING

Akin to the conditional statement is the branch, where the program can take one of several paths, depending on external criteria. A good example of a branch is when a robot senses a collision while moving, as in our earlier example (see the section “The Benefit of a Routine”).

The robot normally just drives forward, but many times each second its program branches off to a routine that checks to see if a collision sensor has been activated. If the sensor has not been activated, nothing special happens, and the robot continues its forward movement. But if the sensor has been activated, the program branches to a different routine and performs a special action to move the robot away from the obstacle that’s just been struck.

LOOPING

A loop is programming code that repeats two or more times. A typical loop checks to make sure some condition is met, and if it is, the contents of the loop are processed. When the program gets to the bottom of the loop, it goes back to the top and starts all over again. This process continues until the test condition is no longer met. At that point, the program skips to the end of the loop and performs any commands that follow it.

INPUTTING DATA

When you sit at a computer, you use a keyboard and a mouse to enter data into the machine. While some robots also have keyboards or keypads (and a few have mice), data input for automatons tends to be a bit more specialized, involving, for example, touch switches or a sonar ranging system. In all cases, the program uses the information fed to it to complete its task.

The reverse-on-collision robot described earlier is once again a good example. The data to be input is simple: it is the state of a bumper switch on the front of the robot. When the switch is activated, it provides a signal—“Hey, I think I hit something!” With that signal your bot can (for example) back up, get out of the way, and head toward some other wall to do it all over again.

OUTPUTTING DATA

In the realm of robot control programs, data output is most often used to turn motors on and off, to activate a sonar chirp for sensing distance, and to blink a light-emitting diode to communicate with you in a crude form of Morse code. (Or how about one flash for Yes, two flashes for No? Well, it worked for Captain Pike in Star Trek!) Data output provides a means for the robot to either interact with its environment or interact with you.

On robots equipped with liquid-crystal display panels, data output can provide a way for the machine to fully communicate its current condition. Simpler data output is possible with that Captain Pike light-emitting diode (LED) trick. Or even simpler still, maybe if the LED is on, it could mean your robot has run into trouble and needs your help. What the signals mean is completely up to you.

Understanding Data Types

At their most basic level, programs manipulate data. Data come in many forms, including a funny-looking guy with platinum-colored skin on Star Trek: The Next Generation. (Oh, no, not another Star Trek joke!) Actually, the kind of data we’re interested in are strictly numbers of one type or another. Those numbers might represent a value like 1 or 127, the numeric equivalent of a text character (65 is “A” using the ASCII standard), or binary 00010001, which could mean “turn on both motors” on your robot.

THE MOST COMMON DATA TYPES

In a program, data types can take the following common forms:

Literals: A literal is, literally, a value “hard-coded” into the program. For example, in the statement MyVariable = 10, the 10 is literal data.

Variables: We’ve already seen what a variable is: it’s a place where data can be stored and referenced elsewhere in the program. It’s the MyVariable in the statement MyVariable = 10.

Constants: Depending on the design of the programming language, a constant can be just another name for a literal or it can be a special kind of variable that—once set—is never meant to be changed.

Expressions: The result of a math or logical expression can “return” a data type. For example, the expression 2 + 2 returns the value 4.

No matter what form the data type is in, the programming language expects to see its data follow predefined types. This is necessary so the data can be properly stored in memory. The most common data type is the 8-bit integer, so called because the value stores an integer (a whole number) using 8 bits.

image
A bit is the smallest value that can be stored in memory and processed by a computer. A bit is either off or on. The two possible values for a bit are most commonly represented by the numerals 0 and 1. The value stored in the bit is not really a numeric “zero” or “one”; the 0 and 1 are used as a kind of shorthand. Other shorthand terms include LOW (for 0) and HIGH (for 1).

With eight sets of bits, the program can work with a number from 0 to 255 (or−128 to +127, depending on how it uses the eighth bit, as discussed later). The basic data types are as follows:

image Single bit, on or off; HIGH or LOW; yes or no, 0 or 1

image 4-bit nibble (half a byte; sometimes called a nybble)

image 8-bit integer, or byte (can hold a number, a True/False value, or a string value)

image 16-bit integer, or word

image 32-bit integer, or long or double word (dword)

image 32-bit floating point, or single (“floating point” means a number with a decimal point)

SIGNED AND UNSIGNED NUMERIC VALUES

In many cases, programming languages provide for either (or both) “signed” and “unsigned” values. Signed means the number can be expressed as either a positive or a negative value; unsigned means the number can only be a positive value.

In these languages, the first bit on the left (called the most significant bit, or MSB; see Figure 36-2) is used to denote whether the number is positive or negative. If the MSB is a 0, it means the number is a positive value; if it’s a 1, the number is negative. With an 8-bit unsigned integer, for example, the program can store values from 0 to 255. With an 8-bit signed integer, the program can store values from−128 to +127.

AT A GLANCE: NUMBER LIMITS BY DATA TYPE

Always remember that there are limits to how big a number can be when stored as any given data type. If the number you try to store exceeds the limits of the data type, your program could report an error (and perhaps stop), or at best the data will be inaccurate. The numeric limits for the main integer data types are:

image

Figure 36-2 Numeric values are stored in a microcontroller as a set of bits, 8 bits making 1 byte. The most significant bit, or MSB, of this value is often used to determine if the number is positive only, or either positive or negative. Here, the bits 10011010 can represent the value 154 or –102, depending on how the MSB is treated.

image

Over the years, programming languages have evolved and have greatly messed things up by playing loosey-goosey with terminology. A good example is the word integer. The term “integer” means—in Latin, no less—a whole number; yet many programming languages use it to refer to a data type of a specific size.

image

What’s worse, the size of the data type can and does change as the programming language evolves. In older versions of Visual Basic, for example, “integer” meant a 16-bit signed whole number. Now it means a 32-bit signed whole number.

Keep all this in mind as you’re learning a new programming language. You may see a data type called Int, int, Integer, or some other variation. Yes, it’s for storing an integer (whole number), but it’s also a data type whose size is specific to that language.

Lucky Seven Most Common Programming Statements

Here are seven of the most common statements you’ll encounter in most any programming language. The examples shown are those for the BASIC programming language, but the fundamentals are the same for other languages.

COMMENTS

Comments are used by a programmer as remarks or as reminders of what a particular line of code or routine is for. The comments are especially helpful if the program is shared among many people. When the program is compiled (made ready) for the computer or microcontroller, the comments are left out. They appear only in the human-ready source code of your programs.

To make a comment using BASIC, use the ‘(apostrophe) character. Any text to the right is treated as a comment and is ignored by the compiler. For example:

′this is a comment

image
The symbol used for comments differs among languages. In the C programming language, for instance, the characters // are used to denote a command. C also offers the /* and */ characters to mark a comment block. Very handy.

IF

The If statement is used to build a conditional expression. It is called a conditional expression because it tests for a specific condition:

image If the expression is True, the program performs the commands following the If statement.

image If the expression is False, the program performs the commands after the Else statement, if any.

Here’s a sample conditional statement in BASIC:

image

The If statement evaluates a condition to determine if it’s True or False. The most common evaluation is for equality. The = (equals) sign is used to test if one value, such as the contents of a variable, is equal to another value. However, there are other forms of evaluation, such as “not equal to,” “greater than,” “less than,” and several others. See the “Variables, Expressions, and Operators” section later in this chapter for more information.

image
In the C language, equality is tested using two equals signs together: ==. This is one of the most common mistakes beginning C programmers make. The statement if x = 1 is wrong. It should be if x == 1.

SELECT CASE

The Select Case statement is used when you want to test a value (usually in a variable) against several possibilities. The Select Case statement lets you test each number individually and tell the program specifically what you want to happen should there be a match.

The basic syntax for the Select Case statement is:

image

image
In the C programming language, the switch statement takes the place of Select Case. In C, you still use the case statement to test each condition, but remember that in C, case is all lowercase.

TestVar is the test expression. It is evaluated against each of the Case arguments that follow. If the value in TestVar is equal to x, then the program performs the action that follows Case x. If the value in TestVar is equal to y, then the program performs the action following Case y, and so forth.

CALL

The Call statement tells the program to temporarily branch elsewhere in the program. This is a routine that is identified by name, using a label. The program expects to find a Return statement at the end of the routine. When it encounters the Return statement, the program jumps back to the Call statement and continues executing. A typical Call statement and label look like this:

image

GO

The Go statement is used to jump to the specified label. In programming parlance, using Go to go to a label is called unconditional branching. The Go statement uses one argument, namely, the name of the destination label. For example:

image

FOR/NEXT

The For/Next statement is actually a pair of commands. They repeat other programming instructions a specified number of times. The For/Next structure is perhaps the most commonly used of all programming loops. The For portion of the For/Next loop uses an expression that tells the program to count from one value to another. For each count, any programming code contained within the For/Next structure is repeated:

image

x is a variable that the program uses to keep track of the current loop iteration. The first time the loop is run, x contains 1. The next time through, x contains 2, and so on. When x contains 10, the program knows it has run the loop 10 times and skips to the Next statement. From there, it executes any additional code that may be in the remainder of the program.

WHILE/WEND

The While/Wend statements also form a loop structure. But unlike For/Next, which repeats a set number of times, the loop of a While/Wend structure repeats while a condition is met. When the While condition is no longer met, the loop is broken and the program continues. Code that falls between the While and the Wend statements is considered part of the loop that is repeated.

image

x is an expression that is evaluated each time the loop is repeated. For instance, the expression might be While switch = 0, which tests to see if the switch variable contains a 0, signifying perhaps that some switch has not been activated. When switch is no longer 0, the loop breaks.

image
In many robot control programs, the While/Wend loop (and variations, such as Do/Loop) is set up to run indefinitely. This infinite loop repeats a process over and over again until the power to the robot is turned off.

Variables, Expressions, and Operators

Earlier in this chapter you read how variables are temporary holders of information. Placing data into a variable is referred to as assigning, or assigning a value to a variable.

ASSIGNING A VALUE TO A VARIABLE

The most common way to assign a value to a variable is to use the assignment operator. In most programming languages used for robot control, this is done with the = (equals) symbol. It is most often necessary (or at least advisable) to define the data type that will be stored in the variable before assigning a value to it. Here’s an example for the BASIC language:

  Dim X As Integer
  X = 10

Dim stands for “Dimension,” which tells the program that you are defining the type of the variable you wish to use—allocating space (dimension) in memory for it. X is the name of the variable you wish to assign. The = (equals) sign is the variable assignment symbol, and 10 is the value you are placing inside the X variable.

image
Many languages restrict the names you can use for variables. Specifically, the variable name must start with a letter character, and it cannot contain spaces or other punctuation. Reserved words—special identifiers such as If, While, and Select—are also unavailable for use as variable names.

Once you define a variable as containing a certain kind of data, it’s important that you do not then assign a different data type to the variable. For example, all of the following are wrong:

image

Most robot control languages let you assign a variety of values to variables, as long as the values match the data type you are using. Among the most common value types assigned to variables are:

Literal values: As mentioned earlier, a literal value is a value you specify when you write the program. For example:

image

Contents of another variable: Here you copy the contents of one variable into another variable. For example:

image

(Careful with this one! In most languages, what gets copied is the content of the variable, not the variable itself. If you later change the content of Y, X stays the same. But some programming languages try to mess with your mind, letting you specify a “pointer” to the variable, rather than just its content. If you change Y, X changes, too.)

Memory location: Many programming languages let you reference specific portions of physical memory. For example:

image

Register reference: A register reference is a value maintained by your robot’s microcontroller. Registers are just like variables, but their names are built into the microcontroller hardware. For example:

image

Evaluated expression: The evaluated expression variable stores a value that is the result of an expression. For example:

image

CREATING EXPRESSIONS

An expression tells the program what you want it to do with information given to it. An expression consists of two parts:

image One or more values

image An operator that specifies what you want to do with these values

In most programming languages, expressions can be used when you are defining the contents of variables, as in the following:

image

The program processes the expression and places the result in the variable.

The following sections present the most common operators and how they are used to construct expressions. Some operators work with numbers only, and some can also be used with strings. The list is divided into two parts: math operators (which apply to number values only) and relational operators (which work with both numbers and in some programming languages’ strings).

Math Operators

image

Relational Operators

image

Relational operators are also known as boolean or True/False operators. Whatever they test, the answer is either yes (True) or no (False). The expression 2 = 2 is True, but the expression 2 = 3 is False.

Using And and Or Relational Operators

The And and Or operators work with numbers (depending on the language) and expressions that result in a True/False condition. It’s often helpful to view the actions of the And and Or operators by using a truth table like the two that follow. The tables show all the possible outcomes given to values in an expression:

AND Truth Table

image

OR Truth Table

image

USING OPERATORS WITH STRINGS

Recall that a string is an assortment of text characters. You can’t perform math calculations with text, but you can compare one string of text against another. The most common use of operations involving strings is to test if a string is equal, or not equal, to some other string, as in:

If “MyString” = “StringMy” Then

This results in False because the two strings are not the same. In a working program, you’d no doubt construct the string comparison to work with variables, as in:

If StringVar1 = StringVar2 Then

Now the program compares the contents of the two variables and reports True or False accordingly. Note that string comparisons are almost always case-sensitive:

image

While the = (equals) operator is used extensively when comparing strings, in many programming languages you can use <>, <, >, <=, and >= as well. See “Creating Expressions,” previously in the chapter, for more details on these operators.

MULTIPLE OPERATORS AND ORDER OF PRECEDENCE

All but the oldest or simplest programming languages can handle more than one operator in an expression. This allows you to combine three or more numbers, strings, or variables to make complex expressions, such as 5 + 10 / 2 * 7.

This feature of multiple operators comes with a penalty, however. You must be careful of the order of precedence, that is, the order in which the program evaluates an expression. Some languages evaluate expressions using a strict left-to-right process, while others follow a specified pattern whereby certain operators are dealt with first, then others. When the latter approach is used, a common order of precedence is as follows:

image

The programming language usually does not distinguish between operators that are on the same level of precedence. If it encounters a + for addition and a − for subtraction, it will evaluate the expression by using the first operator it encounters, going from left to right. You can often specify another calculation order by using parentheses. Values and operators inside the parentheses are evaluated first.

On the Web: More Programming Fundamentals

There’s more that I’d like to discuss about programming, but I’m running out of space. I’ve put together several short articles on the RBB Online Support site (see Appendix A) that provides additional programming fundamentals. Topics include:

image Using bitwise operators—work with the individual bits of a byte or larger value.

image Using operators with text strings—compare, match case, find specific text within a string.

image Additional programming statements and concepts.

image Techniques for writing your programs to reduce memory use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.129.100