Introduction

BasicStamp

The BasicStamp family of microcontrollers is manufactured by Parallax. The BasicStamps contain a Microchip PIC microcontroller unit preloaded with a PBASIC interpreter program, a voltage regulator, and a flash memory unit. The benefits are the power and small size of the PIC controller, with the added benefits of extended memory and the PBASIC instruction language, which is easier to understand and use then the PIC assembly language.

This book is written both as an introduction to PBASIC programming, but also to embedded programming in general. For a more in-depth look at embedded systems and embedded programming, see Embedded Systems.

Who is This Book For?

This book is for anybody interested in learning to program embedded systems. One of the primary uses of the BasicStamp, at least in terms of education, is robotics. Parallax sells a number of robotics kits that are based off the BasicStamp architecture. Beyond the use in robotics, there are a number of other areas where BasicStamps can be used with great success.

An accompanying course at Wikiversity, Introduction to Robotics will be using this textbook and the BasicStamp architecture to teach students about robotics.

What are the Prequisites?

Students should have a basis of understanding in elementary algebra. No prior programming experience is required. The use of and interpretation of graphs will also be a useful skill, but is not strictly required. A background in chemistry or physics where mathematics is used to model physical phenomina will also be helpful. The reader should be able to read and understand metric system units, and be able to make simple conversions between units. For instance, the reader should know that 1000 microseconds are in 1 millisecond.

What Will This Book Cover?

This book will attempt to look at the PBASIC programming language as it is used in practice: in an embedded application. Therefore, we will need to discuss certain things that aren't purely software, such as voltage and electric circuits, sensors and actuators, etc. We attempt to keep discussions on these subjects as simple as possible, so that the reader can use the concepts in their project, but don't get weighted down with complicated mathematical theory. We do, however, need to provide enough explanation of certain concepts that the reader can employ them safely and effectively.

Are There Any Aides for This Book?

There is a robotics course at Wikiversity that uses the BasicStamp and the PBASIC language to operate simple robots. That course uses this book as it's primary text. If the reader is interested in robotics, and would also like some hands-on assignments to help demonstrate the concepts learned in this book, it is recommended that they also participate in the Wikiversity course. The course is located here:

Because of it's focus on robotics, the Wikiversity course may present information in a slightly different order from the way it is present here, and it may also focus more or less of different topics.

History

Microcontrollers

A modern desktop computer contains a special type of chip called a "Microprocessor". Microprocessors are common, and you hear about them all the time: "Pentium", "Athlon", "Core 2 Duo", etc. A microprocessor can do certain math calculations and it can execute instructions, but it relies on the rest of your computer (mother board, RAM, etc) to operate. Take away one of the other parts of the system, and your computer will not work.

Similar to a microprocessor is the microcontroller, a smaller type of device that is more self-reliant. Microcontrollers do not need a special motherboard, or a special power supply, or even additional RAM to operate: you can plug them in and they will work perfectly. Microcontrollers are also typically very small and cheap as well, making them a good addition to almost any design project.

Microcontrollers can be found in all sorts of devices, anywhere from a cellular phone to a digital microwave to your car and your television. If you have something that has buttons, or something more complicated then a paper weight, it probably has a microcontroller inside.

MicroChip PIC

A common and popular type of microcontroller is the PIC, made by a company called Microchip. PIC is not just one microcontroller, but a whole family of them, each with a different size, different shape, different abilities, and a different price. Because of the large range of options, the small size, and the low price, PIC microncontrollers have been very popular devices among hobbyists and engineers. However, PICs have a number of different problems that make their use more difficult:

1. They are difficult to program. Some PICs can only be programmed once, which means that you can't make any mistakes (and everybody makes mistakes). For PICs that can be reprogrammed, you need to either build a programmer or you need to buy one. Programmers are relatively complex circuits and can be tough to build. However, the programmers that you can buy might be very expensive.
2. They are programmed using an assembly language. Assembly language is very low-level, meaning that it is easier for a computer to understand, and harder for a human to understand. Also, programming in assembly requires you know know what is inside the microcontroller, the "architecture", which can be very difficult indeed.
3. They don't have power regulation. A PIC requires a separate power regulator circuit, to help prevent too much power from going into the chip and destroying it. Power regulators typically need to be built by hand, which can be tricky.

BasicStamp

The Parallax company decided to use the PIC processor, but to make it easier for people to use. They took a very small version of the PIC, added memory for bigger programs, added a voltage regulator, added an oscillator, and they preprogrammed it with a BASIC interpreter. The result was the BasicStamp. BASIC is a family of computer programming languages which were designed to be very simple and easy to learn. It is much easier and faster to write a program in BASIC then it is to write the same program in PIC assembly. The designer now doesn't need to build any of the circuits that needed to be built with the PIC: no voltage regulator, no oscillator circuit, and no programmer. This helps to speed up development time. Projects using the BasicStamps can be smaller and simpler then projects using just PICs.

The version of BASIC used in the BasicStamp is called PBASIC. This book will discuss the PBASIC language as it applies to the BasicStamp.

PBASIC Editor

' Cizgin03 Program ' {$STAMP BS2} ' {$PBASIC 2.0} OUTPUT 4 OUTPUT 5 INPUT 0 INPUT 1 INPUT 2 i VAR Byte ' '------------- basla: IF IN7=1 THEN ileri IF IN8=1 AND IN7=0 AND IN6=0 THEN sagsensor IF IN8=1 AND IN7=1 THEN sagsensor IF IN6=1 AND IN7=1 AND IN8=1 THEN ileri IF IN6=1 AND IN7=0 AND IN8=0 THEN solsensor IF IN6=1 AND IN7=1 THEN solsensor IF IN6=0 AND IN7=0 AND IN8=0 THEN durum '------------- ileri: PULSOUT 0,500 PULSOUT 1, 1000 GOTO Basla '------------- solsensor: i=1 GOTO basla '------------- sagsensor: i=3 GOTO basla '------------- durum: IF i=1 THEN solsen IF i=3 THEN sagsen GOTO basla '------------- solsen: i=1 GOTO basla '------------ sagsen: i=3 GOTO basla END

Data Types

Binary Numbers

When we think about numbers that we use every day, we are thinking about numbers in base 10. This means that there are 10 different digits that we can use: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Using these 10 digits and powers of 10, we can create any number in our system:

${\displaystyle 123=1\times 10^{2}+2\times 10^{1}+3\times 10^{0}}$

In a binary or "base 2" system, we only have two digits: 0 and 1. To make a number in binary, we use powers of 2 instead of powers of 10:

${\displaystyle 10101=1\times 2^{4}+0\times 2^{3}+1\times 2^{2}+0\times 2^{1}+1\times 2^{0}=21}$

When talking about numbers in different systems, it is common to use subscripts. A subscript of 10 means the number is in base 10, and a subscript of 2 means the number is in base 2. For instance:

${\displaystyle 1010_{2}=1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+0\times 2^{0}=10_{10}}$

Common Data Types

Computers are very limited, and the space that they have to store numbers is fixed. This means that there are a certain number of bits available, no more and no less. Certain sizes of numbers are so common that they have special names.

Bit

A bit is a single binary number, either a 0 or a 1.

Nibble

A nibble is 4 bits, and can contain values from 0 to 15.

Byte

A byte is 8 bits (2 nibbles) and can contain values from 0 to 255.

Word

A word is 16 bits long (2 bytes or 4 nibbles) and can contain values from 0 to 65535.

Available Storage

The BASIC Stamp has 128 bytes (64 words) of data storage that can be used by your program as variables. We will discuss variables later.

Limitations

There are a number of limitations when working with computer numbers.

Negative Numbers

In order to support both positive and negative numbers, PBASIC needs to "steal" one of the bits from the number to represent the sign. Consequently, the range of all of our data types gets smaller:

Bits
Bits cannot be signed.
Nibble
Signed nibbles can go from -8 to 7
Byte
Signed bytes can go from -128 to 127
Word
Signed words can go from -32768 to 32767

Negative numbers are stored in a special way called two's complement. We will not cover this here.

Fractions

Some computers are capable of dealing with fractional numbers, called "floating-point numbers". However, BASIC Stamps cannot deal with fractions. This means that whenever we try to use a fraction, the BASIC Stamp will always round down. This means that the number 1.9 will become 1 inside the BASIC Stamp. Some people may find it strange that:

${\displaystyle {\frac {3}{2}}=1}$

However in computers, this is common.

Overflow

Datatypes have a fixed width, and they cannot hold numbers that are too big. If we try to store a number too big in a variable, the top-most bits will be "chopped off". If we are talking about bytes, we can write:

${\displaystyle 255+2=1}$

This is called overflow, and is something that we need to pay attention to when doing arithmetic. If a byte or a nibble is too small, we can always use words instead. But if we want to store a number that is greater then 65535, then we are in trouble!

Writing Numbers

There are several ways that a programmer may wish to specify a number: Binary, Decimal, or Hexadecimal. Hexadecimal, which we won't discuss in this book, is another useful number system using a base of 16.

To write a decimal number, we just write the number with no prefix, such as: "99". If we want to write a binary number, we use the "%" prefix, such as: "%110011". To write in hexadecimal, we would use the "$" prefix as so: "$AF99".

ASCII

In a computer, everything is stored in binary. This means that even things that aren't numbers, such as letters or other characters, are stored using binary numbers. There is a special code that assigns every character to a special binary pattern called ASCII. To write a letter in ASCII, we use the double-quotes such as:

MyVariable = "A"


Notice that a number and the ASCII code for that digit are not the same value:

MyVariable = 1

MyVariable = "1"


These two are not the same! However, ASCII has a special property that all the characters and digits are arranged from lowest to highest, and so we can do math with ASCII characters in some instances:

MyVariable = "A" + 1


Now MyVariable is equal to "B"! Also, we can convert digits into regular binary numbers by using a simple relation:

MyVariable = "1" - "0"


Now MyVariable is equal to the binary number 1. We will discuss variables more later, but these examples should be self-explanatory for now.

Variables and Constants

Need for Storage

When we write a program, it's always a good thing to be able to store data that we are using, and to manipulate that data. If we want to set aside some storage for a particular use, we need to tell the computer to save that space, and we need to give the space a name. A variable is a storage location, like a box or a shelf in real life, that has a name. Think about the common algebraic equation for a straight line:

${\displaystyle y=mx+b}$

Where y is a variable that can take values dependent on the values for the other parameters.

Variables

A variable is a storage location where we can hold values. A variable can be the size of one of our datatypes, such as a bit, a nibble, a byte, and a word. Once we define a variable, the size of it is fixed: If we define a byte, our variable cannot contain values over 255.

Defining a Variable

To define a variable, we use the VAR keyword. First we need to give a name to our variable, and the name for the variable cannot be the same as any of the reserved words. Variable names must start with a letter, may contain letters or numbers, and are not case sensitive. Here are some examples:

MyVariable1 VAR Bit
MyVariable2 VAR Nib
MyVariable3 VAR Byte
MyVariable4 VAR Word


Aliases

We can give names to the individual parts of our variables. For instance, we know that a byte is made up of 8 bits, and if we want we can give each of these bits a name, if we want. Notice that bit numbers start at 0, not 1. Here are some examples:

MyVariable VAR Byte
FirstBit VAR MyVariable.Bit0
FirstNib VAR MyVariable.Nib0
SecondNib VAR MyVariable.Nib1
FirstBitFirstNib VAR FirstNib.Bit0


Notice that the variable FirstBit is the same exact thing as FirstNibFirstBit.

Arrays

If we have multiple data values that are related, and we don't want to give them all individual names, we can create an array. An array is a large variable that contains many "boxes", each with an address. The array has a name, and to access an individual box in the array, you need the name of the array and the address. Here are some examples:

MyArray VAR Byte(10)


This creates an array with 10 bytes. Each byte can still only contain numbers up to 255, and we cannot combine multiple bytes in our array to make larger numbers.

We can use aliases with array elements too:

MyArray VAR Byte(10)
MyVariable VAR MyArray(0)


We can also make more complicated aliases, but we need to keep the box address at the end:

MyArray VAR Byte(10)
MyVariable VAR MyArray.Nib1.Bit0(0)


Constants

Sometimes when we are doing calculations, we can define a thing called a constant to make things easier. Constants are just numbers, not variables, and once you set the value it cannot be changed. A common example of a constant that people use is π = 3.1415.... Instead of having to write out π to several decimal points each time we want to use it, we can simply define a constant value with the name "pi". To define a constant, we use the CON keyword. Here are a few examples:

Ten CON 10
ACouple CON 2
ABunch CON 1024


Constants are useful for a number of reasons:

1. Makes mathematical equations easier to read.
2. If we need to change a value, we only change the CON definition, and we dont need to change it everywhere in the code

Basic Arithmetic

Arithmetic Operators

We can use some of the basic arithmetic operators for common operations. Operators can be used with variables, constants, or numbers.

Common Operators

To add two numbers together, we use the "+" operator:
Var1 + Var2

Subtraction
To subtract one number from the other, we use the "-" operator:
Var1 - Var2

Multiplication
To multiply, we use the "*" operator:
Var * Var2

Division
To divide two numbers, we use the "/" operator:
Var1 / Var2


Other Math Functions

Multiply High
"**" returns upper 16 bits of 32 bit result:
Var1 ** Var2


Assignment

We can use the "=" operator to assign a value to a variable. For instance, we can write:

MyVar VAR Byte
MyVar = 10

MyVar VAR Byte
MyVar = 10 + 5

MyVar VAR Byte
MyVar2 VAR Byte
MyVar = 10
MyVar2 = MyVar + 10


We can also write a self-assignment, or an assignment where a variable appears on the left and the right side of the statement:

MyVar VAR Byte
MyVar = 10
MyVar = MyVar + 1


On the third line of this program, MyVar equals 10, and then we add one and store the new result into MyVar again. After this program runs, MyVar contains the value of 11.

Overflow and Underflow

Overflow occurs when we attempt to store a number in a variable that is too large for that variable. For instance, if we try to store a number that is larger then 255 in a Byte, or a number that is larger then 65535 in a word. Underflow is the exact opposite problem, where we attempt to create a negative number that is so low that the variable cannot hold it.

Labels and GOTO

Control Flow

Computers are only able to perform one action at a time. This means that if we write up a large program with many instructions, that the BasicStamp will execute those instructions one at a time, starting at the top and moving to the bottom. The order in which the BasicStamp executes instructions is called the control flow. There are several tools that we can use to change the control flow, so that it doesnt just start at the top and move to the bottom.

Tokens and the Instruction Pointer

When we compile our program, the computer changes the code that we have written into a series of tokens that the BasicStamp can understand. This process is very complicated, so we won't discuss it any further in this book. When we upload our program to the BasicStamp, all of the tokens from the program are stored, in order, in the BasicStamp's FLASH memory unit. The tokens are stored in an array. A special address variable, called the instruction pointer points at the different elements in the token array, and whatever the instruction pointer points at is the instruction that the BasicStamp will perform at that moment.

Labels

We can create special tags called labels that are like addresses or anchors. If we create a label in our code, we can jump to it from other parts of our program by using special instructions called GOTO, GOSUB, or branches called IF / THEN. Labels must have a name, just like a variable. They must:

• Contain letters or numbers
• End with a colon ":"

GOTO

The most simple way to jump to a label that we have defined is through the use of the GOTO command. The GOTO command causes the instruction pointer to point at the label, instead of the next instruction.

Branches

Comparison Operators

A computer processor, such as the BasicStamp is capable of comparing two numbers and testing their relationship. The BasicStamp can compare two numbers and determine if they are equal, not equal, greater than, or less than. We can use special comparison operators to ask the BasicStamp to compare numbers.

Equal
To determine if two numbers are equal, we use the "=" operator.
Not Equal
To determine if two numbers are not equal, we use the "<>" operator.
Greater Than
To determine if one number is greater than the other, we use the ">" operator.
Greater Than or Equal
To determine if one number is greater than or equal to another number, we use the ">=" operator.
Less Than
We can use the "<" operator to determine if one number is less than the other.
Less Than or Equal
We can use the "<=" operator to determine if one number is less than or equal to another number.

IF / THEN Branches

Once we compare two numbers, we can ask the BasicStamp to take action depending on that comparison. Using the IF / THEN structure, we can perform a jump if the condition is true, and we will not jump if the condition is false. The format of the instruction is:

IF [Condition] THEN [Label]


Where [Condition is a comparison of two values (two variables or a variable and a constant, for instance). If the comparison is true, then the control flow jumps to the [Label].

IF / THEN / Else Structures

Sometimes we want to have a second option. for instance, we want to do one thing if the comparison is true, and we want to do a different thing if the comparison is false. Here is an example, using a single IF / THEN branch, and GOTOs:

IF [Condition] THEN GoTrue
... 'Do this if the condition is false
GOTO EndBranch
GoTrue:
... 'Do this if the condition is true
GOTO EndBranch
EndBranch:


Only one set of code in this case will be executed, depending on whether the condition is true or false. There are other ways to arrange this, of course.

Simple Loops

We can use GOTO to create a simple infinite loop. The program will repeat the code in the middle of the loop forver:

LoopTop:
... 'Do this infinitely
GOTO LoopTop


We can use IF / THEN branches to create more advanced loops as well. However, most of the advanced loops that we can create can be made in a better way. We will discuss more advanced loops in the next chapter.

Loops

Looping

There are times when we want to repeat a certain portion of code several times. For small numbers of repeats, we could use something simple like Copy + Paste in our editor. However if we want to repeat an action many times, or even if we want to repeat infinitely, we need to use special techniques called loops. Using our GOTO function we have already seen a basic type of loop, but there are other types of loops that we can use. In some cases there are many ways to perform the same task.

Infinite Loops

We have already seen a simple loop using the GOTO function. Here is a good example:

LoopTop:
... 'code to repeat goes here
GOTO LoopTop


Instead of having to create a new label and then jump to it, we can use a specialized structure called DO / LOOP that performs the same task, but is easier for people to read and understand.

DO / LOOP

A DO / LOOP structure is an infinite loop, but it doesnt require us to create a label. To use a DO / LOOP, we write:

DO
... 'code to repeat goes here
LOOP


FOR / NEXT

If we have a certain piece of code that we want to repeat a finite number of times, we can't use an infinite loop, we need to use a counter variable to count the number of loops. We have already seen a basic implementation of this concept in the chapter on branches, but now we are going to look at a better structure for this, the FOR / NEXT loop. A FOR / NEXT loop allows us to do several things in a very simple and clean way:

1. Initialize our counter variable
2. Increment our counter variable every loop
3. Check the counter variable to see if it has reached a final value. If it has reached the final value we exit the loop.

A FOR / NEXT loop looks like this:

FOR MyCounter = 0 TO 10
... 'code here will be repeated 11 times
NEXT


Nested Loops

We can put one loop inside another loop. This is useful for many complicated programs that need to repeat sets of loops. Loops that are inside other loops are called nested loops. Also, the outer-most loop is typically called the parent loop, and the inside loops are called the child loops. Each child loop must have a different counter variable from it's parent loop, or the system will not work correctly.

Subroutines

Reusing Code

We have seen in our chapters on loops that there are many times that we want to repeat certain blocks of code multiple times. A loop repeats these blocks one after the other, but what if we want to repeat a block of code at different times?

We can use a special tool called a subroutine to make a block of code repeatable. We can "call" our subroutine at any point in our program, and when the subroutine ends, the control flow will jump back to where it was.

When we move control flow into a subroutine, we say that we "call" the subroutine, or that we "enter" it. Similarly, when the subroutine has completed, we say that we "exit" the subroutine, or that we "return from it".

GOSUB and RETURN

Subroutines start with a label. Instead of using a GOTO jump, we use the GOSUB instruction to enter the subroutine. The GOSUB does two things:

1. it jumps to the subroutine's label, like a regular GOTO
2. it stores the old value of the instruction pointer, so that after the subroutine the control flow can return to where it was.

The second point is important, because it allows us to return to our previous position.

The RETURN instruction, at the end of the subroutine, loads the saved value of the instruction pointer.

Subroutines

A basic subroutine looks like this:

MySubroutine:
... 'Do this in the subroutine
RETURN


One of the big benefits to using subroutines is that they help to make your code much easier to read for other people. Many times the person who writes a program will understand it very well, but it may not be so obvious to other people, such as teammates. For instance, if we have a robot using the BasicStamp, and we want to make that robot walk around in the shape of a square, we can use subroutines to do it easily:

GOSUB MoveForward
GOSUB TurnRight
GOSUB MoveForward
GOSUB TurnRight
GOSUB MoveForward
GOSUB TurnRight
GOSUB MoveForward
GOSUB TurnRight


Or, we can combine our subroutines with a loop to make it even easier:

FOR MyCounter = 1 TO 4
GOSUB MoveForward
GOSUB TurnRight
NEXT


The subroutines for MoveForward or TurnRight may be very complicated, but any person can read the small block of code above and understand what the robot will do.

Input and Output

A computer program that does not communicate with the outside world is very boring indeed. Programs, including programs on the BasicStamp need to take input and generate output.

INPUT and OUTPUT

The BasicStamp has 16 basic I/O pins, all of which can be used as either an input or an output. To specify that a pin is an input we use the INPUT command:

INPUT 12


This makes pin 12 an input pin. To specify that a pin is being used as an output, the OUTPUT command can be used:

OUTPUT 15


This makes pin 15 an output.

DIRS Register

The INPUT and OUTPUT commands affect a special memory value called DIRS. DIRS, which is short for "Directions" is a special memory location known as a "Tri-State Buffer". DIRS contains 16 bits, each corresponding to one of the I/O ports. If the pin in DIRS is a 0, then the corresponding pin is an input. If the pin in DIRS is a 1, then the corresponding pin is an output.

For instance, if we wanted to set the top byte to be input, and the bottom byte to be output, we could write:

DIRS = %1111111100000000


This is easier then having to write 16 INPUT and OUTPUT commands!

I/O Ports

1-Bit Ports

I/O ports have a special name, using the prefix "In" or "Out", followed by the pin number. For instance, if we have a variable called MyVariable, and if all the ports were properly designated as INPUT or OUTPUT, we could write all of the following:

MyVariable = IN3

MyVariable = IN5 + 10

OUT12 = MyVariable

OUT15 = MyVariable - 10


Multi-Bit Ports

We can combine multiple I/O pins into multi-bit I/O ports. Each port has a specific name:

Direction Word Byte Nibble Bit
Input INS INL, INH INA, INB, INC, IND IN0 - IN15
Output OUTS OUTL, OUTH OUTA, OUTB, OUTC, OUTD OUT0 - OUT15

The "S" suffix is used to denote the whole 16-bit word. "L" is for the low byte, "H" is for the high byte. "A", "B", "C", and "D" are used for the 4 possible nibbles, with "A" being the lowest (pins 0 - 3) and "D" being the highest (pins 12 - 15).

Sending and Receiving

When we want to send data from the BasicStamp to another device, we write that data to an output port. The external device that we are trying to communicate with will then read that value from an input port, and use that value internally. Data values to read and write from the BasicStamp are 5 volt values. Too much voltage will cause damage to the circuit, and too little voltage cannot be read. In general, we can associate our values for 1 and 0 with voltages:

Binary Voltage
1 +5V
0 0V

"Voltage?"

We are going to digress from the main narrative of the book here for a minute and discuss some issues of electricity. Because of the embedded nature of the BasicStamp, most projects that involve them are going to also involve some manner of hardware integration. Improperly connecting your BasicStamp to external hardware can cause damage to the chip, and could even cause harm to you.

Ohm's Law

A basic law of electricity, and the only such law that we need to consider for the purposes of this book, is Ohm's Law. Ohm's law can be written as:

${\displaystyle v=iR}$

v is the voltage, in volts. i is the current, in amps. R is the resistance, in Ohms.

We know that the output port of the BasicStamp supplies 5V. If there is too much current, the stamp could get hot or even become damaged. We should try to keep our current to 5 milliamps or less (preferably less). This means, using Ohms's law that:

${\displaystyle 5=(5\times 10^{-3})R}$
${\displaystyle R={\frac {5}{(5\times 10^{-3})}}=1000=1k\Omega }$

This means that for every circuit we use with our BasicStamp, we should have at least 1000Ω of resistance. Any less resistance and we risk damage to our BasicStamp.

Serial Communications

Parallel and Serial

If we want to send out 16 bits worth of data, as we had been doing in the last chapter, we would need to define 16 output ports, and then write our data out to the pins. Here is an example that will output a 1 on every port:

DIRS = %1111111111111111
OUTS = 255


Unfortunately, this system doesnt leave us any extra pins to play with. We don't have any available pins to use for inputs or other outputs. In cases like these, we want to use serial communications instead.

Parallel communications, what we have been doing so far, uses many wires in parallel with one another. Each data bit is transmitted on its own wire, and so to send x bits we need to use x wires. In a serial system, instead of using 16 wires, we use just 1 wire, and send all the data bits on that one wire, one at a time. The target computer, where the data is being sent to, reads each of the bits, one at a time, and stores them in a variable.

To use serial I/O, we use the SERIN and SEROUT functions

Serial Settings

Serial I/O is obviously a little more complicated then parallel data is. For instance, we need to know what speed the data is being sent, so that the target computer can read the data at the same speed. We also need to know a few other things:

Parity
Parity adds an extra bit to every byte that we transmit. This extra bit can be used to determine if there is an error in the transmission. Parity can be set to "Odd", "Even", or "None".
Baud
"Baud" is the number of pulses that are transmitted each second. Both the sender and the receiver need to be using the same baud.
Data Bits
Data bits is the number of bits per "chunk" of information. There are commonly 8 data bits, but 7 is also possible on some hardware.

Both the sender and the receiver need to have the same values for the parity, baud, and data bits. If these are not matched, the communication will not work.

Port
This is the number of the port to be used to send or receive the data. This can be any of the regular data ports 0 - 15, or it can be the special dedicated serial port 16. Port 16 is the port that you use to program the BasicStamp. If you use port 16 you will have a fancy serial plug to use, but you won't be able to use the debug features of your BasicStamp. The sender and the receiver can use different ports.

SERIN and SEROUT

To send serial output, we use the SEROUT command. If we want to read serial data, we use the SERIN command. Because serial can send bits one after the other, we can send long data arrays at once, in addition to sending out single data bytes. We can send entire strings or arrays, if needed.

Wikiversity:Introduction to Robotics

{{:Wikiversity:Introduction to Robotics}}

Version 1.3, 3 November 2008 Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. <http://fsf.org/>

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

0. PREAMBLE

The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.

We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.

1. APPLICABILITY AND DEFINITIONS

This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.

A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.

A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.

The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.

A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque".

Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.

The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.

The "publisher" means any person or entity that distributes copies of the Document to the public.

A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.

The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.

2. VERBATIM COPYING

You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.

3. COPYING IN QUANTITY

If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.

4. MODIFICATIONS

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

1. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.
2. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.
3. State on the Title page the name of the publisher of the Modified Version, as the publisher.
4. Preserve all the copyright notices of the Document.
6. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.
7. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice.
8. Include an unaltered copy of this License.
9. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.
10. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.
11. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.
12. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.
13. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified version.
14. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section.
15. Preserve any Warranty Disclaimers.

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.

5. COMBINING DOCUMENTS

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.

In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".

6. COLLECTIONS OF DOCUMENTS

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.

7. AGGREGATION WITH INDEPENDENT WORKS

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.

8. TRANSLATION

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.

If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

9. TERMINATION

You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.

However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.

10. FUTURE REVISIONS OF THIS LICENSE

The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document.

11. RELICENSING

"Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site.

"Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document.

An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.

The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.

To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3