COMPUTER PERIPHERALS
The brains of a robot don’t operate in a vacuum. They need to be connected to motors to make the robot move, arms and grippers to pick up things, lights and whistles to let
you know what is going on, along with different sensors that give the robot the ability to
understand its environment. Input is data passed from the environment sensors to the computer,
and output is the computer’s commands to the devices that do something. These
input and output (I/O) devices are called peripherals and usually require some kind of conditioning
or programming for the computer or microcontroller in the robot to be able to
process information.
This chapter discusses the most common and practical methods for interfacing real-world
devices to computers and microcontrollers. Many of the concepts presented in this
chapter are quite complex and repeated in other chapters, usually from a different perspective
to help you understand them better.
By far the most common use for inputs in robotics is sensors. There are a variety of sensors,
from the super simple to the amazingly complex. All share a single goal: providing the
robot with data it can use to make intelligent decisions. A temperature sensor, for example,
might help a robot determine if it’s too hot to continue a certain operation. Or an energy
watch robot might record the temperature as it strolls throughout the house, looking for
locations where the temperature varies widely (indicating a possible energy leak).
Broadly speaking, there are two types of sensors (see Fig. 14-1).
- Digital sensors provide simple on/off or true/false results or the stepped binary results
shown in Fig. 14-1. A switch is a good example of a digital sensor: either the switch is
open or it’s closed. An ultrasonic ranger, which returns a binary value, with each bit indicating
a specific distance, is also a digital sensor.
- Analog sensors provide a range of values, usually a voltage. In many cases, the sensor
itself provides a varying resistance or current, which is then converted by an external circuit
into a voltage. For example, when exposed to light the resistance of a CdS (cadmium
sulfide) cell changes dramatically. Built in a simple voltage divider, the voltage output
varies with the light striking the CDS cell.
Broadly speaking, in both digital and analog sensors, the input to the computer is a voltage
level. In the case of a digital sensor, the robot electronics are only interested in whether the
voltage bit value is a logical low (usually 0 V) or a logical high (usually 5 V). Digital sensors
can often be directly connected to a robot control computer without any additional interfacing
electronics.
In the case of an analog sensor, you need additional robot electronics to convert the varying
voltage levels into a form that a control computer can use. This typically involves using
an analog-to-digital converter, which is discussed later in this chapter.
14.1.2 EXAMPLES OF SENSORS
One of the joys of building robots is figuring out new ways of making them react to changes
in the environment. This is readily done with the wide variety of affordable sensors now
available. New sensors are constantly being introduced, and it pays to stay abreast of the
latest developments. Not all new sensors are affordable for the hobby robot builder, of
course—you’ll just have to dream about getting that $10,000 vision system. But there are
plenty of other sensors that cost much, much less; many are just a few dollars.
Part 6 of this book discusses many different types of sensors commonly available today
that are suitable for robotic work. Here is just a short laundry list to whet your appetite:
- Sonar range finder or proximity detector. Reflected sound waves are used to judge distances
or if a robot is close to an object. The detected range is typically from about a foot
to 30 to 40 ft.
- Infrared range finder or proximity. Reflected infrared light is used to determine distance
and proximity. The detected range is typically from 0 in to 2 or 3 ft.
- Light sensors. Various light sensors detect the presence or absence of light. Light sensors
can detect patterns when used in groups (called arrays). A sensor with an array of
thousands of light-sensitive elements, like a CCD video camera, can be used to construct
eyes for a robot.
- Pyroelectric infrared. A pyroelectric infrared sensor detects changes in heat patterns
and is often used in motion detectors. The detected range is from 0 to 30 ft and beyond.
- Speech input or recognition. Your own voice and speech patterns can be used to command
the robot.
- Sound. Sound sources can be detected by the robot. You can tune the robot to listen to
only certain sound wavelengths or to those sounds above a certain volume level.
- Contact switches. Used as touch sensors, when activated these switches indicate that
the robot has made contact with some object.
- Accelerometer. Used to detect changes in speed and/or the pull of the earth’s gravity,
accelerometers can be used to determine the traveling speed of a robot or whether it’s
tilted dangerously from center.
- Gas or smoke. Gas and smoke sensors detect dangerous levels of noxious or toxic fumes
and smoke.
- Temperature. A temperature sensor can detect ambient or applied heat. Ambient heat
is the heat of the room or air; applied heat is some heat (or cold) source directly applied
to the sensor.
14.2 Input and Output Methodologies
The robot’s computer controller requires input electrical connections for such things as
mode settings or sensors, as well as connections to outputs, for peripherals like motor control
or speech. The most basic input and output of a computer or microcontroller are two-state
binary voltage levels (off and on), usually between 0 and 5 V. Two types of interfaces
are used to transfer these high/low digital signals to the robot’s control computer.
14.2.1 PARALLEL INTERFACING
In a parallel interface, multiple bits of data are transferred at one time using (typically) eight
separate wires as shown in Fig. 14-2. Parallel interfaces enjoy high speed because more
information can be shuttled about in less time. A typical parallel interface is the printer port
on your personal computer; it sends data to the printer an entire byte (eight bits) at a time.
Characters are represented by different combinations of the eight-bit data (using ASCII
character codes).
14.2.2 SERIAL INTERFACING
The downside to parallel interfaces is that they consume a large number of input/output
lines on the robot computer or microcontroller. There are a limited number of I/O wires or
lines on the control computer; typically 16 or even fewer. If the robot uses two eight-bit parallel
ports, that leaves no I/O lines for anything else.
Serial interfaces, on the other hand, conserve I/O lines because they send data on a single
wire (as can be seen in Fig. 14-2). They do this by separating a byte of information into
its constituent bits, then sending each bit down the wire at a time, in single-file fashion.
There are a variety of serial interface schemes, using one, two, three, or four I/O lines.
Additional I/O lines are used for such things as timing and coordination between the data
sender and the data recipient.
A number of the sensors you may use with your robot have serial interfaces, and while
they appear to be more difficult to interface than parallel connections, they aren’t if you use
the right combination of hardware and software. The task of working with serial data is
made easier when you use a computer or microcontroller because software on the control
computer does all the work for you. The BASIC Stamp 2, for example, uses single commands
that provides a serial interface on any of its I/O lines.
14.3 Motors and Other Outputs
A robot uses outputs to take some physical action. Most often, one or more motors are
attached to the outputs of a robot to allow the machine to move. On a mobile robot, the
motors serve to drive wheels, which scoot the ’bot around the floor. On a stationary robot,
the motors are attached to arm and gripper mechanisms, allowing the robot to grasp and
manipulate objects.
Motors aren’t the only ways to provide motility to a robot. Your robot may use solenoids
to hop around a table, or pumps and valves to power pneumatic or hydraulic pressure systems.
No matter what system the robot uses, the basic concepts are the same: the robot’s
control circuitry (e.g., a computer) provides a voltage to the output, which controls interface
circuitry, allowing motors, solenoids, or pumps to be turned on. When the control voltage
changes, the output device stops.
14.3.1 OTHER COMMON TYPES OF OUTPUTS
Along with motors, some other types of outputs are used for the following purposes:
- Sound. The robot may use sound to warn you of some impending danger (“Danger, Will
Robinson. Danger!”) or to scare away intruders. If you’ve built an R2-D2–like robot
(from Star Wars fame), your robot might use chirps and bleeps to communicate with
you. Hopefully, you’ll know what “bebop, pureeep!” means.
- Voice. Either synthesized or recorded, a voice lets your robot communicate in more
human terms.
- Visual indication. Using light-emitting diodes (LEDs), numeric displays, or liquid crystal
displays (LCDs), visual indicators help the robot communicate with you in direct ways.
14.4 Sample Output Circuits
The most simple output circuit is the LED driver Fig. 14-3 in which one of the output
lines of the robot controller applies either a high or low voltage to turn on or off an LED.
The 470-ohm resistor is used to limit the amount of current passed through the LED to 5
to 6 mA.
Outputs typically drive heavy loads: motors, solenoids, pumps, and even high-volume
sound demand lots of current. The typical robotic control computer cannot provide more
than 15 to 22 mA (milliamps) of current on any output. That’s enough to power one or two
LEDs, but not much else. To use an output to drive a load, you need to add a power element
that provides adequate current. This can be as simple as one transistor, or it can be a
ready-made power driver circuit capable of running large, multi-horsepower motors. One
common power driver is the H-bridge, so called because the transistors used inside it are in
an H pattern around the motor or other load. The H-bridge can connect directly to the control
computer of the robot and provide adequate voltage and current to the load.
Fig. 14-4 through Fig. 14-8 show various approaches for doing this, including NPN transistor,
power MOSFET, discrete component H-bridge, single-package H-bridge, and
buffer circuits. All have their advantages and disadvantages, and they are described in
context throughout this book. See especially Chapter 20, “Working with DC Motors,”
and Chapter 21, “Working with Stepper Motors,” for more information on these power
drive techniques.
Switches and other strictly digital (on/off) sensors can be readily connected to control electronics.
Fig. 14-9 through Fig. 14-12 show a variety of techniques, including direct connection
of a switch sensor, an LED high/low voltage input and indicator, interface via a switch
debouncer, and interface via a buffer. The buffer is recommended to isolate the source of
the input from the control electronics.
14.5.1 INTERFACING FROM DIFFERENT VOLTAGE LEVELS
Some digital input devices may operate a voltage that differs from the control electronics.
Erratic behavior and even damage to the input device or control electronics could result if
you connected components with disparate voltage sources together. So-called logic translation circuits are needed for these kinds of interfaces. Several integrated circuits provide
these functions in off-the-shelf solutions. You can create most of the interfaces you need
using standard CMOS and TTL logic chips.
Fig. 14-13 shows how to interface TTL (5 V) to CMOS circuits that use different power
sources (use this circuit even if both circuits run under +5 vdc). Fig. 14-14 shows the same
concept, but for translating CMOS circuits to TTL circuits that use different power sources.
14.5.2 USING OPTO-ISOLATORS
Note that in both Fig. 14-13 and Fig. 14-14, the ground connection is shared. You may wish
to keep the power supplies of the inputs and control electronics totally separate. This is
most easily done using opto-isolators, which are readily available in IC-like packages. Fig. 14-15 shows the basic concept of the opto-isolator: the source controls a light-emitting
diode. The input of the control electronics is connected to a photodetector of the opto-isolator.
Note that since each side of the opto-isolator is governed by its own power supply, you
can use these devices for simple level shifting, for example, changing a +5 V signal to
+12 V, or vice versa.
14.5.3 ZENER DIODE INPUT PROTECTION
If a signal source may exceed the operating voltage level of the control electronics, you can
use a zener diode to clamp the voltage to the input. Zener diodes act like valves that turn on
only when a certain voltage level is applied. As shown in Fig. 14-16, by putting a zener
diode across the +V and ground of an input, you can basically shunt any excess voltage and
prevent it from reaching the control electronics.
Zener diodes are available in different voltages; the 4.7- or 5.1-V zeners are ideal for
interfacing to inputs. Use the resistor to limit the current through the zener. The wattage
rating of the zener diode you use depends on the maximum voltage presented to the input
as well as the current drawn by the input. For most applications where the source signal is
no more than 12 to 15 V, a quarter-watt zener should easily suffice. Use a higher wattage
resistor for higher current draws.
14.6 Interfacing Analog Input
In most cases, the varying nature of analog inputs means they can’t be directly connected
to the control circuitry of your robot. If you want to quantify the values from the input, you
need to use some form of analog-to-digital conversion (see the section “Using Analog-to-
Digital Conversion” later in this chapter for more information).
Additionally, you may need to condition the analog input so its value can be reliably measured.
This may include amplifying and buffering the input as described in this section.
14.6.1 VOLTAGE COMPARATOR
Before the robot’s controller responds to an input sensor’s analog voltage, it must reach
a specific threshold. Rather than converting the analog voltage to a binary value using an
analog-to-digital converter, the voltage from the input sensor can be compared against a
reference voltage and a simple binary value, indicating if the analog input is above or below
the reference passed to the robot’s controller.
The voltage comparator takes a linear, analog voltage and outputs a simple on/off
(low/high) signal to the control electronics of your robot. Fig. 14-17 shows a sample voltage
comparator circuit. The potentiometer is used to determine the trip point (reference voltage) of the comparator. To set the potentiometer, apply the voltage level you want to
use as the trip point to the input of the comparator. Adjust the potentiometer so the output
of the comparator just changes state.
Note that the pull-up resistor is used on the output of the comparator chip (LM339) used
in the circuit. The LM339 uses an open collector output, which means that it can pull the
output low, but it cannot pull it high. The pull-up resistor allows the output of the LM339
to pull high.
14.6.2 SIGNAL AMPLIFICATION
Many analog inputs provide on and off signals but not at a voltage high enough to be useful
to the control electronics of your robot. In these instances you must amplify the signal,
which can be done by using a transistor or an operational amplifier. The op-amp method
Fig. 14-18 is the easiest in most cases, and while the LM741 is probably the most referenced
op-amp, you should look around for different devices that have simpler power
input requirements (i.e., a single 5 V, which matches the power requirements of your
robot’s controller).
The control electronics of your robot may load down the input sources that you use. This is
usually caused by a low impedance on the input of the control electronics. When this happens,
the electrical characteristics of the sources change, and erratic results can occur. By
buffering the input you can control the amount of loading and reduce or eliminate any
unwanted side effects.
The op-amp circuit, as shown in Fig. 14-19, is a common way of providing high-impedance
buffering for inputs to control electronics. R1 sets the input impedance. Note
that there are no resistors wired to the op-amp’s feedback circuitry, as in Fig. 14-18. In
this case, the op-amp is being used in unity gain mode, which does not amplify the signal.
14.6.4 OTHER SIGNAL TECHNIQUES FOR OP-AMPS
There are many other ways to use op-amps for input signal conditioning, and they are too
numerous to mention here. A good source for simple, understandable circuits is the Engineer’s
Mini-Notebook: Op-Amp IC Circuits, by Forrest M. Mims III, available through
Radio Shack. No robotics lab (or electronics lab, for that matter) should be without Forrest’s
books.
14.6.5 COMMON INPUT INTERFACES
Fig. 14-20 and Fig. 14-21 are two basic, common interfaces for analog inputs. These can be
connected to analog-to-digital converters (ADC), comparators, buffers, and the like. The
most common interfaces are as follows:
- CdS (cadmium-sulfide) cells are, in essence, variable resistors controlled by light and not
a mechanical wiper. By putting a CdS cell in series with another resistor between the +V
and ground of the circuit Fig. 14-20), a voltage divider varying voltage is provided that
can be read directly into an ADC or comparator. No amplification is typically necessary.
- A potentiometer forms a voltage divider when connected as shown in Fig. 14-21. The
voltage varies from ground and +V. No amplification is necessary.
- The output of a phototransistor is a varying current that can be converted to a voltage
by using a resistor. (The higher the resistance is, the higher the sensitivity of the device.)
The output of a phototransistor is typically ground to close to +V, and therefore no further
amplification is necessary.
- Like a phototransistor, the output of a photodiode is a varying current. This output can
also be converted into a voltage by using a resistor (see Fig. 14-20). (The higher the resistance,
the higher the sensitivity of the device.) This output tends to be fairly weak—on
the order of millivolts instead of volts. Therefore, amplification of the output analog voltage
is usually required.

14.7 Analog-to-Digital Converters
Computers are binary devices: their digital data is composed of strings of 0s and 1s, strung
together to construct meaningful information. But the real world is analog, where data can
be almost any value, with literally millions of values between “none” and “lots”!
Analog-to-digital conversion is a system that takes analog information and translates it
into a digital, or more precisely binary, format suitable for your robot. Many of the sensors you will connect to the robot are analog in nature. These include temperature sensors,
microphones and other audio transducers, variable output tactile feedback (touch)
sensors, position potentiometers (the angle of an elbow joint, for example), light detectors,
and more. With analog-to-digital conversion you can connect any of them to your
robot.
There are a number of ways to construct an analog-to-digital converter, including successive
approximation, single slope, delta-sigma, and flash. For the most part, you will not
have to understand how the different ADCs work other than being able to read the data
sheet and understand how they interface to the analog input and robot controller and how
long the analog-to-digital conversion process takes.
14.7.1 HOW ANALOG-TO-DIGITAL CONVERSION WORKS
Analog-to-digital conversion (ADC) works by converting analog values into their binary
equivalents. In most cases, low analog values (like a weak light striking a photodetector)
might have a low binary equivalent, such as 1 or 2. But a high analog value might have a
high binary equivalent, such as 255 or even higher. The ADC circuit will convert small
changes in analog values into slightly different binary numbers. The smaller the change in
the analog signal required to produce a different binary number, the higher the resolution of
the ADC circuit. The resolution of the conversion depends on both the voltage span (0 to
5 V is most common) and the number of bits used for the binary value.
Suppose the signal spans 10 V, and 8 bits (or a byte) are used to represent various levels
of that voltage. There are 256 possible combinations of 8 bits, which means the span of
10 V will be represented by 256 different values. Given 10 V and 8 bits of conversion, the
ADC system will have a resolution of 0.039 V (39 mV) per step. Obviously, the resolution
of the conversion will be finer the smaller the span or the higher the number of bits. With a
10-bit conversion, for instance, there are 1024 possible combinations of bits, or roughly
0.009 V (9 mV) per step.
14.7.2 INSIDE THE SUCCESSIVE APPROXIMATION ADC
Perhaps the most commonly used analog-to-digital converter is the successive approximation
approach, which is a form of systematized “20 questions.” The ADC arrives at the digital
equivalent of any input voltage within the expected range by successively dividing the
voltage ranges by two, narrowing the possible result each time. Comparator circuits within
the ADC determine if the input value is higher or lower than a built-in reference value. If
higher, the ADC branches toward one set of binary values; if lower, the ADC branches to
another set.
While this sounds like a roundabout way, the entire process takes just a few microseconds.
One disadvantage of successive approximation (and some other ADC schemes) is that
the result may be inaccurate if the input value changes before the conversion is complete.
For this reason, most modern analog-to-digital converters employ a built-in sample-and-hold
circuit (usually a precision capacitor and resistor) that temporarily stores the value until
conversion is complete.
14.7.3 ANALOG-TO-DIGITAL CONVERSION ICS
You can construct analog-to-digital converter circuits using discrete logic chips—basically a
string of comparators strung together. An easier approach is a special-purpose ADC integrated
circuit. These chips come in a variety of forms besides conversion method (e.g., successive
approximation, discussed in the last section).
- Single or multiplexed input. Single-input ADC chips, such as the ADC0804, can
accept only one analog input. Multiplexed-input ADC chips, like the ADC0809 or the
ADC0817, can accept more than one analog input (usually 4, 8, or 16). The control circuitry
on the ADC chip allows you to select the input you wish to convert.
- Bit resolution. The basic ADC chip has an eight-bit resolution (the ADC08xx ICs discussed
earlier are all eight bits). Finer resolution can be achieved with 10-bit and more
chips, but they are not widely used or required in robotics.
- Parallel or serial output. ADCs with parallel outputs provide separate data lines for
each bit. (Ten and higher bit converters may still only have eight data lines; the converted
data must be read in two passes.) Serial output ADCs have a single output, and the data
is sent one bit at a time. Serial output ADCs are handy when used with microcontrollers
and single-board computers, where input/output lines can be scarce. In the most common
scheme, a program running on the microcontroller or computer clocks in the data
bits one by one in order to reassemble the converted value. The ADC08xx chips have
parallel outputs; the 12-bit LTC1298 has a serial output.
14.7.4 INTEGRATED MICROCONTROLLER ADCs
Many microcontrollers and single-board computers come equipped with one or more analog-to-digital converters built in. This saves you the time, trouble, and expense of connecting a
stand-alone ADC chip to your robot. You need not worry whether the ADC chip provides
data in serial or parallel form since all the data manipulation is done internally. Along with
this, you are usually given the option of either using the voltage applied to the microcontroller
as the high voltage range or the ADC or an external voltage (generally less than Vdd)
from your circuit, giving you the capability of measuring different voltage ranges accurately.
You just tell the system to fetch an analog input, and it responds when the conversion is
complete.
Fig. 14-22 shows a basic circuit for using the ADC0809, which provides eight analog
inputs and an eight-bit conversion resolution. The input you want to test is selected using a
three-bit control sequence—000 for input 1, 001 for input 2, and so on. Note the ~500
kHz time base, which can come from a ceramic resonator or other clock source or from a
resistor/capacitor (RC) time constant. If you need precise analog-to-digital conversion, you
should use a more accurate clock than an RC circuit.
14.8 Digital-to-Analog Conversion
Digital-to-analog conversion (DAC) is the inverse of analog-to-digital conversion. With a
DAC, a digital signal is converted to a varying analog voltage. DACs are common in some
types of products, such as audio compact discs, where the digital signal impressed upon the
disc is converted into a melody pleasing to the human ear.
At least in the robotics world, however, DACs are not as commonly used as ADCs, and
when they are, simpler approximation circuits are all that’s usually necessary. A common
technique is to use a capacitor and resistor to form a traditional RC time-constant circuit. A
digital device sends periodic pulses through the RC circuit. The capacitor discharges at a
more or less specified rate. The more pulses there are during a specific period of time, the
higher the voltage that will get stored in the capacitor.
The speed of DC motors is commonly set using a kind of digital-to-analog conversion.
Rather than vary the voltage to a motor directly, the most common approach is to use pulse
width modulation (PWM), in which a circuit applies a continuous train of pulses to the
motor. The longer the pulses are on, the faster the motor will go. This works because
motors tend to integrate out the pulses to an average voltage level; no separate digital-to-analog
conversion is required. See Chapter 20 for additional information on PWM with DC
motors.
You can accomplish digital-to-analog conversion using integrated circuits specially
designed for the task. The DAC08, for example, is an inexpensive eight-bit digital-to-analog
converter IC that converts an eight-bit digital signal into an analog voltage.
14.9 Expanding Available I/O Lines
A bane of the microcontroller- and computer-controlled robot is the shortage of input/output
pins. It always seems that your robot needs one more I/O pin than the computer or
microcontroller has. As a result, you think you either need to drop a feature or two from the
robot or else add a second computer or microcontroller.
Fortunately, there are alternatives. Perhaps the easiest is to use a data demultiplexer, a
handy device that allows you to turn a few I/O lines into many. Demultiplexers are available
in a variety of types; a common component offers three input lines and eight output lines.
You can individually activate any one of the eight output lines by applying a binary control
signal on the three inputs.
Table 14-1 shows which input control signals correspond to which selected outputs.
The demultiplexer includes the venerable 74138 chip, which is designed to bring the
selected line low, while all the others stay high. One caveat regarding demultiplexers: only
one output can be active at any one time. As soon as you change the input control, the old
selected output is deselected, and the new one is selected in its place.
TABLE 14-1 Binary Demultiplexer Input to Output Device Selection |
INPUT CONTROL |
SELECTED OUTPUT |
|
000 |
0 |
001 |
1 |
010 |
2 |
011 |
3 |
100 |
4 |
101 |
5 |
110 |
6 |
111 |
7 |
|
One way around this is to use an addressable latch such as the 74259; another way is to
use a serial-to-parallel shift register, such as the 74595. The 74595 chip uses three inputs
(and optionally a fourth, but for our purposes it can be ignored) and provides eight outputs.
You set the outputs you want to activate by sending the 74595 an eight-bit serial word as
shown in Table 14-2.
TABLE 14-2 Using the 74595 Serial-In/Parallel-Out Shift Register to Make
Specific Outputs Active |
SERIAL WORD IN |
SELECTED OUTPUT(s) |
|
00000001 |
0 |
00001001 |
0 and 3 |
01000110 |
1, 2, and 6 |
|
Fig. 14-23 shows how to interface to the 74595. In operation, software on your robot’s
computer or microcontroller sends eight clock pulses to the clock line. At each clock pulse,
the data line is sent one bit of the serial word you want to use. When all eight pulses have
been received, the latch line is activated. The outputs of the 74595 remain active until you
change them (or power to the chip is removed, of course).
If this seems like a lot of effort to expend just to turn three I/O lines into eight, many
microcontrollers (and some computers) used for robotics include a shiftout command that
does all the work for you. This is the case, for example, with the BASIC Stamp 2 (but not
the BASIC Stamp I), the BASICX-24, and several others. To use the shiftout command,
you indicate the data you want to send and the I/O pins of the microcontroller that are
connected to the 74595. You then send a short pulse to the latch line, and you’re done!
A key benefit of the 74595 is that you can cascade them to expand the I/O options even
more.
There are still other ways to expand I/O lines, including serial peripheral interface (SPI),
the Dallas 1-Wire protocol, and the 82C55. Several of the more commonly used systems
were introduced earlier in this chapter. If your computer or microcontroller supports one or
more of these systems, you may wish to investigate using these systems in case you find you
are running out of I/O lines for your robot.
14.10 Bitwise Port Programming
Controlling a robot typically involves manipulating one or more input/output lines (bits) on
a port attached to a computer or built into a microcontroller. A common layout for an I/O
port is eight bits, comprising eight individual connection pins. This is the same general layout
as the parallel port found on IBM PC-compatible computers, which provides eight data
lines for sending characters to a printer or other device (along with a few additional input
and output lines used for control and status).
The design of the typical microcontroller or computer, as well as the usual program
tools for it, do not make it easy to directly manipulate the individual bits of a port. Rather,
you must manipulate the whole port all at once and, in doing so, hopefully alter only the
desired bits. The alternative is to send a whole value—from 0 to 255 for an eight-bit port,
and 0 to 15 for a four-bit port—to the port at the same time. This value corresponds to
the bits you want to control. For example, given an eight-bit port, the number 54 in
binary is 00110110.
Fortunately, with a little bit of programming it’s not hard to convert numeric values
into their corresponding bits, and vice versa. Each programming language provides a different
mechanism for these procedures, and what follows are some simple approaches
using PBASIC. Other languages offer more robust bit-handling operators that you can
take advantage of. The sample code that follows is meant more to teach you the fundamentals
than to be applied directly with a robot. Take the ideas and adapt them to your
particular case.
14.10.1 MASKING VALUES BY ANDing
It is not uncommon to have to manipulate the individual bits of a computer or microcontroller
port. Quite often, you will find that the bits are not conveniently placed within bytes
for easy manipulation. When working with PBASIC (and other microcontroller programming
languages), individual bits can be easily manipulated, regardless of which line it comes
in on. For example, declaring an input line on pin12 of a BS2 is accomplished by using the
statement
SwitchIn var INS.bit12
and can be manipulated like any other bit in PBASIC
A = SwitchIn & 1
Quite often, however, it is not possible or practical to address each individual bit. Rather,
you must read in an entire register and then mask off the bits that you would like to access
as well as shift them down so they are zero-based for easy manipulation. In these cases,
you will have to AND the bits with a number of set bits and then shift them up or down
depending on the requirements of the application. In the following example program,
three bits are input to the BS2, they are incremented by 1 and then output on three different
lines:
14.10.2 CONVERTING A VALUE INTO A BINARY-FORMAT STRING
Numeric values can be readily converted into a string of 0s and 1s by testing to see which
power of two bits are set in the value.
14.10.3 SUMMING BITS INTO A DECIMAL VALUE
You will have plenty of occasions to convert a set of binary digits into a decimal value. This
can be accomplished using the reverse of the previous program:
To learn more about . . . |
|
Read |
Motor specifications |
|
Chapter 19, “Choosing the Right Motor” |
Interfacing circuitry to DC motor loads |
|
Chapter 20, “Working with DC Motors” |
Computers and microcontrollers for robotic control |
|
Chapter 12, “An Overview of Robot ‘Brains’ ” |
Input and output |
|
Chapter 15, “The BASIC Stamp 2 Microcontroller” |
Interfacing sensors |
|
Part 6, “Sensors and Navigation” |