0% found this document useful (0 votes)
101 views154 pages

Basic Analog and Digital

fdsfgdfgdfdc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views154 pages

Basic Analog and Digital

fdsfgdfgdfdc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

Basic Analog and Digital

Student Guide for Experiments #1 through #8

Version 1.1

Note regarding accuracy of this text:


Many efforts were taken to ensure accuracy of this text and the
experiments, but the potential for errors still exist. If you find errors
or any subject requiring additional explanation please report this to
[email protected] so we can continue to improve the
quality of our documentation.
Warranty

Parallax warrants its products against defects in materials and workmanship for a period of 90 days. If you discover a defect, Parallax
will, at its option, repair, replace, or refund the purchase price. Simply call for a Return Merchandise Authorization (RMA) number,
write the number on the outside of the box and send it back to Parallax. Please include your name, telephone number, shipping
address, and a description of the problem. We will return your product, or its replacement, using the same shipping method used to
ship the product to Parallax.

14-Day Money Back Guarantee


If, within 14 days of having received your product, you find that it does not suit your needs, you may return it for a full refund. Parallax
will refund the purchase price of the product, excluding shipping / handling costs. This does not apply if the product has been altered
or damaged.

Copyrights and Trademarks


This documentation is copyright 1999 by Parallax, Inc. BASIC Stamp is a registered trademark of Parallax, Inc. If you decided to use the
name BASIC Stamp on your web page or in printed material, you must state that "BASIC Stamp is a registered trademark of Parallax,
Inc." Other brand and product names are trademarks or registered trademarks of their respective holders.

Disclaimer of Liability
Parallax, Inc. is not responsible for special, incidental, or consequential damages resulting from any breach of warranty, or under any
legal theory, including lost profits, downtime, goodwill, damage to or replacement of equipment or property, and any costs or
recovering, reprogramming, or reproducing any data stored in or used with Parallax products. Parallax is also not responsible for any
personal damage, including that to life and health, resulting from use of any of our products. You take full responsibility for your BASIC
Stamp application, no matter how life-threatening it may be.

Internet Access
We maintain internet systems for your use. These may be used to obtain software, communicate with members of Parallax, and
communicate with other customers. Access information is shown below:

E-mail: [email protected]
Ftp: ftp.parallaxinc.com and ftp.stampsinclass.com
Web: http://www.parallaxinc.com and http://www.stampsinclass.com

Internet BASIC Stamp Discussion List


We maintain two e-mail discussion lists for people interested in BASIC Stamps. The BASIC Stamp list server includes engineers,
hobbyists, and enthusiasts. The list works like this: lots of people subscribe to the list, and then all questions and answers to the list are
distributed to all subscribers. Its a fun, fast, and free way to discuss BASIC Stamp issues and get answers to technical questions. To
subscribe to the BASIC Stamp list, send e-mail to [email protected] and write subscribe stamps in the body of the
message. This list generates about 40 messages per day.

The Stamps in Class list is for students and educators who wish to share educational ideas. To subscribe to this list go to
http://www.stampsinclass.com and look for the E-groups list. This list generates about 5 messages per day.
Contents

Table of Contents

Preface ............................................................................................................................................. 5
Audience and Teachers Guides.......................................................................................................................................... 5
Copyright and Reproduction .............................................................................................................................................. 6

Experiment #1: Analog Voltage and Binary States ................................................................................ 7


Parts Required ....................................................................................................................................................................... 8
The Potentiometer - A Source of Variable Voltage......................................................................................................10
The LM358 Op-Amp ............................................................................................................................................................11
Build It....................................................................................................................................................................................13
Program It.............................................................................................................................................................................14
About the Code....................................................................................................................................................................15
Troubleshooting...................................................................................................................................................................16
The Output ............................................................................................................................................................................17
About the Comparator.......................................................................................................................................................18
What have I learned?..........................................................................................................................................................19
Questions ..............................................................................................................................................................................20
Challenge! .............................................................................................................................................................................20
Why did I learn it? ...............................................................................................................................................................21
How can I apply this? ..........................................................................................................................................................21

Experiment #2: Introduction to Bit Crunching................................................................................... 23


Parts Required .....................................................................................................................................................................23
Build It....................................................................................................................................................................................24
Program It.............................................................................................................................................................................26
The Output ............................................................................................................................................................................27
About the Code....................................................................................................................................................................28
Counting in Binary...............................................................................................................................................................31
Parallel and Serial Transmission ......................................................................................................................................33
Reprogramming to Send Serial Data ..............................................................................................................................33
The Output ............................................................................................................................................................................34
About the Code....................................................................................................................................................................36
What have I learned?..........................................................................................................................................................38
Questions ..............................................................................................................................................................................39
Challenge! .............................................................................................................................................................................39
Why did I learn it? ...............................................................................................................................................................40
How can I apply this? ..........................................................................................................................................................40

Basic Analog and Digital Student Guide Version 1.0 Page 1


Contents

Experiment #3: Build Your Own Digital DC Voltmeter ......................................................................... 41


Parts Required .....................................................................................................................................................................42
The Potentiometer - A Source of Variable Voltage......................................................................................................42
The ADC0831 Integrated Circuit - An 8-bit Analog to Digital Converter.................................................................43
Build It....................................................................................................................................................................................45
Program It.............................................................................................................................................................................45
The Output ............................................................................................................................................................................47
About the Code....................................................................................................................................................................47
Interpreting the Output .....................................................................................................................................................51
Binary to Decimal Conversion Revisited.........................................................................................................................52
Calculate Voltage.................................................................................................................................................................53
The Output ............................................................................................................................................................................57
About the Code....................................................................................................................................................................58
Resolution .............................................................................................................................................................................59
Calibration ............................................................................................................................................................................60
What have I learned? ..........................................................................................................................................................61
Questions ..............................................................................................................................................................................62
Challenge! .............................................................................................................................................................................62
Why did I learn it?................................................................................................................................................................63
How can I apply this? ..........................................................................................................................................................63

Experiment #4: Basic Digital to Analog Conversion............................................................................. 65


Build a Resistive Ladder Network ....................................................................................................................................65
Parts Required .....................................................................................................................................................................66
Build It....................................................................................................................................................................................68
Program It.............................................................................................................................................................................69
The Output ............................................................................................................................................................................71
About the Code....................................................................................................................................................................71
Modify the Code ..................................................................................................................................................................73
Addressing ............................................................................................................................................................................74
The Voltage Follower ..........................................................................................................................................................77
What did I learn? .................................................................................................................................................................81
Questions ..............................................................................................................................................................................82
Challenge! .............................................................................................................................................................................82
Why did I learn it?................................................................................................................................................................83
How can I apply this? ..........................................................................................................................................................83

Page 2 Basic Analog and Digital Student Guide Version 1.0


Contents

Experiment #5: Time Varying Signals................................................................................................. 85


Parts Required .....................................................................................................................................................................86
Program It.............................................................................................................................................................................87
The Output - A Triangle Wave...........................................................................................................................................88
About the Code....................................................................................................................................................................91
The Pulse Train.....................................................................................................................................................................93
The Sine Wave and Pulse Width Modulation .................................................................................................................97
Reprogram the Circuit for Musical Notes ......................................................................................................................98
The Output ............................................................................................................................................................................99
About the Code....................................................................................................................................................................99
What have I learned?........................................................................................................................................................100
Questions ............................................................................................................................................................................101
Challenge.............................................................................................................................................................................101
Why did I learn it? .............................................................................................................................................................102
How can I apply this? ........................................................................................................................................................102

Experiment #6: Recording Data Frequency ..................................................................................... 103


Parts Required ...................................................................................................................................................................103
Build It..................................................................................................................................................................................104
Program It...........................................................................................................................................................................106
About the Code..................................................................................................................................................................106
The Output ..........................................................................................................................................................................107
Program It...........................................................................................................................................................................109
About the Code..................................................................................................................................................................112
What have I learned?........................................................................................................................................................113
Questions ............................................................................................................................................................................114
Challenge! ...........................................................................................................................................................................114
Why did I learn it? .............................................................................................................................................................115
How can I apply this? ........................................................................................................................................................115

Experiment #7: Digital to Analog the Easy Way Using PWM................................................................117


Parts Required ...................................................................................................................................................................121
Build It..................................................................................................................................................................................121
Program It...........................................................................................................................................................................124
The Output ..........................................................................................................................................................................124
What have I learned?........................................................................................................................................................129
Questions ............................................................................................................................................................................130
Challenge! ...........................................................................................................................................................................130
Why did I learn it? .............................................................................................................................................................131

Basic Analog and Digital Student Guide Version 1.0 Page 3


Contents

Experiment #8: Light Meter Gizmo.................................................................................................. 133


Parts Required ...................................................................................................................................................................136
Build It..................................................................................................................................................................................136
Program It...........................................................................................................................................................................138
The Output ..........................................................................................................................................................................139
Do the Math........................................................................................................................................................................140
What have I learned? ........................................................................................................................................................143
Questions ............................................................................................................................................................................144
Challenge! ...........................................................................................................................................................................144
Why did I learn it?..............................................................................................................................................................145
How can I apply this? ........................................................................................................................................................145

Appendix A: Parts Listing and Sources ............................................................................................ 147


Appendix B: Resistor Color Code......................................................................................................151

Page 4 Basic Analog and Digital Student Guide Version 1.0


Preface

Preface
The personal computer brought in a whole new era of electronic sophistication. With it, we have
immense amounts of digital computing power located right at our desk. Computers work well when they are
connected to each other, and digital data can be transferred quite reliably from machine to machine.
However, the minute you wish to connect a digital computer to some real world device (such as a
wind speed indicator or fuel level sensor) you need to design a circuit that interfaces an analog device to the
digital computer. In many cases, this involves the conversion from an analog voltage to a digital
representation of that voltage.
This set of Stamps in Class experiments will explore many of the basic principles of interfacing analog
devices to digital microcontrollers. Many times this involves the use of easy-to-use commands built right into
the BASIC Stamp, and at other times requires the use of a an analog to digital converter.
Why should we be interested in converting from analog to digital? Many different aspects of our lives
are dependent upon this conversion process. Some are not too critical to our survival like compact disc
players, telephone systems, and music. Others, however, might be critical. Medical equipment and sensors
often require analog to digital and digital to analog conversion.
The Basic Analog and Digital curriculum will be revised and updated continually based on feedback
from students and educators. If you would like to author an addition to this curriculum, or have ideas for
improvements, always send them to [email protected]. We'll do our best to integrate your ideas
and assist you with whatever technical support, sales support, or on-site training you need.

Audience and Teachers Guide


The audience for this text is ages 17 and above. Effective during the first publication of this text in
August, 1999, there is no Teacher's Guide edition planned. If a Teacher's Guide is to be published it would likely
be available the first part of year 2000. The answers to these experiments present no impossible or very
difficult technical hurdles, and could be solved with a bit of patience.

Basic Analog and Digital Student Guide Version 1.0 Page 5


Preface

Copyright and Reproduction


Stamps in Class lessons are copyright Parallax 1999. Parallax grants every person conditional
rights to download, duplicate, and distribute this text without our permission. The condition is that this text
or any portion thereof, should not be duplicated for commercial use resulting in expenses to the user beyond
the marginal cost of printing. That is, nobody would profit from duplication of this text. Preferably, duplication
would have no expense to the student. Any educational institution wishing to produce duplicates for their
students may do so without our permission. This text is also available in printed format from Parallax.
Because we print the text in volume, the consumer price is often less than typical xerographic duplication
charges. This text may be translated to any foreign language with the permission of Parallax, Inc.

Authors
The primary author and developer of this curriculum is Andrew Lindsay of California State University,
Sacramento. Several concepts in the Basic Analog and Digital curriculum were developed for Parallax by I-
Four of Grass Valley, California. Mr. Lindsay thanks the Parallax technical support team, in particular Russ
Miller, Jeff Martin, and John Barrowman for their project ideas and technical assistance and Ken Gracey for
editing.

Page 6 Basic Analog and Digital Student Guide Version 1.0


Experiment #1: Analog Voltage and Binary States

Experiment #1: This series of experiments introduces analog and digital


electronics. What's that mean? In Whats a Microcontroller?
Analog Voltage and we learned that analog is a continuously variable value.
Binary States Another way to think about it is that analog electronics is
analogous to nature.

There are lots of continuously variable values in nature, such as motion, light level, and sound. The position of
a door as it swings open is a good example of a continuously variable value. As a door swings from all the way
closed to all the way open, it visits every value in between. At one instant during its travel, it is 1/3 of the way
open. At another instant, it is 1/2 way open, and so on.

Digital simply means represented by digits. Think about how many


times each day you encounter analog values that are represented
Volt/Voltage: with digits. The temperature is 79.8 degrees. The speed limit is 45
The Volt is a fundamental unit of miles per hour, etc. Not surprisingly, digital electronics represents
electrical measurement named after 18th values with digits.
century physicist Allesandro Volta, and a
measurement in Volts is referred to as
voltage. The term digital is also used when referring to binary devices such as
the circuitry that makes a calculator work, the microprocessor in a
Most of us encounter this unit of computer, and the BASIC Stamp microcontroller. It's true - they are
measurement when buying batteries
such as the 9 Volt (DC) battery that can all digital devices. Binary is a type of digital, and it uses two digits, 0
be used to power the Board of and 1.
Education. Inside a battery there are
two chemical reactions, which are The experiments in Whats a Microcontroller were mostly about
separated from each other by a barrier. using the BASIC Stamp in binary applications. This series will focus
One of the reactions creates a surplus or
electrons and the other creates a mostly on using the BASIC Stamp in analog applications. This first
shortage of them. experiment introduces the concept of analog voltage.
The electron surplus and shortage sides In this first experiment, we'll build a circuit that produces an analog
of the barrier are connected to the
negative and positive terminals of the voltage at its output. Remember that analog voltage is continuously
battery respectively. Given a pathway variable. The circuit will be adjustable so that it can produce an
around the barrier, the electrons have output anywhere between 0 and 5 Volts. We'll also build a circuit
the potential to do work to get from the called a voltage follower that uses this analog voltage to drive an LED
negative to the positive terminal. The
Volt is a measure of this potential to do
circuit.
work. The Volt is also referred to as a
unit of electric potential. The analog voltage will also be connected to one of the BASIC Stamp
I/O pins set to input mode. This binary input can actually be used to
measure small variations in the analog voltage. PBASIC will be used

Basic Analog and Digital Student Guide Version 1.0 Page 7


Experiment #1: Analog Voltage and Binary States

to program the BASIC Stamp to drive a binary LED circuit, which will indicate when these variations have been
detected.

The Debug window is also a useful tool for displaying data the BASIC Stamp collects and sends. It will be used
to monitor the binary value that the input pin receives as the analog voltage is varied.

For each experiment you will need a BASIC Stamp II and a


Board of Education connected to an IBM-compatible PC with
Parts Required DOS 2.0 or higher, Win95/98/NT4.0 running the BASIC Stamp
editor software. In addition, you'll need the following parts for
this experiment:

(2) 470 ohm resistors


(2) Red LEDs
Circuit Schematic: (1) 100 kW potentiometer.
Often referred to as a schematic, (6) Jumper wires.
a circuit schematic is a map that
uses symbols to show the
(1) LM358 op-amp
components in a circuit and how
they are connected. The Throughout this series of experiments, we will build circuits from circuit
components are represented by schematics. One of the keys to learning how to read circuit schematics is
symbols such as the one that learning what each symbol on the schematic means. It's also important to
represents the LED in Figure 1.1.
learn how to connect a part from the Analog and Digital Parts Kit to the
Board of Education based on its circuit symbol in a schematic.

Figure 1.1 shows the circuit symbol for an LED on the left and a drawing of an LED from the parts kit on the
right. It also shows how the pins on an LED correspond to the terminals on the circuit symbol.

Page 8 Basic Analog and Digital Student Guide Version 1.0


Experiment #1: Analog Voltage and Binary States

Flat spot on
plastic part of
+ - LED indicating
Figure 1.1: LED Circuit the cathode.
Symbol Compared to the Cathode
Component
LED

Anode

Figure 1.2 shows a drawing of a resistor below its circuit symbol. The circuit symbol typically has the
resistance value written below or next to it. The colored stripes on the part drawn below the symbol
indicate its value, which is measured in Ohms. The omega symbol () is used to denote the Ohm. You can use
Appendix C to convert the color codes on the resistor to resistance values.

Figure 1.2: Resistor Circuit Symbol


and Corresponding Component 470

For your information:


Ohm's Law
Current/Amp: When a resistor is used to provide a pathway between the negative and positive
Current happens when electrons terminals of a battery, you have an electric circuit with voltage, resistance, and
travel from point A to point B. current. Ohm's Law relates the three quantities as follows:
Direct current is what happens
when you give the surplus V=IR
electrons in the negative terminal
of a battery a pathway to get to V is the voltage measured in Volts, I is the current measured in Amps, and R is the
the positive terminal. The Amp is resistance measured in Ohms.
the measurement of how many The Other Guys
electrons per second are traveling Ever notice that Volt, Amp, and Ohm all start with capital letters? That's because
they are named after some of the people who made significant discoveries about
electricity. We already know who the Volt is named for; what about the other guys?
The Amp, also called the Ampere, is named after 18th century physicist Andr Marie
Ampre. The Ohm is named after 19th century physicist Georg Simon Ohm.

Basic Analog and Digital Student Guide Version 1.0 Page 9


Experiment #1: Analog Voltage and Binary States

The Potentiometer - A Source of Variable Voltage

The potentiometer (pot) has 3 pins on its underside that get plugged into the Board of Education. On the
topside, it has a knob you can twist to adjust it. In this experiment, we will use variable resistance to get a
variable voltage output. Figure 1.3 shows how the pins on the underside of the pot from the parts kit
correspond to the circuit symbol.

Figure 1.3: Potentiometer


Circuit Symbol and Component

POT

Figure 1.4 shows what happens inside the pot as it is adjusted. The jagged line represents a resistive element,
typically made of carbon. One end of the resistive element is wired to Vdd on the Board of Education, and the
other end is wired to Vss. The middle of the three terminals is connected to the wiper, and its where the
variable output voltage is measured. The wiper stays in contact with the carbon element as it moves.

As the wiper gets closer to Vdd, the voltage measured at the wiper terminal will approach the value of Vdd,
which is 5 Volts. Likewise, when the wiper is closer to Vss, the voltage at the wiper terminal will be closer to
Vss, which is 0 Volts. As the wiper terminal travels between Vdd and Vss, the output measured at the wiper
terminal varies between these two values in a manner analogous a to door as it opens and closes.

Vdd

Figure 1.4: Potentiometer Wiper


showing how the wiper in a "Wiper" 100k
potentiometer travels along the Potentiometer
surface of the resistive element as
its adjusted.

Vss

Page 10 Basic Analog and Digital Student Guide Version 1.0


Experiment #1: Analog Voltage and Binary States

The LM358 Op-amp

An op-amp (operational amplifier) is a building block commonly used in analog circuits. Figure 1.5 shows the
circuit symbol and block diagram for the LM358 op-amp used in this experiment. The op-amp circuit used in
this experiment is called a voltage follower because the same voltage comes out as goes in. In other words,
the voltage at the output "follows" the voltage at the input. The reason it's used in the circuit in this
experiment is to electrically separate a potentiometer circuit from an LED circuit. We'll learn more about the
usefulness of a voltage follower in Experiment #4.

Figure 1.5: LM358 op-amp "index" mark


pin #1
The circuit symbol has numbers on each of
its terminals that correspond to the
numbers on the block diagram. Output A V+
1 8
LM358
The block diagram is a top-view of the part 2 8
Inverting A
Output B
from your parts kit with the circuit - Input A 2 - +
7
symbols for the two op-amps in the IC A
+ 1
B
drawn in. 3 LM358 -

+
4 Inverting
3 6 Input B
Make sure to note the location of pin 1 op-amp
Non-Inverting
and the index mark when you place the GND
5 Input B
4
LM358 on the breadboard. Improper
wiring can damage an op-amp. Circuit Symbol Block Diagram

IMPORTANT: Disconnect the Board of Education's power source while you build the circuit.

The Board of Education

Figure 1.6 shows the remaining circuit symbols used in the first experiment and where to find them on the
Board of Education. The symbol for Vdd is the positive 5 Volt supply for the BASIC Stamp and the Board of
Education. There are 4 sockets along the top side of the breadboard to the left for making connections to
Vdd.

Next, the ground symbol is used for Vss. This is the reference terminal for taking measurements, and it's
considered to be 0 Volts compared to all other voltages on the Board of Education. The four sockets for
connecting jumper wires to Vss along the top of the breadboard to the right.

There is a row of fifteen sockets along the left side of the breadboard for connecting to the BASIC Stamp I/O
pins. Each I/O pin has a label. I/O pin P0 is connected to the bottom left socket. Pin P1 is the next socket up,
and above that socket is the connection to pin P2, and so on through pin P15 at the top left.

Basic Analog and Digital Student Guide Version 1.0 Page 11


Experiment #1: Analog Voltage and Binary States

Vdd

P15 Vss

Figure 1.6: Board of


Education Circuit Symbols
and where to find them on
the Board of Education.
Also shown is how each row
of 5 sockets on the
breadboard is electrically
connected underneath. Rows of 5 sockets
are connected
underneath the
breadboard.
P2
P1
P0

Figure 1.6 also shows some samples of 5 socket wide rows that are electrically connected underneath the
breadboard. There are 34 of these 5 socket wide rows arranged in the two columns on the breadboard. If you
want to connect two jumper wires to each other, you can just plug them into the same row of 5. Then the
wires are electrically connected. Likewise, if you want to connect a one or more wires to the terminal of a
part, just plug them into the same row on the breadboard and they'll be connected.

Page 12 Basic Analog and Digital Student Guide Version 1.0


Experiment #1: Analog Voltage and Binary States

Build the circuit according to the schematic in Figure 1.7. This schematic is
Build It like a list of connections between circuit symbols. Try to use this list to build
the circuit. Here is a partial list of the connections shown in the schematic:

The wiper terminal of the 100 k pot is connected to pin 3 of the LM358 op-Amp.
Pin 2 of the LM358 is connected to pin 1 of the LM358.
Pin P7 of the BASIC Stamp is connected to the wiper terminal of the pot.
Pin 8 of the LM358 is connected to Vdd on the Board of Education.
Pin 4 of the LM358 is connected to Vss on the Board of Education.

Keep following the schematic like a list and you'll have the circuit built in no time.
Pot with analog
Figure 1.7: Circuit Schematic. output from Op-Amp voltage Analog LED Binary LED
Remember to treat this schematic like wiper terminal follower circuit output output.
a list of connections for building your
circuit.

Although this circuit only has a few


parts, it actually has 4 separate sub Vdd
circuits, and each has a different Vdd P12
function as shown. P7

2 8
The Potentiometer is what makes the -
analog output. The op-amp is wired 100k
A
1
+
to function as a voltage follower. The POT 3 4 LM358
voltage follower drives the analog LED 470 470
output. Then there's a separate
circuit that uses a BASIC Stamp I/O pin
to drive an LED.
Vss Vss Vss Vss

Basic Analog and Digital Student Guide Version 1.0 Page 13


Experiment #1: Analog Voltage and Binary States

Figure 1.8 shows a breadboard example of the schematic from Figure 1.7. For extra tips on building circuits on
the breadboard, consult Whats a Microcontroller, Experiment #1.

Figure 1.8 Breadboard Example:


Compare this breadboard example to the
schematic from Figure 1.6. Is the LM358
connected right? Does Vdd go to pin 8 and
does Vss go to pin 4?

It turns out that the answer to both


questions is yes. Vss is connected by a wire
to the leftmost terminal on the pot. Then
another wire connects from the leftmost
pot terminal to pin 4 on the LM358. 358
LM
Since you can follow a wire all the way
from pin 4 on the LM358 to the Vss
terminal, that means it is in fact connected
directly to Vss.

IMPORTANT: Pay careful attention to placing the LM358 so that the index mark is to the right, as shown on this
breadboard example. If you place it in reverse, the op-amp will be ruined after the battery or power supply is
connected to the Board of Education.

Program Listing 1.1 shows how PBASIC can be used to instruct the BASIC
Stamp to do several tasks. First, the BASIC Stamp monitors the state of
Program It the pin P7, which is set to function as an input. Remember, P7 is
connected to the wiper terminal of the pot.

Depending on the analog voltage level at pin P7, the BASIC Stamp
interprets the input as low or high (binary 0 or 1). As soon as the input to P7 receives the high signal, the
BASIC Stamp sends a high signal to the LED circuit via pin P12. When the input is low, a low signal is sent to the
output pin. The debug window is also used to monitor the state of pin P7.

Enter Program Listing 1.1 into the Stamp Editor, and save it under a convenient name, such as PL1_1R0.bs2.
This stands for Program Listing 1.1 Revision 0. Make sure the programming cable is properly connected to
your Board of Education and to the serial port on your computer. Also make sure that a battery or power
supply is properly connected, then run the program by pressing Alt-R if you're using the DOS version of the
Stamp Editor or ctrl-r if you're running the Windows version.

Page 14 Basic Analog and Digital Student Guide Version 1.0


Experiment #1: Analog Voltage and Binary States

'Program Listing 1.1


debug cls
input 7
output 12
loop:
out12 = in7
debug home, "The state of P7 is ", bin in7
goto loop

About the Code

The first line starts with an apostrophe. This means that it's a comment and not a PBASIC command.

'Program Listing 1.1

The BASIC Stamp needs to be told how to treat the I/O pins connected to the circuit. They can either be set to
function as inputs or outputs. This PBASIC commands sets BASIC Stamp I/O pin P7 to function as an input pin:

input 7

Likewise, I/O pin P12 functions as output with this command:

output 12

It's good to start the debug window and clear it before using it to display data. This way you will avoid
inadvertently displaying outputs from previous programs that were in the BASIC Stamp's memory. The debug
window starts automatically the first time it encounters the debug command in a PBASIC program. This
debug command clears the Debug window after it is opened:

debug cls

The rest of the program should be done over and over again, so this is a good place to put a label. A label ends
with a colon, and you can chose any word you want, except for reserved words. Consult the BASIC Stamp
Manual Version 1.9 for a list of reserved words. Lets use the word loop:

loop:

Later in the program, the command goto loop is entered. Each time the program gets to the goto loop
command, it returns this loop: label and starts executing instructions all over again.

Basic Analog and Digital Student Guide Version 1.0 Page 15


Experiment #1: Analog Voltage and Binary States

The next task is to make the LED connected to pin P12 light up when the voltage at P7 is high enough to qualify
as a binary high signal. In other words, if the input value measured at P7 is a binary-1, then the output at P12
should be set to binary-1. Although there are several ways to accomplish this, the easiest way is to set the
binary output value of pin P12 equal to the binary input value of pin P7.

out12 = in7

The debug commands can be used to display the signal levels received by an I/O pin functioning as an input in
the debug window. The debug command below prints three different items. When printing more than one
item with a debug command, always separate each of the items with commas.

debug home, "The state of P7 is ", bin in7

The first item displayed using the debug command is home, and it sends the cursor to the top-left "home"
position in the debug window. Note how home is followed by a comma to separate it from the next item. The
next item is a message in quotes: "The state of pin P7 is ". Whenever you want to display a text
message in the debug window, use quotes. The third item is bin in7, which tells the debug window to display
the binary input value measured at pin P7.

We want the BASIC Stamp keep checking the voltage at P7 over and over again. We also want the BASIC
Stamp to automatically update the LED and the debug window with the latest information from P7. This is
accomplished by repeatedly sending the program back to the loop: label we created earlier.

To send the program back to the loop: label to start the process all over again, use the command:

goto loop

Troubleshooting

Here are a few tips on things to check if your program doesn't work as expected.

It often takes a few tries to catch all the wiring mistakes and programming errors. The most common
mistake is program entry errors. In some cases the Stamp Editor will tell you there is a mistake. For
example if you misspelled a command, the Stamp Editor will not understand it, and it will tell you
which term it didn't understand by highlighting it and displaying a brief message.

Page 16 Basic Analog and Digital Student Guide Version 1.0


Experiment #1: Analog Voltage and Binary States

In other cases the program will run even though a line of code was typed incorrectly. For example
you might have typed p13 when you meant to type p12. With a mistake like this, when you try to run
the program, the LED connected to pin P12 won't light up when you expect it to because the high
signal gets sent to pin P13 instead.

Another common mistake is to plug a wire into the wrong socket on the breadboard. If an LED is not
turning on and off the way it should, and there are no programming errors, check the wiring. Also
check to make sure the cathode and anode of the LED are connected to the proper places. When an
LED is hooked up backwards it won't emit light.

If the information in the debug window appears garbled or nonsensical, try closing the debug window
and running the program again.

The Output

As you adjust the potentiometer, note how the LED at the voltage follower's analog output can vary in
brightness. Meanwhile the LED circuit driven by P12 either turns on or off. This characterizes the difference
between analog voltage and digital (binary) voltage.

The output displayed in the debug window should resemble the output shown in Figure 1.9. The state of P7 will
either be 0 or 1. Correspondingly, the LED circuit driven by P12 will either be off or on.

The state of P7 is 0
Figure 1.9: Debug Output for
Program Listing 1.1.

Adjust the potentiometer until you have found the threshold voltage. You will know when you've found it
because the debug window will indicate that the state of P7 skips back and forth between 0 and 1 with just
the slightest adjustment of the pot. Note the position of the potentiometer. After we build a DC Voltmeter in
the Experiment #3, we can find out how close we are to 1.4 Volts, which is the actual threshold voltage of a
BASIC Stamp I/O pin when it's functioning as an input.

Basic Analog and Digital Student Guide Version 1.0 Page 17


Experiment #1: Analog Voltage and Binary States

About the Comparator

Using PBASIC, we programmed the BASIC stamp to function as a comparator. A comparator is so named
because it's a circuit that compares its input voltage to a particular voltage, also called the threshold voltage.
If the input voltage is higher than the threshold voltage, the comparator sends a high signal at its output. If
the input to the comparator is below the threshold voltage, it sends a low signal.

In the case of our circuit and program, when the analog voltage at pin P7 is below 1.4 Volts, the BASIC Stamp
sends a low signal (0 Volts) at pin P12. When the analog voltage at pin P7 is above 1.4 Volts a high signal (5
Volts) is sent from pin P12. As you can see in the debug window, the BASIC Stamp interprets analog input
below 1.4 Volts as low (0) and input above 1.4 Volts as high (1).

Operating a comparator near the threshold voltage is interesting because you can make a small change in
voltage at a BASIC Stamp input pin, say from 1.3 to 1.5 Volts, and it results in a fairly large change, from 0 to 5
volts at the output.

Page 18 Basic Analog and Digital Student Guide Version 1.0


Experiment #1: Analog Voltage and Binary States

On the lines below, insert the appropriate words from the list
What have I on the left.
learned?

carbon A __________ shows circuit symbols connected to each other by lines. Each circuit
symbol corresponds to a component and the lines connecting the symbols work like a list
op-amp of connections that can be used to guide the construction of a working circuit on a
__________.
analog
An __________ is an analog building block that was used in this experiment as a voltage
threshold follower.
output In this experiment, the potentiometer was used as a source of __________ voltage.
The voltage at the wiper terminal of the potentiometer can be made to vary depending
schematic on where the wiper is in contact with the __________ element.
breadboard A comparator is a device that sends a binary output that depends on whether its analog
input is above or below a certain __________ voltage. A comparator has can react to a
small change in input voltage with a comparatively large change in __________ voltage.

Basic Analog and Digital Student Guide Version 1.0 Page 19


Experiment #1: Analog Voltage and Binary States

Questions

1. Circle the word that makes the sentence true: The input for a voltage follower is at the ( inverting / non-
inverting ) terminal of the op-amp in this experiment.

2. How do you tell the difference between the cathode and the anode on an LED from your parts kit?

3. If the threshold for a comparator is 2.5 Volts, and the input is at 1.5 Volts, what's the output going to be?

4. Explain what the command debug home does. What has to be done to display more than one item using
a single debug command.

5. What command would you use to set pin P8 to function as an input?

6. What does the colon after loop: indicate?

Challenge!

1. Add a second LED to the circuit to the Board of Education and use pin P11 to drive it in an inverted state.
In other words, when one LED is on, the other off. Hint: Add 1 to the output value at P11 to invert it.

2. Modify the code from Program Listing 1.1 so that the LED output flashes on and off when the
potentiometer output is above the threshold voltage of the BASIC Stamp input pin threshold voltage.
Hint: You can use the command pause 500 to make the program pause for half a second.

3. Modify Program Listing 1.1 to cause one LED to light up when the input voltage at pin P7 is above the
threshold voltage and the other LED to light up when the voltage at pin P7 is below threshold voltage.

Page 20 Basic Analog and Digital Student Guide Version 1.0


Experiment #1: Analog Voltage and Binary States

In this experiment, we compared a binary LED output to an analog


LED output. Aside from knowing that the voltage at the wiper
Why did I learn terminal had just crossed the threshold voltage, there was no way
it? of indicating the potentiometer's position or the LEDs brightness.
On the other hand, in the neighborhood of the threshold voltage,
fine variations in analog voltage could be detected.

Even with the limited amount of analog information provided by a binary input, we were able to develop a
device called a comparator, which has many applications in electronics design. As we'll discover in a later
experiment, the 555 timer in youre A & D parts kit can do some pretty amazing things. This is due in part to
two microscopic comparators in the chip.

In later experiments, we'll use the threshold voltage to measure


the frequency of sound for record and playback purposes. We can
How can I apply also build another type of analog to digital converter using a very
this? simple circuit, the BASIC Stamp and the concept of threshold
voltage. We'll use this technique to measure light intensity as well
as values for capacitors from the Analog and Digital parts kit.

Basic Analog and Digital Student Guide Version 1.0 Page 21


Experiment #1: Analog Voltage and Binary States

Page 22 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

Experiment #2: An important step in learning how to make the BASIC Stamp
process analog data is learning how to make it send and receive
Introduction to binary numbers. It's also important to understand how binary
Bit Crunching numbers work, and how to convert from a binary number to a
decimal number.

This experiment introduces some techniques for transmitting and receiving binary numbers using the BASIC
Stamp. In this experiment, we'll make a binary keypad for transmitting binary numbers to the BASIC Stamp.
The BASIC Stamp will also be programmed to process and display the binary numbers it receives. The binary
numbers will be displayed by LEDs as well as by the debug window. The debug window will also come in handy
for monitoring and displaying the binary numbers in decimal form.

In Whats a Microcontroller, we learned that binary is the number system used by microcontrollers that it
works with two digits, 0 and 1. The BASIC Stamp is part of an entire class of digital electronic devices that can
interpret 0 Volts as binary-0 and 5 Volts as binary-1.

Binary is useful for describing both states and numbers. In terms of states, the two digits in the binary number
system (0 and 1) can be used to describe off/on, closed/open, no/yes, etc. Combinations of binary digits can be
used to describe numbers. For example, the binary numbers 101, 110, and 111 describe the decimal numbers
5, 6, and 7. These numbers can in turn be used to describe analog information, such the position of a door as
it swings open and closed.

Gather these parts from your parts kit and let's get started.
Parts Required
(2) 470 ohm resistors
(2) 10 K ohm resistors
(2) Pushbutton switches
(2) Red LEDs
(misc.) wires

There's just one new part and circuit symbol to introduce for this experiment, the pushbutton in Figure 2.1.
Note how the each terminal on the circuit symbol corresponds to two pins on the part. If you want to connect
to a particular terminal shown on the symbol, you can connect to either (or both) of the two corresponding
pins on the part.

The open space in the circuit symbol indicates that the switch is normally open. When the two terminals of a
switch are not connected, the switch is referred to as an open circuit. Under normal circumstances (when the
pushbutton is not pressed), the circuit is open, thus the name normally open.

Basic Analog and Digital Student Guide Version 1.0 Page 23


Experiment #2: Introduction to "Bit Crunching"

Figure 2.1:
Pushbutton Circuit
Symbol Compared to
the Component PB Switch

Figure 2.2 shows the schematic for this experiment. Remember to


think of a schematic as a list of components and connections. For
Build It example, the anode of the LED on the right is connected to the P5
terminal on the Board of Education. The cathode is connected to
one terminal of a 470 resistor. The other pin on that same
resistor is connected to the Vss terminal on the Board of Education, and so on. Follow schematics faithfully
when constructing circuits.

Vdd Vdd

P4 P5

Figure 2.2: Schematic


featuring two pushbutton
circuits and two LED P0 P1
circuits.
10k 10k
470 470

Vss Vss Vss Vss

Page 24 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

Before making a PBASIC program telling the BASIC Stamp how to interface with this circuit, it's essential to
understand how the circuit works. The LED's are pretty straightforward. Set P4 high and the LED lights up; set
P4 low and the LED goes dark again. The LED circuit connected to P5 works the same way.

Now, what about the pushbuttons? Let's look at what pin P0 sees when the pushbutton is pressed, then not
pressed. When the pushbutton is pressed, P0 gets connected directly to Vdd, which is 5 Volts. P0 sees a high
signal. When the pushbutton is not pressed, P0 is connected to Vss (0 Volts) through the 10 k resistor. Then
P0 sees a low signal. This concept applies to both the pushbuttons shown in Figure 2.2.

Figure 2.3 shows a breadboard example of the circuit schematic. Of the two BASIC Stamp I/O pins used for
the pushbuttons, the left pin (P0) is connected to the pushbutton on the right. Likewise, the right pin (P1) is
connected to the pushbutton on the left. The reason the wires for the pushbuttons cross relates to the way
binary numbers are written, which will be explained later in this experiment.

Figure 2.3: Breadboard


Example. Entering binary
numbers on the pushbuttons
will be easiest if you orient the
Board of Education as shown.

Note that the left button is


connected to pin P1, and the
right button is connected to p0.

Basic Analog and Digital Student Guide Version 1.0 Page 25


Experiment #2: Introduction to "Bit Crunching"

Program Listing 2.1 makes the LED on the left in Figure 2.3 light up when the left pushbutton is pressed.
Likewise, the LED on the right lights up when the pushbutton on the right is pressed. The program also
displays the activity of the pushbuttons in the debug window.

Program It
Here is a more precise description of the program specifications
for the pushbuttons and LEDs.

When P0 receives a low signal, P5 should send a low signal.


When P0 receives a high signal, P5 should send a high signal.
When P1 receives a low signal, P4 should send a low signal.
When P1 receives a high signal, P4 should send a high signal.

The debug window can be used to display what the BASIC Stamp receives at pins P0 and P1. PBASIC
commands are used for displaying the binary values the BASIC Stamp receives as well as their decimal
equivalents.

Let's see how this can be done using PBASIC. Enter Program Listing 2.1 into the BAISC Stamp Editor, and save
it as PL2_1R0.bs2. This stands for Program Listing 2.1 Revision 0. Make sure the Board of Education has power
and the programming cables are properly connected, then run the program.

'Program Listing 2.1

a var bit
b var bit
d var nib

input 0
input 1

output 5
output 4

debug cls

loop:
a = in0
b = in1

Page 26 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

out4 = b
out5 = a
d = (2*b)+(1*a)
debug home, "State of pin P0 is ", bin a, cr
debug "State of pin P1 is ", bin b, cr, cr
debug "2-bit binary number:", cr
debug "P1 P0", cr
debug " ", bin b, " ", bin a, cr, cr
debug "Decimal equivalent: ", dec1 d, cr
goto loop

The Output

Here's how the program should work. When no pushbuttons are pressed, the debug output should match
Figure 2.4, and both LEDs should be off. Try pressing the button on the right (in Figure 2.3). Did the LED on the
right light up? Did the state of P0 in the debug window change to 1? Is the decimal equivalent 1? If so, it looks
like your circuit and program are working well so far.

State of pin P0 is 0
State of pin P1 is 0

2-bit binary number:


Figure 2.4: Debug Output for
Program Listing 2.1.
P1 P0
0 0

Decimal equivalent: 00

So how do you count from decimal-0 to decimal-3 using the binary pushbuttons? The 2-bit binary equivalent
of decimal-0 in a 2-bit binary number is 00. When you dont press either of the pushbuttons, the decimal
output is 0 in the debug window. When you press the right button, you get 01, which has a decimal equivalent
of 1. When you press the left button, you get 10, which has a decimal equivalent of 2. When you press both
pushbuttons, you get 11, which has a decimal equivalent of 3.

Basic Analog and Digital Student Guide Version 1.0 Page 27


Experiment #2: Introduction to "Bit Crunching"

About the Code

As with Program Listing 1.1, the first line starts with an apostrophe, so it's a comment, and BASIC Stamp
ignores it.

'Program Listing 2.1

Next, three variables are defined. Variables can be used to store values while the program is running. The
letters a and b are defined as variables that store 1-bit each. So, the variable a can store a single binary
digit, likewise with the variable b. The letter d is defined to be a variable that stores a "nibble" of binary
information.

a var bit
b var bit
d var nib

This segment of code uses commands introduced in Program


Listing 1.1. First, 2 I/O pins are declared inputs and two more
pins are declared outputs. Then the debug window is opened and
Memory and Food cleared. The loop: label defines a routine.
A bit of memory can store one binary
digit, either a 0 or a 1.
input 0
A nibble of memory stores 4-bits.
input 1
A byte (pronounced bite) stores 8-bits.
output 5
A word stores 16 bits.
output 4
Since a bit, a nibble, and a byte, all sound like
debug cls
references to eating food, perhaps a better
loop:

Next, we need to check the state of the pushbuttons by checking the input at pins P0 and P1. The first of these
two commands sets the bit variable a equal to the state measured at pin P0. The second command sets the
bit variable b equal to the state measured at pin P1.

a = in0
b = in1

Next, we need to set the output at pin P4 equal to the input taken at pin P1. The LED on the left which is
connected to P4 will light up when the button on the left, which is connected to P1, is pressed. Likewise, we
need to set the output at pin P5 equal to the input measured at pin P0.

Page 28 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

Since the input values were set to the variables, a and b, we can use a and b to dictate the output values at
pin P4 and P5.

out4 = b
out5 = a

We could just as easily have used the commands out4=in1 and


out5=in0; however, using variables to store the values in
memory has advantages as the programs get more
BASIC Stamp Memory complicated. In the next experiment, it will be necessary to use
RAM
The BASIC Stamp has 26 bytes of RAM (random
variables to store values.
access memory) that can be used for storing
variable values. Another 6 bytes of RAM is used The reason we used variables in this program is because they
to interface the BASIC Stamp with its I/O pins. can be manipulated arithmetically, and the next task is to
EEPROM convert from binary to decimal. To do this, multiply the variable
Short for electrically erasable programmable
read only memory, EEPROM is used mainly to b by 2 and the variable a by 1 and add them together. The
store the PBASIC programs. EEPROM can also be nibble variable d is used to store this new value. This is the
used to store data values that do not change method for converting a 2-bit binary number to a decimal
frequently. number. The next section shows how to do this for a binary
number of any size.

d = (2*b)+(1*a)

In the calculation we just did using PBASIC, the parentheses are necessary to maintain the normal algebraic
rules of operation. This is because the BASIC Stamp performs its math beginning at the left. Then, it performs
each operation within parentheses it encounters while checking the line from left to right.

Without the parentheses, d would be set equal to the value ((2 b + 1) a) because that's the order in which
the operators (+, -,*, /, etc) are encountered.

Six debug commands are used to display all the measured states and the calculated binary values in the
Debug window. The first debug command below displays four different items. Remember, each item in a
single debug command must be separated by a comma.

The debug home sends the cursor to the top-left "home" position in the debug window. Note that it is
followed by a comma to separate it from the next item. The next item is a message in quotes: "State of
pin P1 is ". Whenever you want to print a text message to the debug window, use quotes. The third item
is bin a, which tells the debug window to print the binary value of the variable a. The fourth item is cr, which
makes the debug window print a carriage return.

Basic Analog and Digital Student Guide Version 1.0 Page 29


Experiment #2: Introduction to "Bit Crunching"

debug home, "State of pin P0 is ", bin a, cr

A similar message is printed for the variable b, without the home command. The home command works well
when it's used once per loop. Remember that debug home sends the cursor to the top-left corner of the
debug window. If we used home more than once in the loop, the information displayed after the first home
command would be over written by the information following the second home command.

debug "State of pin P1 is ", bin b, cr, cr

Next a message in quotes is printed followed by two carriage returns.

debug "2-bit binary number:", cr, cr

Next, another message in quotes is printed followed by another carriage return.

debug "P1 P0", cr

In this next command, the quotes contain spaces. The first pair of quotes just contains one space (the space
bar on the keyboard was pressed once). Then the binary value of b is printed, followed by another two spaces
in quotes, followed by the binary value of a, then two more carriage returns.

debug " ", bin b, " ", bin a, cr, cr

Here's something new. The modifier dec was used to print the decimal value of the variable d.

debug "Decimal equivalent: ", dec d, cr

We want the BASIC Stamp keep checking the inputs over and over again. We also want the BASIC Stamp to
automatically update the LEDs and the debug window with the latest information on the pushbuttons. The way
to accomplish this is to keep sending the program back to the loop: label we created earlier. To send the
program back to the loop: label, use the command:

goto loop

Page 30 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

Counting in Binary

Table 2.1 shows how to count from 0 to 3 using 2-bit binary numbers and how to count from 0 to 7 using 3-
bit binary numbers.

Note that four numbers (decimal 0 through 3) can be represented with a 2-bit binary number. Eight numbers
(0 through 7) can be represented with a 3-bit binary number. 4-bits can describe 16 different numbers, 5-bits
can describe 32 different numbers and so on.

Table 2.1: Counting with Binary Numbers

Decimal 2-bit binary 3-bit binary


number representation representation
0 00 000
1 01 001
2 10 010
3 11 011
4 100
5 101
6 110
7 111

You can always determine how many counting numbers (combinations of 0s and 1s) can come from a given
number of bits by using this formula:

combinations = 2bits

This means the number of combinations equals two raised to the power of the number of bits. For 2-bits, the
number of combinations is 22 = 4. For 3-bits, the number of combinations is 23 = 8, and so on.
Converting from binary to decimal takes two steps. The first step is to multiply each bit by its power of two.
Table 2.2 shows the powers of two for up to 8-bits. When you multiply each bit by its value from Table 2.2, you
end up with a series of decimal values. The second step is to add up all the decimal values.

Add table that points at different bits in a binary number

Basic Analog and Digital Student Guide Version 1.0 Page 31


Experiment #2: Introduction to "Bit Crunching"

Table 2.2: Bit Multipliers for an 8-bit Binary Number


Bit 7 6 5 4 3 2 1 0
Multiplier 128 64 32 16 8 4 2 1

Bit multipliers and Powers of Two

Bit-0 is the least significant bit (LSB) and bit-7 is the most significant bit (MSB). Thats because bit-0 makes the smallest
contribution to the number and bit-7 makes the largest contribution. Thinking about a binary number as starting on the left
with bit-7 and ending on the right with bit-0 is useful because these numbers indicate the power of 2 for each digit.

Examples:
The multiplier for bit-0 is 1, which equals 20.
The multiplier for bit-1 is 2, which equals 21.
The multiplier for bit-7 is 128, which equals 27.

----------------You can use powers of two to extend Table 2.2 to any number of bits. ---------------

As an example, lets convert binary-1011 to decimal. First, multiply each bit by its power of two from Table
2.2.

81=8
40=0
21=2
11=1
Second, add all 4 of the decimal values:
8+0+2+1 = 11

Now we know the binary number 1011 is equal to the decimal number 11.

Add bit pictorial.

Page 32 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

Parallel and Serial Transmission

Program Listing 2.1 repeats the entire check and report on the pushbutton states routine over and over
again. Because the BASIC Stamp checks for input over and over again without waiting for some kind of signal
that the data is ready means that we are sending the binary numbers to the BASIC Stamp asynchronously.

We are also sending the binary bits across two separate data lines
at the same time. This means we are sending our data bits to the
BASIC Stamp in parallel.
Asynchronous:
Asynchronous means not synchronized. In
the case of our binary keypad, it means that The BASIC Stamp has a 16 I/O pins. We could actually send a word-
we change the binary values whenever we size binary number to the BASIC Stamp in parallel. The problem is
want to without waiting for permission from that we wouldn't have any pins left for outgoing signals or other
the BASIC Stamp to do so. Likewise, the
BASIC Stamp checks the signals at P0 and P1
input data. When dealing with larger binary numbers, sending
as fast as it can without waiting for a signal serial data instead of parallel data can be useful because it reduces
from us that says the data is ready to be the number of BASIC Stamp I/O pins used to receive data.
checked.
When sending serial data, there has to be some way of letting the
BASIC Stamp know when each new bit is ready. The BASIC Stamp
has build in functions for sending asynchronous as well as
synchronous serial data.
Parallel: In this next example, the same two pushbuttons are used to send
Parallel means the data bits are sent across
more than one data line at the same time.
the BASIC Stamp a nibble (4-bits) of serial, synchronous data. The
We just finished using the pushbuttons to result is displayed in the debug window.
send two parallel bits.
Serial:
Instead of sending data in parallel along Reprogramming to Send Serial Data
multiple data lines, a single data line can be
used and the data bits can be sent one after
another. Enter Program Listing 2.2 into the BASIC Stamp Editor, and save it
Synchronous: under the name PL2_2R0.bs2.
Sending data synchronously means we are
sending the data in time coordinated
manner (in sync). Technically, it means that
the sender and receiver of the data bits do
so according to signals from the same clock.

Basic Analog and Digital Student Guide Version 1.0 Page 33


Experiment #2: Introduction to "Bit Crunching"

'Program Listing 2.2


debug cls

n var nib
d var nib

input 1
input 2

for n = 1 to 4
wait_for_high:
if in1 = 0 then wait_for_high
wait_for_fall:
if in1 = 1 then wait_for_fall
out4=in1
d=d<<1
d=d+in0
debug home, "Shifting in bits: ", bin4 d
next

debug cr, cr, "Done shifting.", cr, cr


debug "Decimal value: ", dec2 d, cr, cr

The Output

Follow these instructions carefully to send the synchronous, serial data. First, press and hold the right button.
Then press and release the left button. The output should look like Figure 2.5 below.

Shifting in bits: 0001


Figure 2.5: Debug Output for
Program Listing 2.2.

Next, release the right button, and press and release the left button again. The output should change so that it
looks like Figure 2.6.

Shifting in bits: 0010


Figure 2.6: Debug Output for
Program Listing 2.2.

Page 34 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

Press and hold the right button, then press and release the left button twice. Then the output should look like
Figure 2.7

Shifting in bits: 1011


Figure2.7: Debug Output for
Program Listing 2.2. Done shifting.

Decimal value: 11

If your program worked as shown, you just synchronously shifted 4 serial bits into the BASIC Stamp's RAM. In
addition, it was verified that the decimal value of binary-1011 really is 11 in the decimal number system.

Figure 2.8 shows how these events occurred (from left to right) in a timing diagram. The left pushbutton was
the clock signal. The clock signal consisted of a series of clock pulses. Each clock pulse was the press and
release of the left pushbutton. This sent a low-high-low signal to P1. Each time the left pushbutton was
released, the BASIC Stamp checked the state of the data line, which was the state of the right pushbutton
(P0).

Read Read Read Read


Input Input Input Input
Figure 2.8: Timing
Diagram. The
BASIC Stamp reads Clock signal
the input data from left
after the clock pushbutton to
signal's transition P1
from high to low.
This transition is
referred to as the Data signal
negative edge of from right
the clock pulse. pushbutton
to P0

1 0 1 1

Basic Analog and Digital Student Guide Version 1.0 Page 35


Experiment #2: Introduction to "Bit Crunching"

About the Code

Similar to Program Listing 2.1, we use a comment to include some information about the program at the
beginning. Remember, as soon as an apostrophe appears in a line of PBASIC code, everything to the right of
the apostrophe is ignored by the BASIC Stamp. Next the two nibble variables are defined, and I/O pins P0 and
P1 are set to function as inputs.
'Program Listing 2.2
debug cls

n var nib
d var nib

input 0
input 1

A for-next loop is started to shift all 4-bits into memory.

for n = 1 to 4

For-Next loop

for n = 1 to 7 In the example shown to the left, the for-next loop


PBASIC commands executes the PBASIC commands between the for
. command and the next command 7 times. The first
.
time through the loop the value of n is 1, the second time
.
next through the value of n is 2, and so on until n gets to 7.

PBASIC Commands After the 7th pass through the for-next loop, the program
. skips out of the loop and starts executing the PBASIC
. commands that follow the next command.
.

The code that gets repeated within the for-next loop is different from what we've seen before. It starts
with the wait_for_high: label. Next the if-then statement is used to check the value at pin P0. If the
value of P0 is low, the if-then sends the program back to the wait_for_high: label. If the value at pin P1
is high, then the program executes the next line.

Page 36 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

wait_for_high:
if in1 = 0 then wait_for_high

The same technique is applied with the next two lines of code, which repeat themselves until a low signal is
received.

wait_for_fall:
if in1 = 1 then wait_for_fall

As shown below, d=d<<1 shifts all the bits in d left by 1. When values are shifted, the vacant space in the
rightmost bit (the LSB) is automatically filled with a zero. Then the bit value at pin P0 is loaded into the LSB
position in the nibble. This is done using the d=d+in0 command, which adds the single bit measured at P0 to
the value of the nibble variable d. The second time through the loop, the value that was placed in the LSB gets
shifted left by one, so it ends up in bit-1. Meanwhile the next value sampled at P0 is placed in the LSB slot. The
shift and add process is repeated four times as each bit is shifted into the byte.

d=d<<1
d=d+in0

Each time a new bit is shifted in, we use the debug command to display the new value. Each time the program
gets to the next command it returns to the for n = 1 to 4 command, and the value of n is incremented,
until it gets to 4. Finally the program breaks out of the loop.

debug home, "Shifting in bits: ", bin4 d


next

Once the for-next loop is finished and all the bits are shifted into the d variable, two messages are printed.
The second of the two debug commands has a new modifier, dec2. This modifier is used to make the debug
window display the value of d as two decimal digits.

debug cr, cr, "Done shifting.", cr, cr

debug "Decimal value: ", dec2 d, cr, cr

Experiment #1 introduced analog voltage, and this experiment introduced the basics of sending and receiving
binary numbers. In the next experiment, we'll combine these topics to build a digital DC voltmeter, which is a
device that measures analog voltage and display the measurement as a digital value.

Basic Analog and Digital Student Guide Version 1.0 Page 37


Experiment #2: Introduction to "Bit Crunching"

What have I On the lines below, insert the appropriate words from the list on
the left.
learned?

largest The _____________ can be used to process information about analog measurements
using _____________ . Before working with analog to digital interfaces, it's important
word to understand how the BASIC Stamp sends, receives, and stores binary data. It's also
important to be able to use _____________ to program the BASIC Stamp to send,
decimal receive, and store binary data.

BASIC Stamp When converting a binary number to its _____________ equivalent, each bit should be
multiplied by a particular power of two. The _____________ is the rightmost bit in a
synchronously binary number, and it makes the smallest contribution to the value of that number. It is
also referenced as bit-0. The MSB is the leftmost bit. It makes the _____________
LSB contribution to the value of a binary number. The bit just to the left of the LSB is bit-1,
the bit 2-bits to the left of LSB is bit-2 and so on.
PBASIC
The BASIC Stamp can store a single bit, a nibble, which is 4-bits, a _____________,
byte which is 8-bits, or a _____________, which is 16-bits. To save I/O pins, the BASIC
Stamp can send and receive serial data as opposed to parallel data, which uses multiple
binary numbers
data lines. Binary data can also be sent _____________ or asynchronously.

Page 38 Basic Analog and Digital Student Guide Version 1.0


Experiment #2: Introduction to "Bit Crunching"

Questions

1. Determine the decimal equivalents of these binary numbers: 1010, 1111, 0010, and 0100.

2. The command d = d<<1 was used to shift the bits in the variable d to the left by 1. What command do
you think would be used to shift the bits to the right? What command would you use to shift the bits by,
say, 3 to the left?

3. Explain the difference between serial and parallel data.

4. Explain the difference between synchronous and asynchronous data transmission.

Challenge!

1. Program Listing 2.1 is used to count to three. Write a program that uses three parallel bits (use pin P2
for the third bit) and counts to 8. You can check your work by connecting the input pin P2 to Vdd for a
high signal and to Vss for a low signal.

2. Modify Program Listing 2.2 so that it displays the clock pulses you apply to the left pushbutton with the
left LED.

3. Modify Program Listing 2.2 so that it shifts the bits back out, displaying them with the right LED.

Basic Analog and Digital Student Guide Version 1.0 Page 39


Experiment #2: Introduction to "Bit Crunching"

The goal in this series of experiments is to demonstrate how a


device such as the BASIC Stamp, which processes binary data, can
Why did I learn be used to interface with the analog world. Binary numbers and
it? states form the foundation for how microcontroller,
microprocessors and an entire class of binary circuits process
data.

Analog data can be effectively processed with binary numbers using the techniques in this experiment.
Learning the basics of processing binary data will help make a myriad of electronic circuits easier to
understand. This is also the foundation for how the home computer processes data. Understanding data at
the binary level ("bit crunching") also makes various programming languages easier to understand.

In some of the upcoming experiments, we will process analog data


using serial and parallel data. We will also use synchronous and
How can I asynchronous communication. The BASIC Stamp can be connected
apply this? to other integrated circuits and exchange binary data. The BASIC
Stamp can also be programmed to convert the binary data to a
meaningful decimal form.

We'll use these techniques to measure voltage, sound, light, etc.

The BASIC Stamp has commands which automate the serial data transmit and receive processes in both
asynchronous and synchronous modes. We will encounter the serial, synchronous method in Experiment #3.
The BASIC Stamp also has features available to simplify the sending and receiving of parallel data, as we'll
discover in Experiment #4 where asynchronous parallel data is transmitted.

Page 40 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

Experiment #3: Build Your Own Digital DC Voltmeter


Basic Analog to A digital DC voltmeter (DC DVM) is a handy tool for measuring
Digital voltage between two contact points. In this experiment, we will
Conversion build a DVM for measuring DC voltage in the 0 to 5 Volt range. A
common use for a DC DVM is testing the voltage (potential)
between the two terminals on a battery.

A digital voltmeter is so named because it displays its measurements with digits. The digits 0 through 9 and a
decimal point are used to display the voltage measurements as decimal values. The digits 0 and 1 could be
used. It would still be a "digital" voltmeter, but it would have binary display instead of a decimal display.
Making sense out of each measurement would be time consuming. Since our DVM processes its measurements
in binary, we'll start with a binary display and then modify it to the more conventional and easy to read
decimal display.

In Experiment #1, we used an LED circuit to display changes in


analog voltage level applied to a circuit. As a continuously
Continuous range: variable value, analog voltage varies within a continuous range.
A minimum value, a maximum value, and We'll use the potentiometer as we did in Experiment #1 to make a
everything in between.. When a source of
voltage varies over a continuous range, it is range of voltages that can vary continuously between 0 and 5
considered an analog voltage. Volts on the Board of Education.
We will use our DVM to sample voltages Although information about analog voltage can be processed
over a continuous range, from 0 to 5 Volts.
So, the voltage we measure might be 1.234
efficiently with binary devices, the voltage has to be sampled and
Volts or 3.857564 Volts, or 4.9999 Volts, described using binary numbers first. The ADC0831 is a common
etc. integrated circuit that does this job. It describes the analog
information with binary numbers for devices that process binary
information, such as the BASIC Stamp.

In this experiment, we will make a DVM using the BASIC Stamp together with the ADC0831 integrated circuit.
A pot will be wired to the Board of Education and adjusted to make analog output voltage. The DVM will then
be used to measure samples from the pots continuous range of voltage outputs.

Basic Analog and Digital Student Guide Version 1.0 Page 41


Experiment #3: Basic Analog to Digital Conversion

Parts (1) ADC0831


(1) 100K potentiometer
Required (10) Wires, give or take a few

The Potentiometer, a Source of Variable Voltage


Resistors in Series:
A chain of resistors connected end
There is a reason why the voltage at the wiper terminal of a pot changes.
to end. Three resistors in series are when you turn the knob. The wiper terminal makes the single resistive
shown below. The three resistors element in the pot work like two resistors in series. Figure 3.1 shows
can be viewed as a single resistance two resistors in series. When input voltage is applied and output voltage
whose value is: is measured as shown in Figure 3.1, the circuit is referred to as a voltage
Rseries = R1 + R2 + R3 divider. R1 and R2 are the resistances between the wiper and the other
two terminals on the pot, and their values change as the pot is adjusted.
Since the pot causes the R1 and R2 to vary, we can call our wiper
R1 R2 R3 terminal the output of a variable voltage divider.

Vinput Vdd
= Vdd
Resistor Values Figure 3.1: A Voltage Divider Circuit
When you know the value of the two shows how the wiper in a potentiometer
resistors in Figure 1.2, you can makes the single resistive element look like R1
predict the output voltage using this two resistors in series.
equation.
Voutput is the voltage measured at the Voutput
R2 wiper terminal. (Taken at
Voutput = Vinput the wiper
R1 + R 2 R2 terminal)
Not surprisingly, its called the
voltage divider equation, and this
technique for scaling down an input Vss
voltage is commonly referred to as
using a voltage divider.

Page 42 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

The ADC0831 Integrated Circuit - An 8-bit Analog to Digital Converter

The ADC0831 is an integrated circuit referred to as an 8-bit analog to digital converter (A/D converter) with
synchronous serial output. Let's look at what each of these terms mean:

An integrated circuit (IC) is a circuit with microscopic components implanted on the surface of a
silicon wafer. The Analog and Digital Parts Kit has three chips used in these experiments. Each chip is
a black casing with eight pins. The black casing houses and protects an integrated circuit.

An A/D converter measures an analog voltage sample and returns a binary number that describes the
sample.

8-bit is the number of binary digits the ADC0831 uses to describe the analog voltage it samples. 8-bit
is also the resolution of the A/D converter. You can count from 0 to 255 (decimal) using an 8-bit
binary number. This means that the ADC0831 can approximate the voltage it measures as one of 256
levels. A higher resolution converter, such as 12-bit, would break the same voltage range into 4096
levels because you can count from 0 to 4095 with 12 binary bits.

Synchronous and serial are terms we learned about in Experiment #2. We sent serial binary digits
(bits) to the BASIC Stamp using one pushbutton and the bits were synchronized to a second
pushbutton that was used to send a clock signal. The ADC0831 works in a similar way. The difference
is that the ADC0831 depends on a clock signal sent by the BASIC Stamp to time the sending of each
serial output bit.

The BASIC Stamp will be programmed to read and store the 8-serial-bits
transmitted by the ADC0831. Well also program the BASIC Stamp to display
Binary control signal: the decimal equivalent of the binary output. Next, well use this decimal
A voltage signal with two equivalent to calculated and display the measured voltage in decimal form
possible states, low or high, (our DVM output). The BASIC Stamp must also be programmed to send
that is sent to tell a device binary control signals to make the ADC0831 do its job.
how or when to do something.
The ADC0831 requires control
signals to activate it and a Figure 3.2 shows a pinout map of the ADC0831. Each pin has a number and a
clock signal to synchronize the label. The number is important for getting the wires connected to the right
sending of each of the pins when constructing your circuit. The labels indicate the function of each
ADC0831's output bits.
pin.

Basic Analog and Digital Student Guide Version 1.0 Page 43


Experiment #3: Basic Analog to Digital Conversion

Index Mark
Figure 3.2: ADC0831 Circuit 8 5
Symbol and Pin Map. The Vdd Vref pin #1
pin map on the right shows 1
/CS ADC0831
the pins and labels according
to where they are on the 2 /CS Vcc
Vin(+) 1 8
chip. The circuit symbol on ADC0831
Vin (+) 2 7 CLK
the right also shows the pins 7 4 A/D
and their labels, but it's CLK Gnd Converter
Vin (-) 3 6 D0
typically drawn in a way that 6
most conveniently fits into DO GND VREF
3 4 5
the schematic. Vin(-)

The notation for the ADC0831's inputs and outputs works as follows:
Vin(+) is the analog input, and D0 is the serial output. VREF and Vin(-)
Bias:
are used to bias the IC. Vcc and GND are used for supplying power to
A method of applying specific voltage the IC. Vcc is essentially the same term as Vdd on the Board of
levels at certain places in a circuit to Education, and GND corresponds to Vss. /CS stands for active low chip
calibrate or tune it. select, and CLK stands for clock. Both are inputs for binary control
signals.

To prime the ADC0831 for taking a measurement, the /CS pin has to receive a signal from the BASIC Stamp
that starts high, then goes low. This signal has to stay low for the duration of the conversion. Then the CLK
input must receive a single clock pulse (a term introduced in Experiment #2, Figure 2.8) to signify that the
conversion should start at the next clock pulse. For this IC, a clock pulse starts low, goes high, then goes low
again. It takes 8 more clock pulses to complete the conversion. Each time a clock pulse is received by the CLK
input, another of the serial bits is sent by the D0 output.

Electronics designers use data sheets to find the kind of information just discussed. Each IC manufacturer
publishes data sheets for the integrated circuits they make. The information just covered on the pin map and
control signals was condensed from a data sheet published by National Semiconductor, the maker of the
ADC0831. Of course all of the datasheets are available on the manufacturer's web sites.

Page 44 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

Figure 3.3 shows the schematic for this experiment. This is a fairly simple
circuit to build, so let's try it without the breadboard example. Hopefully
Build It you're getting the hang of the list of connections described by a schematic.
Remember that when working with the connections to an IC, use the index
mark on the chip along with the pin map to figure out the pin numbers!

Vdd
Figure 3.3: Schematic
List of connections made on this schematic:
Pin 1 on the ADC0831 is connected to pin P0 on
the BASIC Stamp. 8 5
The wiper terminal of the pot is connected to pin Vdd Vref Vdd
2 on the ADC0831. P0 1
/CS ADC0831
Of the two remaining terminals on the pot, one is
connected to Vdd on the Board of Education, and Vin(+)
2 100k
the other is connected to Vss. POT
Pins 3 and 4 on the ADC0831 are connected to P1 7
CLK 4
Vss. Gnd
Pins 5 and 8 on the ADC0831 are connected to P2 6
DO
Vdd. 3
Pins 7 and 6 on the ADC0831 are connected BASIC Vin(-)
Stamp pins P1 and P2 respectively.

Vss

Program Listing 3.1 is the first step to a functional DC voltmeter. This


program displays the 8-bit serial output of the ADC0831. Enter the code and
Program save it as P3_1R0.bs2. There will be three revisions of this program listing, so
It it will become important to keep track of your source code versions.

We'll modify the code so that it also displays the decimal conversion of the
8-bit binary number. Next we'll add some more code to adjust the number to a 5 Volt scale. Make sure your
circuit is constructed correctly and your programming cable and power source are connected, then run the
program.

Basic Analog and Digital Student Guide Version 1.0 Page 45


Experiment #3: Basic Analog to Digital Conversion

Program Listing 3.1


ADC0831 Binary output display.

'Declarations.
adcbits var byte
v var byte
R var byte
v2 var byte
v3 var byte

CS con 0
CLK con 1
D0 con 2

'Start display.
debug cls

'Main routine.
main:

gosub ADCDATA
gosub CALC_VOLTS
gosub DISPLAY

goto main

ADCDATA:
high CS
low CS
low CLK
pulsout CLK,210
shiftin D0,CLK,msbpost,[adcbits\8]
return

CALC_VOLTS:
return

DISPLAY:
debug home
debug "8-bit binary value: ", bin8 adcbits
return

Page 46 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

The Output

If the pot is adjusted somewhere in the middle of its range, the output displayed in the debug window should
look similar to Figure 3.4. As you adjust the pot, the zeros and ones should change rapidly. Each time you stop
adjusting the pot, the output should settle, and a new pattern of eight zeros and ones should display.

8-bit binary value: 10110100


Figure 3.4: Debug Output for
Program Listing 3.1.

If your debug window responds this way, its likely your circuit and program are working right. If it doesnt do
this, check the wiring on your circuit. Also make sure code is entered correctly. The debug window could also
be hidden from view, accessed by Run/Debug/New Terminal in the Windows version of the software.
Sometimes just one wrong letter will cause the program not to work properly.

About the Code

The first few lines of text in this program are comments that begin with apostrophes, and they don't have any
function in the program aside from explaining it to someone reading the code.

'Program Listing 3.1


'ADC0831 binary output display.

The next section is called the variable declarations section, and it begins with a comment explaining that this
is the declarations section. This program uses just the adcbits variable at present. We'll add code that will
make use of the other four variables, v, R, v2, and v3.

' Declarations
adcbits var byte
v var byte
R var byte
v2 var byte
v3 var byte

Basic Analog and Digital Student Guide Version 1.0 Page 47


Experiment #3: Basic Analog to Digital Conversion

Following is a new type of declaration we haven't used before. Three constants are defined using the con
directive. After we define these constants, we can use CS in place of the number 0, CLK in place of the
number 1, and D0 in place of the number 2. The names for the constants were chosen to correspond with the
ADC0831's pin labels. The numbers were chosen based on BASIC Stamp I/O pin numbers.
CS con 0
CLK con 1
D0 con 2

Next there's a loop that contains three gosub commands. The


main:goto main routine runs 3 different subroutines over and over
again. The subroutines are named ADCDATA:, CALC_VOLTS:, and
Subroutine:
A subroutine is a small program that DISPLAY:. The label main: is used in the same manner that we used
does a specific task within a larger the loop: label in the first two programs. The label name main: was
program. chosen because, as the comment preceding this routine indicates, it's
the "main routine" in the program.

'Main routine
main:

gosub ADCDATA
gosub CALC_VOLTS
gosub DISPLAY

goto main

So, how does a gosub command work? As shown in the flow diagram in Figure 3.5, gosub ADCDATA means
go to the subroutine labeled ADCDATA: and come back when finished. The program jumps to the ADCDATA:
label and starts executing commands. As soon as it gets to the return command, the program jumps back to
the command just after gosub ADCDATA. In this case, the next command is another gosub command, gosub
CALC_VOLTS.

Page 48 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

main:

Figure 3.5: Flow Diagram gosub ADCDATA


A subroutine sends the program to gosub CALC_VOLTS
the specified label. In this case the gosub DISPLAY
label is ADCDATA:. Then the goto main
program continues executing
commands until it encounters the ADCDATA:
return command. The return high CS
command sends the program back low CS
low CLK
to the command immediately after pulsout CLK,210
the gosub command. In this case shiftin
it's another gosub command. D0,CLK,msbpost,[adcbits\8]
return

The subroutine ADCDATA: sends control signals to and collects output data from the ADC0831. This
subroutine is where the usefulness of the con directive really shows. P0 on the BASIC Stamp is connected to
the /CS pin on the ADC0831. Likewise, pins P1 and P2 are connected to CLK and D0. When sending signals to
the /CS pin, we can enter a command like high CS instead of high 0. It makes more sense when writing the
code, and it makes deciphering the code easier too. It's also easier to change one constant in the top of the
program should you decide to connect the ADC0831 to a different BASIC Stamp I/O pin.

The command high CS sends a high signal to the ADC0831s /CS pin. To start a conversion, we need to send a
high signal (5 Volts). Then we need to send a low signal (0 Volts) to the /CS input on the ADC0831 using low
CS. The signal sent to the ADC0831's /CS input needs to stay low for the duration of the conversion.

high CS
low CS

The low CLK command is necessary so that the clock pulses take the right form. Using this command
guarantees that the next command (pulsout) will send a clock pulse that has the right shape, low-high-low.
Sending high and low signals using the high and low commands is an alternative to the out0=1 and out0=0
techniques used in the first experiment.

low CLK

The pulsout CLK,210 command sends a clock pulse to the ADC0831's CLK input. This is the first clock pulse,
and all it does is tell the ADC0831 to start converting on the next clock pulse. Because of this, we don't need
to check for input from D0 after this first clock pulse.

pulsout CLK,210

Basic Analog and Digital Student Guide Version 1.0 Page 49


Experiment #3: Basic Analog to Digital Conversion

Since we set the clock low just before this command, pulsout sends the desired low-high-low signal. The
duration of the high segment is twice the number specified in the pulsout command, in microseconds (us). 1
us = 1/1,000,000 of a second. Therefore the duration of this high segment is 2 us 210 = 420 us.

The command shiftin D0,CLK,msbpost,[adcbits\8] is a powerful instruction that takes care of all the
synchronous serial communication so that we don't have to program it as we did in Experiment #2. In effect,
this command sends control signals to the ADC0831s CLK input and reads output bits from ADC0831s D0
output. This command also loads each of the ADC 0831s output bits into the adcbits byte.

shiftin D0,CLK,msbpost,[adcbits\8]

The shiftin command is discussed in more detail in the BASIC Stamp Manual Version 1.9, but the general
format for the command is:

shiftin data pin,clock pin,mode,[variable\bits]

In our case, the data pin is D0, a constant equal to the number 2. This constant is used to reference BASIC
Stamp I/O pin P2 in this program. Likewise, the clock pin is CLK, which is a constant equal to the number 1, and
it references BASIC Stamp I/O pin P1. The mode in this case is msbpost, and it's one of four transmission
modes that can be used in this command. It indicates that the the MSB is transmitted first by the ADC0831,
and that the ADC0831's output bits are ready after the clock pulse's negative edge, the transition from high to
low. [adcbits\8] means the data is shifted into the adcbits variable, and 8-bits are expected.

The CALC_VOLTS: subroutine is empty right now, but we will develop the code for this subroutine shortly.
The subroutine will calculate the measured voltage to the hundredths decimal place.

CALC_VOLTS:
return

At present, the DISPLAY: subroutine just displays the binary output for each analog voltage sample taken by
the ADC0831. It will be modified to display the decimal equivalent of the 8-bit binary value. It will also be
modified to display the voltage measurement.

The command debug home, cr, "8 bit binary value: ", bin8 adcbits sends the cursor to the
top-left "home" position in the debug window. Then it prints the message in quotes. The modifier bin8 makes
it so the value of the adcbits variable is displayed as 8 binary digits.

debug home, cr, "8 bit binary value: ", bin8 adcbits

Page 50 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

If the number of digits displayed is likely to vary, when using the debug home command, always specify how
many digits the numeric outputs should have with modifiers like bin8, dec3, etc. When debug cls is used,
its OK to skip specifying the number of digits, so modifiers such as bin and dec can be used instead.

The debug home command is better for programs that cycle through loops where the debug window display
is updated frequently and rapidly. When debug cls is used under these circumstances, the repeated clearing
the debug window causes a flicker that makes the display difficult to read.

The return command sends the program back to the line immediately following the gosub display
command.

DISPLAY:
debug home
debug "8-bit binary value: ", bin8 adcbits
return

We will modify the DISPLAY: subroutine to display the decimal equivalent of the binary contents of adcbits
in the debug window. Code will also be added to make the debug window display our DVM reading.

Interpreting the Output

The ADC0831 measures an analog voltage at its input. Then it sends the BASIC Stamp a binary number
describing the value it measured. For now, well focus on a voltage scale that starts with 0 Volts and ends at 5
Volts.

With an 8-bit binary number, you can start counting with 00000000 and count all the way up to 11111111.
Translated to decimal numbers, it's the same as counting from 0 to 255. When applied to a 5 Volt scale that
starts at 0 Volts, its the same as counting from 0 to 5 Volts using 255 voltage steps.

For the 5 Volt scale, when the ADC0831 measures 0 Volts, you get 00000000. When it measures 5 Volts, the
output is 11111111. It turns out that the debug window output 10110100 from Figure 3.4 is the same as the
decimal number 180. Decimal-180 in turn corresponds to a measured voltage of 3.53 Volts.

Basic Analog and Digital Student Guide Version 1.0 Page 51


Experiment #3: Basic Analog to Digital Conversion

Binary to Decimal Conversion Revisited

So how do we know that 256 combinations can come from an 8-bit binary number? Remember, you can
always tell how many numbers (combinations of 0s and 1s) can come from a given number of bits by using this
formula from Experiment #2:

combinations =2bits

This means the number of combinations equals two raised to the power of the number of bits. For 8-bits, the
number of combinations is 28 = 256. For 12-bits, the number of combinations is 212 = 4096, and so on.
Let's use the two-step method from Experiment #2 to convert the 8-bit binary number 10100101 to its
decimal equivalent. Here is a repeat of the bit multipliers table to work with:

Table 3.1 Bit Multipliers for an 8-bit Binary Number


Bit 7 6 5 4 3 2 1 0
Multiplier 128 64 32 16 8 4 2 1

First, multiply each bit by its power of two from Table 3.1
128 X 1 = 128
64 X 0 = 0
32 X 1 = 32
16 X 0 = 0
8X0=0
4X1=4
2X0=0
1X1=1
Second, add all 8 of the decimal values:
128+0+32+0+0+4+0+1 = 165

Now we know the binary number 10100101 is equal to the decimal number 165. To display this conversion, a
single debug command can be added to the DISPLAY: subroutine. Added lines are shown with a "".

Page 52 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

DISPLAY:
debug home, "8 bit binary value: ", bin8 adcbits
debug CR, CR, "Decimal value: ", dec3 adcbits ' new lines
return

The command debug CR, CR, "Decimal value: ", dec3 adcbits tells the debug window to display
two carriage returns followed by the message in quotes, followed again by the 3-digit decimal value of
adcbits. If the actual number only has one or two digits, the debug window will automatically display leading
zeros since dec3 was specified. For example, the number 7 will display as 007, and the number 85 as 085, etc.

With some careful adjustment of the pot, we can check our work using output sample shown in Figure 3.6.

8-bit binary value: 10100101


Figure 3.6: Debug Output for
Program Listing 3.1, Revision 1. Decimal value: 165

Calculate Voltage

Now that we know the decimal equivalent of the ADC0831s binary output, we can do a few calculations to get
the measured voltage. To find out what voltage the decimal number corresponds to, we need to calculate
where in the voltage range the number falls. Here is an effective way to think about the problem.

We know that the voltage is on a 0 to 5 Volt scale, and we know that the ADC0831s output is on a
scale from 0 to 255.
In other words, the measured voltage is to 5 as the A/D output is to 255.

This translates to fractions as:

Voltage Decimal A / D Output


=
5 255
We can re-arrange this equality to calculate the voltage:

5 (Decimal A/D Output)


Voltage=
255

Basic Analog and Digital Student Guide Version 1.0 Page 53


Experiment #3: Basic Analog to Digital Conversion

So, now we know to multiply by 5 and divide by 255 for a 5 Volt scale with 256 levels. We can calculate the
voltage from Figure 3.6 where the ADC0831s output is 10100101 = 165. The measured voltage is:

5 165
Voltage = = 3.24 Volts rounded to two decimal places .
255

To calculate this voltage using the BASIC Stamp, well add some code to both the CALC_VOLTS: and
DISPLAY: subroutines. First, the voltage equation needs to be expressed in PBASIC code. Here is an example
of some code that could reasonably be expected to work.

v = 5*adcbits/255

This PBASIC calculation looks like it will give us the output we want, but it wont. Its instructive to try it this
way and see what happens. Modify the CALC_VOLTS: and DISPLAY: subroutines in Program Listing 3.1 as
follows:

CALC_VOLTS:
v = 5*adcbits/255 ' new line
return

DISPLAY:
debug home, "8 bit binary value: ", bin8 adcbits
debug CR, CR, "Decimal value: ", dec3 adcbits
debug CR, CR, DVM Reading: , dec3 v, Volts ' new line
return

We calculated that 165 would lead to a measured voltage of 3.24 Volts. The 003 Volts shown in Figure 3.7 is
only accurate to the nearest volt! What happened?

8-bit binary value: 10100101


Figure 3.7: Debug Output for
Decimal value: 165
Program Listing 3.1, Revision 2.
DVM Reading: 003 Volts

The PBASIC command set for the BASIC Stamp does arithmetic using integer values. Integers are the counting
numbers: -2, -1, 0, 1, 2, 3, etc. The largest integer the BASIC Stamp can process is 65535. When using integer
arithmetic, the fractional part of any answer is discarded. Fortunately, we can still use integer arithmetic to
find the fractional values we are trying to display.

Page 54 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

Before dividing, the A/D output is multiplied by 5. This doesnt cause any problems.

5 (Decimal A/D Output) is essentially the same as 5 adcbits .

In our voltage calculation example, thats 5 165 = 825. Since 825 is an integer that is less than 65535, this
part of the calculation goes without a hitch. The problem occurs when we try to divide 825 by 255. The answer
has a fractional component that never gets calculated with integer math.

Doing long division with a pencil and a piece of paper takes several steps, and it relies solely on integer
arithmetic. Let's look at how to calculate the answer for this division problem.

5 (Decimal A/D Output)


Voltage = = 3 + a remainder of 60
255

In long division, calculating the part of the answer to the right of the decimal point is repetitive. We multiply
the remainder by 10, then divide by 255 again, then take another remainder, multiply it by 10, and divide by
255 again, etc. A shortcut to this procedure is to take the remainder, and multiply it by 100, then divide by
255. This gives us two decimal places. Let's try it.

(60 100) 255 = 6000 255 = 23.5924... Integer


Math 23

Remember: the BASIC Stamp cuts off everything to the right of the decimal point without rounding. This is
called truncating. The result we get is 23. This result should have been rounded up to 24 because 23.5294 is
more than half way to the next integer value, 24. For now, let's stick with 23 to the right of the decimal point.

Our answer using this algorithm is the integer 3 to the left of the decimal point,
and the integer value 23 to the right of the decimal point. Since we used only
Algorithm:
integers in our arithmetic, it should work using PBASIC and the BASIC Stamp.
A procedure for solving a
problem. The procedure is Since the BASIC Stamp works with integers, it's not surprising that there is a
broken down into PBASIC command to calculate the integer remainder of a division problem. The
repeatable steps. operator for division is / and the operator for getting the remainder is //. Let's
try converting this algorithm into PBASIC code to do the work for us. The steps
for long division below show the PBASIC commands corresponding to the steps in
the algorithm.

Basic Analog and Digital Student Guide Version 1.0 Page 55


Experiment #3: Basic Analog to Digital Conversion

v+R
v=5*adcbits/255 255 5 adcbits R=(5*adcbits//255)

v2
v2=(100*R)/255 255 100 R

This gives us our 3 PBASIC commands for calculating the values to the left and right of the decimal point. To
reconstruct the fractional value on the display, well print a period "." in-between the two values.

The first of the three commands is already in our CALC_VOLTS: subroutine. Just add the other two
instructions to complete the algorithm.

CALC_VOLTS:
v=5*adcbits/255
R=5*adcbits//255 ' new line
v2=100*R/255 ' new line
return

The DISPLAY: subroutine also needs to be updated to print the two variable values with a period in between
them. Make sure to update the line in the display: subroutine exactly as shown below.

DISPLAY:
debug home, "8 bit binary value: ", bin8 adcbits
debug CR, CR, "Decimal value: ", dec3 adcbits
debug CR, CR, DVM Reading: "
debug dec1 v, ".", dec2 v2, Volts ' new line
return

Now run the program again, and see what happens. Figure 3.8 shows an output sample, which is now almost
ready to display to the nearest hundredth of a Volt. All that needs to be corrected is a rounding error in the
hundredths decimal place.

8-bit binary value: 10100101


Figure 3.8: Debug Output for
Program Listing 3.1, Revision Decimal value: 165
2.
DVM Reading: 3.23 Volts

Page 56 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

All that remains to be done is to correct the rounding error in the hundredths place. This rounding problem
can be corrected by adding the segment of code shown below to the CALC_VOLTS: subroutine.
CALC_VOLTS:
v=5*adcbits/255
R=5*adcbits//255
v2=100*R/255
v3=100*R//255 ' new line
v3=10*v3/255 ' new line
if v3<5 then skip_a_line ' new line
v2=v2+1 ' new line
skip_a_line: ' new line
if v2<100 then skip_out ' new line
v=v+1 ' new line
v2=0 ' new line
skip_out: ' new line
return

The Output

The output sample from Figure 3.9 indicates that the DVM is now calculating to the hundredths decimal place
correctly.

8-bit binary value: 10100101


Figure 3.9: Debug Output for
Program Listing 3.1, Revision Decimal value: 165
3.
DVM Reading: 3.24 Volts

IMPORTANT: As soon as you're sure your program works right, save it as P3_1R3.bs2. We will add to both the
code and circuit in the next experiment.

Basic Analog and Digital Student Guide Version 1.0 Page 57


Experiment #3: Basic Analog to Digital Conversion

About the Code

To round off to the nearest hundredth, we need to know the digit in the thousandths place. Using the rules of
long division, we can simply set a new variable, v3 equal to the remainder from the calculation for v2, and
divide by 255 again.

v3=100*R//255
v3=10*v3/255

Instead of using another variable, v3 is simply redefined in the second line. The value of v3 to the right of the
equals sign is the one calculated in the first line. The value of v3 to the left of the equals sign is the redefined
value, which is ten times the old v3, divided by 255.

This process could be repeated over and over again to get the digit in the ten-thousandths place, the
hundred-thousandths place, and so on.

Once the digit in the thousandths place is known, the rules for rounding apply as follows:

If the digit in the thousandths decimal place is less than 5, skip adding 1 to the hundredths
decimal place.
Otherwise, add 1 to the hundredths decimal place.
In either case, truncate everything after the hundredths place.

Since the value v2 is already truncated, we just need code for deciding whether or not to add 1 to the
hundredths place. It turns out to be a decision on whether or not to add 1 to v2 as shown below.

if v3<5 then skip_a_line


v2=v2+1
skip_a_line:

Since the value in the ones place is stored in a different value, we need to check and see if adding one to the
hundredths place increments that value. Without this code, 3.996 would round to 3.00 instead of 4.00.

if v2<100 then skip_out


v=v+1
v2=0
skip_out:

Page 58 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

Save this code, and if possible, leave the circuit as it is because we can use this DVM to take measurements on
the circuit we build in Experiment #4.

Resolution

The BASIC Stamp is now programmed to accurately calculate the voltage associated with the ADC0831's
binary output, and the calculation is accurate to the hundredths decimal place. Although sources of
calculation error have been been eliminated, there is another source of error that caused by the resolution
limitation of the A/D converter.

The A/D converter chip we are using is capable of 256 binary values. This means that each measured voltage
gets rounded to one of 256 discrete values. The step size is the amount of the voltage range covered between
each of these discrete values. Since the first value is zero, there are 255 voltage steps. The step size is given
by :
5 Volts
Step Size = = 0.0196 Volts/step 0.02 Volts/step
255 steps

With this in mind, each time you adjust the pot, the converter comes close to approximating the analog value,
but it's not exact because of the resolution constraints. So, there is still some uncertainty at the hundredths
decimal place. In some applications, the uncertainty is stated along with the measurement. Assuming the
ADC0831 rounds at the half way point, we can use this convention to read the voltage from Output Sample 1.5
as: "3.24 Volts plus or minus 0.01 Volts."

Higher resolution converters are available, such as 12 and 16 bit (and higher), but because of their higher
resolutions, they come with a higher cost as well. The improvement in resolution is significant. As mentioned
before, a 12-bit converter will give you a resolution of 4095 steps. This results in 5 volts / 4095 steps, or one
step for every 0.0012 Volts. A 12-bit converter typically costs more money than an 8-bit converter. There is
also a cost in terms of the amount of memory the measurement takes, (12 as opposed to 8-bits) and the
amount of processing it takes to get each measurement (13 clock pulses instead of 9).

Basic Analog and Digital Student Guide Version 1.0 Page 59


Experiment #3: Basic Analog to Digital Conversion

Calibration

What if the power supply on the Board of Education only supplies 4.963 Volts instead of 5.000 Volts? The
BASIC Stamp voltmeter can be calibrated using a second voltmeter known to be highly accurate. The
difference between Vdd and Vss can be measured using the accurate voltmeter. Developing the code to
correct for this error requires more representation of fractional values using integer math and is best left as
a challenge problem.

Another item to consider if you're shooting for a high degree of precision is that different current draws on
the power supply can also cause variations in power supply output voltage. This is an experiment unto itself
that would also require additional equipment. As you probably guess, designing for a high degree of precision
involves a number of design challenges. For the remaining experiments, the present degree of accuracy of our
DVM is sufficient.

Page 60 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

What
have I On the lines below, insert the appropriate words from the list on the left.
learned?

binary Using the A/D converter makes it possible to process __________ information with the
BASIC Stamp, a digital ( __________ ) device. The converter used in this experiment is
resolution the ADC0831 integrated circuit, an 8-bit, __________ A/D converter.

analog For a given analog __________ , the A/D converter outputs an __________ binary
number. The BASIC Stamp can be used to control and collect data from the A/D
serial converter. Various programming techniques can be used to read, remember, and display
this data.
input
The digital representation of the converted analog signal is very good, but not perfect
8-bit due to inherent __________ limitations of the A/D converter. A second source of error
for the Stamp DC DVM can result from the fact that the power supply on the Board of
Eductaion does not necessarily supply exactly 5 Volts.

Basic Analog and Digital Student Guide Version 1.0 Page 61


Experiment #3: Basic Analog to Digital Conversion

Questions

1. In your own words, explain the function of an A/D converter.

2. What would be the resolution if you were to use a 16-bit A/D converter in this experiment?

3. How does the voltage divider equation relate to the wiper terminal of the pot? What would you expect
the output to be if the resistors are equal? Can you prove this?

4. How do the measurements taken at the wiper terminal of the pot in this experiment differ from those
taken in Experiment #1? What is gained by using the ADC0831 for measurements instead of just using a
BASIC Stamp I/O pin to check the voltage?

5. Given the resolution of our 8 bit A/D converter, when the voltage on the pot is set to 3.6 volts, what
decimal value will be displayed? Whats the binary value?

Challenge!

1. Use another jumper wire to connect the wiper terminal of the pot to an unused BASIC Stamp I/O pin.
Add a subroutine to the DVM program that monitors the state of the I/O pin set to input. Determine if
the threshold voltage you were working with in Experiment #1 is indeed 1.4 Volts.

2. Write a program that will monitor the analog value of the 100 k potentiometer, and alert you to the
fact that it has gone beyond a certain pre-set limit.

3. Write a program and build a circuit that creates a safety zone between 1.0 volts and 2.0 volts. If the
analog voltage goes outside of these boundaries, an LED blinks.

Page 62 Basic Analog and Digital Student Guide Version 1.0


Experiment #3: Basic Analog to Digital Conversion

4. Draw the complete schematic for Challenge #3, and modify the program so that the LED is only on when
the voltage (as set on the pot) is set on exactly 2.0 volts.

5. Assume the power supply on your board of education supplies 4.960 Volts. Develop a subroutine to adjust
the voltage measurements to this scale.

There is a wide variety of electronic applications where analog signals are


measured and digital devices are used to process the analog signal data. In
Why did I this experiment, we used a BASIC Stamp and A/D converter combination to
learn it? construct a digital DC voltmeter. We'll be using the BASIC Stamp DC-DVM in
several of the remaining experiments. There is a surprising variety of uses
for such a device as you will discover with each new experiment.

How can I In developing the digital voltmeter, the process of sampling voltage,
converting it, and processing it in digital form was introduced. An example
apply of another use for an A/D interface is the digital sampling of the analog
this? signal from a microphone for digital recording purposes. Another example
that could make use of the circuit we built is a door sensor. Our
potentiometer could be attached to a door hinge, and the analog
information could be used to monitor how far the door is open. This circuit could in turn be incorporated into
a larger system that controls how far open the door swings.

The field of analog to digital conversion is an industry in itself. There are semi-conductor manufacturing
companies that specialize solely in creating A/D conversion chips and systems. Whether youd like to design at
the component level, or at the integrated circuit level, there will always be a need for creative analog
interfacing simply because the world isnt black and white (binary), its all the colors in-between as well
(analog).

Basic Analog and Digital Student Guide Version 1.0 Page 63


Experiment #3: Basic Analog to Digital Conversion

Page 64 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

Experiment #4:
Build a Resistive Ladder Network
Basic Digital to Analog
Conversion Digital to analog conversion (D/A conversion) is, for the most
part, the reverse of A/D conversion. With A/D conversion, we
started with a continuous voltage range at the converter's input. The A/D converter rounded to the nearest
voltage step and sent a binary output indicating which step it measured.

D/A conversion starts with a binary number as the input, and the output is a voltage step. While the A/D
process starts with an analog input and ends with a binary output, the D/A process starts with a binary input
and ends with a voltage step for an output. It's not a true analog value that varies continuously, it's a discrete
voltage that varies in steps.

The term resolution was introduced at the end of Experiment #3. Since a D/A converter's output is always
going to get rounded to a voltage step (a discrete voltage value) it's important to pick the right resolution for
your D/A converter. Remember that with higher resolution comes higher precision, but it typically comes at
the price of greater expense, more memory, and more processing steps.

The number of voltage levels a D/A converter can produce is given by how many counting numbers you can get
from the number of binary bits in the resolution. We can use the combinations equation again to figure this
out.

combinations = 2bits

The D/A converter we will use in this experiment has 4-bit resolution, so the number of output voltage levels
for the converter will be:

combinations = 2bits = 24 = 16

In Experiment #3, we used an integrated circuit, which performed the A/D conversion. In this experiment, we'll
build a D/A converter using resistors. It's called a resistive ladder network, and adding or removing resistors
can be done to change the resolution of the converter. With a resistive ladder network, if you start with a 4-
bit converter, and you want to increase the resolution by 1-bit, all it takes is two extra resistors added to the
network.

Basic Analog and Digital Student Guide Version 1.0 Page 65


Experiment #4: Basic Digital to Analog Conversion

In this experiment, we will build a resistive ladder network and program the BASIC Stamp to make the
network do D/A conversion. PBASIC will be used to program the BASIC Stamp to send the resistive ladder
network sets of binary voltage levels. These sets of binary voltages are converted by the resistive ladder
network to discrete output voltages.

The DVM from Experiment #3 will be used to measure the converter's output voltages. Measuring all the D/A
converter's output levels is called a voltage sweep. We will use PBASIC to automate our DVM to perform the
entire voltage sweep. That way, the D/A converter's output voltages can be measured without manually
repeating each measurement.

Parts Required
Gather these parts from your parts kit and let's get started:

(6) 2 k ohm resistors


(3) 1 k ohm resistors
(1) ADC0831 A/D Converter
(10) Jumper wires
(1) Red LED
(1) 270 ohm resistor

The resistive ladder network for this experiment is shown in shown in Figure 4.1. The name comes from the
fact that the resistor network in the schematic resembles a ladder. It's definitely an inexpensive alternative
compared to a integrated circuit digital to analog converter (D/A converter or DAC). A few resistors are a
fraction of the cost of an integrated circuit.

Page 66 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

DAC
Output
Figure 4.1: Resistive Ladder P7
D/A Converter. This resistive 2k
1k 2k
ladder network can be used as a
D/A converter. The binary P6
number input is sent in parallel 2k Vss
as 4-bits across 4 separate data 1k
lines, P4 through P7. As long as P5
the value of all four bits are
2k
present at the same time, the 1k
output of the D/A converter P4
output will be the intended
discrete voltage value. 2k
2k

Vss

This being the case, why doesn't everybody use resistive ladder networks for A/D and D/A conversion? The
resistive ladder network is also used in many A/D and D/A integrated circuits, such as the ADC0831. The
resistors used in integrated circuits are microscopic implants on the surface of a silicon wafer. One advantage
of IC converters is that they have a high degree of accuracy. Another advantage an IC has is extra built in
circuitry similar to the voltage follower we built in Experiment #1.

Basic Analog and Digital Student Guide Version 1.0 Page 67


Experiment #4: Basic Digital to Analog Conversion

Build the circuit as shown in Figure 4.2. Pay careful attention to the values
of the resistors as well as what each resistor connects to. If your circuit
Build It from Experiment #3 is still intact, just remove the potentiometer and build
the resistive ladder network near the sockets for pins P4 through P7. The
input lead to the DVM, which was connected to the wiper terminal on the
potentiometer, should now be connected to the output of the D/A
converter. Be sure to pay close attention so that the resistors don't touch each other except where they're
supposed to on the breadboard nodes.

Voltmeter DAC
Input Lead Output
Vdd
Figure 4.2: Schematic.
The DC voltmeter from
P7
Experiment #3 is connected 8 5
to the output of the Vdd Vref 2K
1K 2K
resistive ladder network P0 1
/CS
D/A Converter. P6
AD 0831
A/D Vin(+) 2 Vss
2K
Converter 1K
P1 7 4 P5
CLK Gnd
P2 6 2K
DO 1K
3 P4
Vin(-)
2K
2K

Vss

It's best to try to wire the circuit directly from the schematic in Figure 4.2. This will be a complex circuit to fit
on the breadboard. The placement of the parts and other wiring specifics are usually left up to the person
building the circuit, and you're now on your own!

Page 68 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

Not only can we use the DVM to measure the output voltage from the D/A
converter, we can automate the testing process to measure all 16 the D/A
Program It converter's output voltage levels. This might not be a big deal for just 16
measurements, but just imagine trying to test all 4096 voltage steps on a
12-bit converter!

With some relatively simple additions to the code from Experiment #3, which was saved as file P3_1R3.bs2, we
can control both devices. PBASIC can be used to instruct the BASIC Stamp to send an output signal to the D/A
converter. The code for this will be added to the final version of Program Listing 3.1. This way we can use our
DVM from this experiment to measure the D/A converter's output

Program Listing 4.1 is shown below. It's the final revision of Program Listing 3.1 with a subroutine labeled
DAC: added to send binary voltages to the D/A converter. There are also a few additional changes that are
pointed out using comments such as ' which means add this line and ' which shows the lines that have
been changed.

If you saved the program listing from Experiment #3, add and modify the code for this experiment, and save
the program under the name P4_1R1.bs2. If you do not have the code from Experiment #3, enter the entire
program listing below using the BASIC Stamp editor and make sure to save it for future use. When the circuit
is built and the code is entered and saved, run Program Listing 4.1, and let's see how it works.

'Program Listing 4.1 '


'Digital Voltmeter (DVM)
'D/A Converter Added '

'Declarations
adcbits var byte
v var byte
R var byte
v2 var byte
v3 var byte
n var nib '

CS con 0
CLK con 1
D0 con 2

'start display
debug cls

'Main routine
main:

Basic Analog and Digital Student Guide Version 1.0 Page 69


Experiment #4: Basic Digital to Analog Conversion

gosub DAC '


gosub ADCDATA
gosub CALC_VOLTS
gosub DISPLAY
goto main

DAC: '
n = 11 '

output 7 '
output 6 '
output 5 '
output 4 '

out7=n.bit3 '
out6=n.bit2 '
out5=n.bit1 '
out4=n.bit0 '

return '

ADCDATA:
high CS
low CS
low CLK
pulsout CLK,210
shiftin D0,CLK,msbpost,[adcbits\8]
return

CALC_VOLTS:
v=5*adcbits/255
R=5*adcbits//255
v2=100*R/255'
v3=100*R//255
v3=10*v3/255
if v3<5 then skip_a_line
v2=v2+1
skip_a_line:
if v2<100 then skip_out
v=v+1
v2=0
skip_out:
return

Page 70 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

DISPLAY:
debug home, cr, cr, "Decimal value to DAC: ", dec2 n '
debug cr, cr, "Binary value to DAC: ", bin4 n '
debug CR, CR, "DVM Reading: ", dec1 v, ".", dec2 v2, " Volts"
return

The Output

Given perfect resistor values, the output would be 3.00 Volts. The resistors used in this sample have a 10%
tolerance. This means that the measured resistance for each resistor should have a value within 10% of
what its supposed to be. Because of this, we can expect the output to be slightly different than whats
expected, such as the measured value in Figure 4.3. Given perfect resistor values, the measurement would be
2.20 Volts. Check for propagated errors; might have to re-document.

Decimal Value to DAC: 11


Figure 4.3: Debug Output for
Binary Value to DAC: 1011
Program Listing 4.1.
DVM Reading: 2.25 Volts

About the Code

The first of these two comments is updated to indicate that this is Program Listing 4.1. The second comment
is added to indicate that a function was added to the DVM that does D/A conversion.
'Program Listing 4.1
'D/A Converter Added to DVM

A nibble size variable n is added to the declarations section, and it will be used to store the binary value for
the D/A converter.

n var nib

A gosub command is added to the main routine that sends the program to the DAC: subroutine.

gosub DAC

Basic Analog and Digital Student Guide Version 1.0 Page 71


Experiment #4: Basic Digital to Analog Conversion

This is the start of the digital to analog conversion (DAC) subroutine, so it's descriptively labeled DAC:. The
value of n is set to 11. This means that the output should be n steps above 0 on an output scale of 0 to 16. The
value of n can be changed to specify voltage.

DAC:
n = 11

The BASIC Stamp I/O pins connected to the D/A converter are set to output. These commands are normally
found in the declarations section. If they were placed in the declarations section, the program would run
faster because these commands would only be done once at the beginning of the program. Instead, they are
executed each time the subroutine is run. The reason they were placed in the subroutine is to make it easier
to present some new PBASIC techniques.

output 7
output 6
output 5
output 4

Next, the BASIC Stamp's parallel binary output is sent to the D/A converter. We are using the same command
for sending outputs that was used in Experiments #1 and #2, but there is a new feature added. The variable n
has an extension to indicate which bit in the nibble value is being used. For example, the command
out7=n.bit3 sets the output value of pin P7 equal to the value of bit3 in the nibble variable n. Since we set
the value of n to 11, the binary value of n is 1011. Bit 3 is the leftmost bit of the binary number, so it's 1,
which means the output value of P7 is set high. Also, when n = 11, P6 is set low, P5 is set high, and P4 is set
high.
out7=n.bit3
out6=n.bit2
out5=n.bit1
out4=n.bit0

That's all it takes for programming digital to analog conversion using a resistive ladder network. The return
command sends the program back to the command immediately following the gosub DAC command in the
main: routine.

return

Page 72 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

The first two lines in the DISPLAY: subroutine are modified to show the decimal and binary values of n, the
4-bit binary value used D/A output value.

debug home, cr, cr, "Decimal value to DAC: ", dec2 n


debug cr, cr, "Binary value to DAC: ", bin4 n

Modify the Code

If the D/A converter works as we expect, each time the value of n is incremented by 1, the D/A output should
increment by 0.2 Volts. Try starting with n=0 by modifying the value of n in the DAC: subroutine.

n = 0 '

Then run the program again with n=1.

n = 1 '

Then change n to 2 and run the program a third time.

n = 2 '

Continue for each value up to n=15

Figure 4.4 shows a sample measurement of a resistive ladder D/A conversion with the value of n set to 15.
Remember that the 10% resistors lead to some error in the output. In Experiment #3, we were interested in
programming our DVM for accurate calculations to the nearest hundredth of a volt. In this experiment,
anything within 10% of the expected value is fine. So your end output when n=15 might be as low as 2.7 Volts
or as high as 3.3 Volts. If the errors are larger than that, double check to make sure that a 1k resistor didnt
get swapped with a 2k somewhere in the resistive ladder.

Decimal value to DAC: 15


Figure 4.4: Debug Output for
Program Listing 4.1, Revision Binary Value to DAC: 1111
1.
DVM Reading: 3.10 Volts

Basic Analog and Digital Student Guide Version 1.0 Page 73


Experiment #4: Basic Digital to Analog Conversion

Addressing

Addressed: Until now, weve been addressing each of the I/O lines one at a time.
When an I/O pin is addressed, it means This works well whenever you need to have control over the status
that a value has been written into a of a particular control line. For example, a single LED, is easily
particular place in the BASIC Stamp's addressed by the individual I/O pin to which it is connected using
RAM. For example, a particular memory
outp=value, where p is a pin number between 0 and 15, and
location can be set high to set a given I/O
pin to be an output. Another address value is either 0 or 1.
might be used to set the pin high or low.
Since the I/O pins (P4 through P7) are used as outputs in this
Performing these operations one bit at a experiment, it would be easier and more efficient to have a method
time is not always efficient. The memory
locations are adjacent to each other so of addressing this group of bits. Notice that it takes four lines of
that the operations can be performed 1 code just to set up the bits as outputs, and then it takes 4 additional
nibble (4-bits) at a time or one byte (8- lines to individually set each bit. Its not a big deal now, but as time
bits) at a time, or even a word (16-bits) at goes on and you begin to create more complex programs, you may
a time.
find yourself looking for ways to get the most out of the least code.

There are two registers that we need to set to control output on a


specific group of I/O lines. The first register is called direction. The command output sets the direction as
an output. Conversely, input sets the I/O line up as input. The second is the data register. If the I/O pin has
been set up as an output, then this registers data can be set to either 0 or 1. This in turn sends either a low
or high signal to that pin, and the measured output will either be 0 or 5 Volts.

Certain commands in PBASIC allow us to directly address its I/O lines as a word (16 individual bits), two bytes
(two sets of 8 individual bits) or as 4 nibbles (four sets of four individual bits). To modify our code, we want to
address a nibble at a time, and the four bits that were using are P4-P7. According to the BASIC Stamp Manual
Version 1.9 (which you should have a copy of by now - its free at www.stampsinclass.com and printed copies
are not expensive) the group P4-P7 is called nibble b. The next set of four (P8-P11) is nibble c, and so on.
{Input/Output variables}.

Lets try using this in a program and figure out how it works. Rewrite the DAC: subroutine in Program Listing
4.1 as follows:

DAC:

n = 11

dirb = 15
outb = n

Page 74 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

return

Figure 4.5 shows the output is identical to the previous version of the DAC: subroutine. We did the same job
with two lines of code instead of eight.

Decimal Value to DAC: 11


Figure 4.6: Debug Output for
Binary Value to DAC: 1011
Program Listing 4.1, Revision 2.
DVM Reading: 2.25 Volts

Here is how to count from 0 to 15 using a nibble:

0 = 0000 4 = 0100 8 = 1000 12 = 1100


1 = 0001 5 = 0101 9 = 1001 13 = 1101
2 = 0010 6 = 0110 10 = 1010 14 = 1110
3 = 0011 7 = 0111 11 = 1011 15 = 1111

When nibble b is selected using dirb, each bit in the number dirb is set equal to a value corresponding to a
data direction as shown below:

Bit in nibble B 3 2 1 0
I/O pin P7 P6 P5 P4

If we used the command dirb =4 the following direction register bits would be set like this:

Bit value 0 1 0 0
I/O pin P7 P6 P5 P4

This would result in I/O pin P6 being set as an output, and all the other pins (P0,P1,P3) set as inputs. Hence the
command dirb=15 (by virtue of the fact that all four bits are a 1) sets up each of the I/O lines as outputs.

Sweeping the value of n from 0 to 15 should result in the same values as before.
A truly powerful aspect of using this method of addressing is that we can use PBASIC to count up and down or
access values from a look up table to automatically address the I/O pins. The result is that we can program the
BASIC Stamp to more effectively control the D/A converter output.

Basic Analog and Digital Student Guide Version 1.0 Page 75


Experiment #4: Basic Digital to Analog Conversion

Modify the code immediately following the 'START DISPLAY label in Program Listing 4.1. First, modify the
debug cls command, then add a second line as shown.

'Start display
debug cls, "DAC Nibble Values", cr '
debug "Decimal Binary DVM", cr '

Modify the main: subroutine as shown:

'Main routine
main:
for n = 0 to 15
gosub DAC
gosub ADCDATA
gosub CALC_VOLTS
gosub DISPLAY
next
stop
goto main

Delete the line that sets the value of n in the DAC: subroutine. Once that's done it should look like this:

DAC:
dirb = 15
outb = n
return

Also modify the DISPLAY: subroutine as shown.

DISPLAY:
debug dec2 n, " ", bin4 n, " ", dec1 v, ".", dec2 v2, " Volts", cr
return

Figure 4.7 shows the output. Try that with a hand held voltmeter and youll begin to see the usefulness of
combining the BASIC Stamp with analog interfaces. Imagine trying to test all 4096 levels of a 12-bit DAC one
at a time!

Page 76 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

DAC Nibble Values


Decimal Binary DVM
00 0000 0.00 Volts
01 0001 0.20 Volts
02 0010 0.41 Volts
03 0011 0.61 Volts
04 0100 0.82 Volts
05 0101 1.02 Volts
Figure 4.7: Debug Sample
06 0110 1.24 Volts
Output for Program Listing 4.1,
07 0111 1.45 Volts
Revision 3.
08 1000 1.63 Volts
09 1001 1.84 Volts
10 1010 2.04 Volts
11 1011 2.25 Volts
12 1100 2.47 Volts
13 1101 2.67 Volts
14 1110 2.88 Volts
15 1111 3.10 Volts

This is a very efficient way to collect your voltage sweep data. Looking at the data for the voltage sweep brings
several things to light. First, the voltage output for the D/A converter is always a little high. Second, the error
increases as the output voltage increases. Third, the largest error is 0.1 volts. This kind of data can be
exceedingly useful in electronics design, and the automated testing process is a huge time saver.

The Voltage Follower

Let's use the voltage sweep to analyze what happens when the output of the D/A converter is connected to
another circuit. We'll use the output of the D/A converter to drive an LED circuit. First we'll connect the D/A
converter output directly to the input of the LED circuit. Then we'll use the voltage follower as an
intermediate step between the D/A converter output and the LED circuit input.

Figure 4.7 shows the D/A converter with an LED circuit added. The LED circuit is the "load" that the D/A
converter must "drive". Run a voltage sweep on this circuit, and fill in the table below. Then try the voltage
sweep using the output of the voltage follower in as shown in Figure 4.8. Fill out the same table of voltage
sweep information for this second circuit, and compare the two. The voltage follower in Figure 4.8 is referred
to as a buffer.

Basic Analog and Digital Student Guide Version 1.0 Page 77


Experiment #4: Basic Digital to Analog Conversion

Vdd
Figure 4.7: D/A
Circuit without
P7
a Buffer. The 8 5
LED circuit has Vdd Vref 2k
1k 2k
no voltage P0 1
follower to /CS P6
AD 0831 270
separate it from A/D Vin(+) 2
2k
Vss
the resistive Converter 1k
ladder network. P1 7 P5
CLK 4
The LED is an Gnd Vss
"unbuffered" P2 6 2k
DO 1k
load for the D/A 3
converter. Vin(-) P4
2k
2k

Vss

Table 4.1: D/A Converter Output Without Buffer

Decimal Binary DVM (Volts)


00 0000 ___________
01 0001 ___________
02 0010 ___________
03 0011 ___________
04 0100 ___________
05 0101 ___________
06 0110 ___________
07 0111 ___________
08 1000 ___________
09 1001 ___________
10 1010 ___________
11 1011 ___________
12 1100 ___________
13 1101 ___________
14 1110 ___________
15 1111 ___________

Page 78 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

Figure 4.9: D/A


Circuit With a Vdd
Buffer to separate
the LED circuit's
input from the D/A 2
-
8
Vdd
converter's output. A
1
SAVE THIS CIRCUIT 3
+
4 LM358
FOR EXPERIMENT
#5. 8 5 P7
Vdd Vref Vss
2k
1k 2k
P0 1
/CS P6
AD 0831 270
A/D Vin(+) 2 Vss
2k
Converter 1k
P1 7 Vss
CLK 4 P5
Gnd
P2 6 2k
DO 1k
3 P4
Vin(-)
2k
2k

Vss

Table 4.2: D/A Converter Output with Buffer

Decimal Binary DVM (Volts)


00 0000 ___________
01 0001 ___________
02 0010 ___________
03 0011 ___________
04 0100 ___________
05 0101 ___________
06 0110 ___________
07 0111 ___________
08 1000 ___________
09 1001 ___________
10 1010 ___________
11 1011 ___________
12 1100 ___________
13 1101 ___________
14 1110 ___________
15 1111 ___________

Basic Analog and Digital Student Guide Version 1.0 Page 79


Experiment #4: Basic Digital to Analog Conversion

Comparing the two tables, it should be fairly clear that the buffer (voltage follower) eliminated a problem
caused by connecting the LED circuit directly to the D/A converter's output. The voltage of the D/A output
without a buffer reached a maximum well below the D/A converter's 3 Volt maximum. On the other hand, the
buffered output went all the way to 3 Volts with no problem.

The reason for this goes back to Ohm's Law: V = I R (Voltage equals current multiplied by resistance). Each
BASIC Stamp I/O pin can supply up to 20 mA of current. In the case of the resistive ladder network without the
buffer, the BASIC Stamp I/O pins reached their maximum current output. Meanwhile, the resistance seen by
the I/O pins stayed about the same. In other words, I R reached a limit because I (the current) could no
longer increase, and R is a fixed value. So the output voltage is equal to a current value that can't get any
higher multiplied by a fixed resistance. This is why the voltage stops increasing.

Aside from isolating two circuits from each other, an op-amp in voltage follower configuration can typically
supply more current than the circuit connected to its input. The name buffer is commonly used when a
voltage follower is used to supply extra current.

The circuit from figure 4.9 will also be used at the beginning of Experiment #5, so do not disassemble the
circuit after completing Experiment #4.

Page 80 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

On the lines below, insert the appropriate words from the list on the
What did I left.
learn?

binary A set of ___________ voltage values sent to the inputs of a resistive ladder
network results in a ___________ voltage level at the output. This method is an
discrete inexpensive alternative to integrated circuits. Its advantages are flexibility in
resolution and low cost. Its main disadvantage is accuracy.
bit
The .bit extension can be attached to a variable to select a particular
output ___________ within a nibble, byte or word. This can be used to select bits from a
binary number in memory and set ___________ values equal to those bits.
bit
PBASIC can be used to address BASIC Stamp I/O pins a bit at a ___________ at a
current time, or alternatives exist for ___________ nibble, byte or word size groups of I/O
pins. This allows the ___________ and output values of the I/O pins to be
addressing addressed as groups of bits instead of as a single bit.

direction A voltage ___________ can be run on a D/A converter. This allows one to view the
D/A converter's outputs for all possible binary inputs. The BASIC Stamp can be
sweep programmed to ___________ this process and display the data in a table format.

automate The voltage follower can be used as a buffer, which can supply extra ___________
to the input of a circuit connected to the D/A converter's output.

Basic Analog and Digital Student Guide Version 1.0 Page 81


Experiment #4: Basic Digital to Analog Conversion

Questions

1. What function is provided by a D/A converter?

2. What type of D/A converter did we create in this experiment and what are its limitations?

3. Why does the D/A voltage jump from one value to another, unlike the voltage available on a pot?

4. Whats a nibble?

5. 1101 is what value in the decimal number system? What voltage would you expect from the D/A
converter output if you sent it this binary number?

Challenge!

1. Create an 8 bit resistive ladder D/A converter. Draw the complete schematic.

2. Write a program that will step through 256 different analog voltages. Each voltage should be present
for 100 milliseconds on the voltmeter.

Page 82 Basic Analog and Digital Student Guide Version 1.0


Experiment #4: Basic Digital to Analog Conversion

There are many different real world circuits that require some sort of
analog voltage. For example, when you listen to a compact disc, youre
Why did I listening to an analog signal (from the microphone) that has been digitized
learn it? (A/D) and stored on the CD media. This digital data is then output to an
amplifier and speaker (after undergoing the D/A process).

When designing commercial products, it is your responsibility to determine the most appropriate (and cost
effective) method to accomplish a given task. A resistive D/A converter is a very economical method to get an
analog voltage from a digital device.

You've just built a variable voltage source and a digital voltmeter on the
same breadboard. You also used some PBASIC Programming techniques to
How can I obtain information about the converter using a voltage sweep. One
apply this? application of this can be testing circuits, but there are many others. In
Experiment #5, we'll see how PBASIC can be used to control the volume of
tones emitted by a speaker. In Experiment #7, we'll use D/A conversion to
control the brightness of an LED transmitting a signal to a photoresistor.

The applications for D/A and A/D interfaces combined with a microcontroller are only limited by one's
imagination. These techniques can be applied to automated houses, irrigation systems, rocket guidance
systems, and robotics to name a few. Control systems engineering is a field of study within electrical
engineering that you might look into if you find designing such systems interesting.

Basic Analog and Digital Student Guide Version 1.0 Page 83


Experiment #4: Basic Digital to Analog Conversion

Page 84 Basic Analog and Digital Student Guide Version 1.0


Experiment #5: Time Varying Signals

In this experiment we'll view signals with the Stamp-O-


Experiment #5: Scope. To do this we'll use the BASIC Stamp along with the
Time Varying Signals A/D and D/A circuits built in Experiments #3 and #4 to
emulate the function of an oscilloscope.

The voltage output of the resistive ladder


network will be varied with time, and the
Oscilloscope: changes will be tracked using our
A device that measures and displays time-varying voltage signals. The oscilloscope emulator, the Stamp-O-Scope.
oscilloscope is a common tool used by many electronics technicians and The Stamp-O-Scope will gather its input
engineers to display these signals. The signals of interest often repeat
themselves many times each second. The oscilloscope can be used to
voltage data from the ADC0831 and display it
view the general shape of the signal, how fast it repeats itself, and the graphically in the debug window.
maximum and minimum voltage values of the signal as it repeats itself.
We'll view two different signals using the
Stamp-O-Scope, and we'll use the D/A
converter to adjust the attributes of both
signals. The first signal we'll work with is
called a triangle wave, and the second is
called a pulse train. The LED will be used to
monitor the activity of both signals.

Unlike a normal oscilloscope, the Stamp-O-


Scope cannot monitor voltage signals at
frequencies in the audible sound range.
However, the BASIC Stamp can easily send a
voltage signal in the audible sound range via
the D/A converter. This signal can be used to
make a speaker emit tones of adjustable
pitch and volume.
Figure 5.1: Oscilloscope displaying a sine wave output from Program The pitch and volume will be adjusted by
Listing 5.3.
changing two of the pulse train's properties.
Frequency: But first, let's get started and view these
The rate at which a time varying signal repeats its self. Frequency is properties with the Stamp-O-Scope.
measured in repetitions per second. The name Hertz (Hz) is used when
referring to frequency. One Hertz is one repetition per second, that is: Also in this experiment, the BASIC Stamp is
1 Hz = 1 repetition/second = 1/s used to generate sine waves (see Figure 5.1)
of adjustable frequency. These sine waves
are used to make musical notes.

Basic Analog and Digital Student Guide Version 1.0 Page 85


Experiment #5: Time Varying Signals

The same circuit used in Experiment #4, Figure 4.8 is used


to begin this experiment. Later, the LED circuit is replaced
Parts Required with a piezoelectric speaker circuit. For this experiment
you'll need the following parts:

(6) 2 k ohm resistors


(3) 1 k ohm resistors
(1) ADC0831 A/D Converter
(10) Jumper wires
(1) Red LED
(1) 270 ohm resistor
(1) Piezoelectric speaker
(1) 1.0 uF Electrolytic Capacitor
(1) 100 ohm resistor

The piezoelectric speaker shown in Figure 5.2 has positive and negative terminals shown on both the circuit
symbol and the component. The speaker from the Analog and Digital Parts Kit has a plus (+) on its topside
above the appropriate pin.
+
+
Figure 5.2: Piezo Speaker.
Circuit symbol and part.

The electrolytic capacitor shown in Figure 5.3 also has a positive and negative terminal. The wire that comes
out of the metal canister closest to the black stripe is the negative terminal. The arrows (>>) on the black
stripe point to the negative terminal. The canister also has the value printed on it. 1uF or 1MF indicates 1
micro-Farad while 10uF or 10MF indicates a 10 micro-Farad capacitance value.

Page 86 Basic Analog and Digital Student Guide Version 1.0


Experiment #5: Time Varying Signals

Figure 5.3: Electrolytic


Capacitor Circuit Symbol

+
and Component
1uF 1uF25V
- >> >>

If you saved the circuit that was developed in experiments #3 and #4, you are ready for the next step.
Otherwise, rebuild the circuit shown in Experiment #4, Figure 4.9.

Start with an unmodified version of Program Listing 4.1, and make the
following changes. Changed lines are shown with and added lines are
Program It shown with a .

Modify the first line as shown:

'Program Listing 5.1 '

Insert a routine labeled loop: between the debug cls command and the main: label as shown below:

'START DISPLAY
debug cls

loop: '

for n = 7 to 15 '
gosub main '
next '

for n = 14 to 8 '
gosub main '
next '

goto loop '

Basic Analog and Digital Student Guide Version 1.0 Page 87


Experiment #5: Time Varying Signals

Modify the main: routine as shown. There are two changes to make. First, the gosub CALC_VOLTS
command should be commented with an apostrophe, and second, the goto main command should be
changed to a return command.

main:

gosub DAC
gosub ADCDATA
'gosub CALC_VOLTS ' (Comment this line!)
gosub DISPLAY

return '

Modify the DAC: subroutine so it looks like this:

DAC:
outb=n
pause 30
return

Also modify the DISPLAY: subroutine from Program Listing 4.1 so it looks like this:

DISPLAY:
v3=adcbits/8
debug rep " "\v3,"*",cr
return

The Output - A Triangle Wave

Save the program as P5_1R0.bs2, and download it to your BASIC Stamp. The Stamp-O-Scope output should
look like Figure 5.4. The red LED on the breadboard should be gradually getting bright and then dim again at
the same pace as the triangle shaped wave varies in the debug window. The asterisk in the bottom line of the
debug window indicates the current voltage measurement. The further right the asterisk appears in the debug
window, the higher the measured voltage.

Page 88 Basic Analog and Digital Student Guide Version 1.0


Experiment #5: Time Varying Signals

Figure 5.4: Output Sample


for Program Listing 5.1 is the
Stamp-O-Scope display. The
waveform displayed is
commonly referred to as a
triangle wave.

If you were to rotate the Stamp-O-Scope display a quarter turn counter-clockwise, it would resemble the
display of a normal oscilloscope. Figure 5.5 shows the Stamp-O-Scope rotated this way. It also shows three of
the most basic measurements taken on an oscilloscope: amplitude, frequency, and DC offset. An oscilloscope
typically displays time on the horizontal scale and voltage on the vertical scale. Time passes across an
oscilloscope screen from left to right, and as the wave gets higher in the screen, the voltage is higher. Most
graphs of time varying waveforms are also presented in this format.

Basic Analog and Digital Student Guide Version 1.0 Page 89


Experiment #5: Time Varying Signals

Voltage
Figure 5.5: Output
Sample
A more conventional
way of viewing time-
varying waveforms.
This is the way they are Period
typically displayed
using an oscilloscope.
The amplitude, period
and DC offset are
three common
measurements taken Amplitude
using an oscilloscope.

Note how the time axis


is the horizontal axis in
this picture, and the
voltage axis is the
vertical axis. DC Offset

Time

The period of a waveform is the amount of time it takes to repeat itself. In this case, that amount of time is
about 1 second. The frequency is the inverse of the period, so we can use a simple equation to determine the
frequency when we know the period:

f = 1T

The term f is the frequency, measured in Hertz (Hz), and T is the period, measured in seconds (s). Since the
period is one second, and 1 1 = 1, the frequency is also 1 Hz. As another example, if the period is 1/100 of a
second, the frequency is 1, 1/100 = 100 Hz.

Page 90 Basic Analog and Digital Student Guide Version 1.0


Experiment #5: Time Varying Signals

Amplitude and DC offset are two quantities related to voltage that are measured differently for different
signals. The amplitude shown in Figure 5.4 is called the peak-to-peak amplitude. The D/A converter's output is
programmed for a maximum of 3 Volts and a minimum of 1.6 Volts. Therefore the peak-to-peak amplitude is
3 1.6 Volts = 1.4 Volts.

The DC offset is the difference between 0 Volts and the waveform's minimum value. We already know the
lowest point of the sample triangle wave is 1.6 Volts, and that's the DC offset.

An alternative reference point for both Amplitude and DC offset is half way between the upper and lower
peak. The half way point would be (3 + 1.6) / 2 Volts = 2.3 Volts. The amplitude would be 3 2.3 Volts = 0.7
Volts. The DC offset would be 1.6 + 0.7 Volts = 2.3 Volts. (Add Picture)

About the Code

The main: routine is has been relegated to a subroutine in favor of the loop: routine. The loop: routine
increments and decrements up and down counts for n, the value sent to the D/A converter. This is why the
measured output of the D/A converter increases and then decreases in the Stamp-O-Scope display.

Each time a for-next loop in the loop: routine increments the value of n, it also sends the program to the
main: subroutine.

loop:

for n = 7 to 15
gosub main
next

for n = 14 to 8
gosub main
next

goto loop

The main: subroutine still does the same job it did in the previous experiment. The only difference is that now
it's a subroutine. The CALC_VOLTS: subroutine is not necessary for our Stamp-O-Scope display, so the
gosub CALC_VOLTS: command is commented. To save EEPROM memory, you could also delete the entire
subroutine. Keep that in mind if you use this in a larger application and start to run out of EEPROM memory
to store your program.

Basic Analog and Digital Student Guide Version 1.0 Page 91


Experiment #5: Time Varying Signals

main:

gosub DAC
gosub ADCDATA
'gosub CALC_VOLTS
gosub DISPLAY

return

This is the simplest form of DAC subroutine covered in Experiment #4.

DAC:
outb=n
pause 30
return

The debug command in the DISPLAY: subroutine is what places the asterisks in the location in the debug
window corresponding to the magnitude of the measured voltage at that instant. The higher the voltage
measurement, the further to the right the cursor is printed in the debug window.

The debug modifier rep is what causes the " " (single space) character to be printed over and over again. In
this case it's repeated adcbits/4 (the value of adcbits divided by four) times. After all those spaces, an
asterisk and carriage return are printed so that the next asterisk for the next voltage measurement will
appear on the following line.

DISPLAY:
debug rep " "\adcbits/4,"*",cr
return

How many spaces before the asterisk is printed? Let's say we are measuring 3-Volts, the highest voltage level
the DAC is supposed to output. Remember that adcbits is the number sent by the ADC0831, and it's between
0 and 255 on a 5-Volt scale. Therefore when 3-Volts is measured:

adcbits = (3/5) X 255 = 153

The number of spaces is:

adcbits/4, which is 1534 = 38.25 = 38 rounded to zero decimal places.

The maximum voltage will place an asterisk 39 spaces across the debug window.

Page 92 Basic Analog and Digital Student Guide Version 1.0


Experiment #5: Time Varying Signals

Try changing the limits for n in the for-next loops in the main: routine. In this case, it will change both the
amplitude and the period of the triangle wave. This is an example where the limits of the for-next loop are
set to the voltage output limits of the resistive ladder network D/A converter.
loop:

for n = 1 to 15 '
gosub main
next

for n = 14 to 0 '
gosub main
next

Note that both the amplitude and period of the waveform increased. This is because the BASIC Stamp is
programmed to pause for a fixed amount of time at each output voltage level. The pause statement is part of
the DAC: routine.

The Pulse Train

The next waveform we'll examine is called the pulse train, though a better name for it might be a rectangle
wave. For a pulse train, the amplitude is the voltage between the high and low voltage levels, and the DC offset
is the voltage between 0 volts and the low part of the signal. The period and frequency are the same for a
pulse train as they are for a triangle wave. So the period is still the amount of time the waveform takes to
repeat itself, and the frequency is still the number of times the waveform repeats itself in a second. The
frequency is also still the inverse of the period.

The loop routine can be modified to make a pulse train that has the same frequency of the original triangle
wave. The variable v3 is not used right now because we are skipping the CALC_VOLTS: subroutine. It can be
used to for counting up and down. The value of n, which controls the D/A converter output can be set to a high
value and a low value. Let's start with a high value of 3 Volts and a low value of 0 Volts. Modify the loop
routine, and save the modified program as P5_1R1.bs2

Basic Analog and Digital Student Guide Version 1.0 Page 93


Experiment #5: Time Varying Signals

loop:

for v3 = 0 to 15 '
n=15 '
gosub main
next

for v3 = 15 to 0 '
n=0 '
gosub main
next

goto loop

Run the program and view the pulse train. Is it really square? You can
adjust the value of n in the first for-next loop to change the
Pulse width: amplitude. You can change the values of n in the second for-next loop
A binary signal goes high-low-high- to get various DC offsets. Just remember that n has to be between 0
low-high-low... the pulse width is the and 15.
amount of time that a binary signal
stays high in between the lows.
Changing the limits of the first for-next loop changes the amount of
Duty cycle: time the signal stays high. In other words, you can change the pulse
The duty cycle is the ratio of time the width buy adjusting v3 in the first for-next loop.
signal stays high to the amount of
time it takes the signal to repeat
itself. In other words it's the pulse Changing the value of the limits of the second for-next loop adjusts
width divided by the period of the the duration of the low portion of the signal.
signal.
By changing both the duration of the low and high portion of the signal
proportionately, you can change the frequency without affecting the duty cycle. By changing only one of the
two sets of limits, you change the duty cycle as well as the frequency of the signal.

Now let's run the frequency of this pulse train up into the audible sound frequency range and listen to the
result of adjusting these signal characteristics. Remove the ADC0831 from the circuit. Also, replace the LED
circuit with the piezoelectric speaker circuit shown in Figure 5.6.

Page 94 Basic Analog and Digital Student Guide Version 1.0


Experiment #5: Time Varying Signals

Vdd

2 8
-
A
1
+
3 4 LM358

Figure 5.6: P7 100


Piezoelectric Vss
2k
Speaker Circuit 1k 2k
connected to the
P6
buffered output +
of the D/A Vss

+
2k
1k 1uF
converter. -
P5
2k Piezo
1k -

P4
2k
2k

Vss Vss

'Program Listing 5.2


'D/A Converter Making Sound
'n changes volume
'm changes frequency

n var nib
m var word

dirb=15

n = 15
m = 1

DAC:
outb = n
pause m

Basic Analog and Digital Student Guide Version 1.0 Page 95


Experiment #5: Time Varying Signals

outb = 0
pause m

goto DAC:

First, run the program as shown. The piezoelectric speaker should tick about every half-second indicating the
transitions between the high and low signal.

Next, change the value of m from 500 to 100, and note that the ticking is much quicker. Also try the values of
50, 20, 10, 5, and 1. Experiment a bit.

The value of m = 1 should cause the piezoelectric speaker to emit a fairly clear tone.

Next, let's change the value of the amplitude by varying the value of n. First, try the value of n = 1. The tone
should be the same, just much quieter. Next try the value of n =5. The tone is still the same pitch, just louder.
For values of n = 10 and 15, the volume should increase two more notches.

In this application, we caused the piezoelectric speaker to make sound by applying pulses using the BASIC
Stamp. We steadily increased the frequency by decreasing the amount of time the signal paused in its high
and low state, effectively decreasing the signals period. Since frequency is the inverse of period, decreasing
the period increased the frequency. When the frequency was increased the pitch of the tone also increases.
Next we changed the amplitude of the pulse train by changing the output value for the high signal. This
changed the volume of the sound made by the piezoelectric speaker.

Causing variations in air pressure creates sound. Any sound can be represented by some sort of time-varying
waveform. To cause the piezoelectric speaker to make sound, we sent a time varying voltage signal to its
input. The speaker converted the signal into motion of a membrane inside the plastic case. As the membrane
vibrated, it caused air pressure variations. Our eardrum (another membrane) senses these pressure
variations, and we, in turn, heard the tones.

The pulse train we sent to the piezoelectric speaker represented variations in air pressure. We varied the
amplitude of the signal to increase the amplitude of the air pressure variations, which in turn increased the
volume of the tone. The frequency of the pulse train was varied to change the frequency of the pressure
variations. This in turn changed the pitch of the tone.

Page 96 Basic Analog and Digital Student Guide Version 1.0


Experiment #5: Time Varying Signals

The Sine Wave and Pulse Width Modulation (PWM)

The BASIC Stamp has a built in function to generate tones similar to those you hear when you strike a tuning
fork. Disconnect the terminal of the 100 resistor connected to the buffer output (LM358 pin 1), and
connect it to P10 on the Board of Education as shown in Figure 5.7. These three circuit elements are all that's
necessary to connect to the BASIC Stamp to play tunes and tones.

P10
100

Figure 5.7: BASIC +


Stamp Music Circuit

+
1uF
-
Piezo
-

Vss

Without the piezoelectric speaker, the capacitor and resistor shown in Figure 5.7 work like a rechargeable
battery that charges and discharges over short periods of time. By applying lots of pulses to the circuit, the
voltage output can actually be shaped into a signal.

These pulses can be varied in width and applied more or less frequently. Depending on the pulse widths and
frequencies, the capacitor gains or looses voltage at varying rates. That's the gist of how pulse width
modulation (PWM) works, and it can be used to shape voltage signals. Figure 5.8 shows a sample of a PWM
signal applied to the input of an RC circuit as well as a sine wave output.

Basic Analog and Digital Student Guide Version 1.0 Page 97


Experiment #5: Time Varying Signals

Figure 5.8: Oscilloscope


Samples of a PWM signal
and a sine wave.

PWM Signal Sine Wave

Sine waves can be used to represent musical notes. When a sine wave is played on the piezoelectric speaker,
the sound has a significantly improved quality. The variations in air pressure caused by a tuning fork are
represented by a sine wave. Program Listing 5.3 defines an octave of musical notes and their corresponding
frequencies. A list of these musical notes is then played using freqout commands. Let's try it.

Reprogram the Circuit for Musical Notes

'Program Listing 5.3 - Charge!!!


C con 2093
C_Sharp con 2218
D con 2349
D_Sharp con 2489
E con 2637
F con 2794
F_Sharp con 2960
G con 3136
G_Sharp con 3322
A con 3520
A_Sharp con 3729
B con 3951

debug cls
freqout 10, 100,C
Debug home, "Frequency of PWM sine wave output is ", dec4 C, " Hz.", cr
freqout 10, 100,D
Debug "Frequency of PWM sine wave output is ", dec4 D, " Hz.", cr
freqout 10, 100,D_Sharp
Debug "Frequency of PWM sine wave output is ", dec4 D_Sharp, " Hz.", cr
freqout 10, 200,G
Debug "Frequency of PWM sine wave output is ", dec4 G, " Hz.", cr

Page 98 Basic Analog and Digital Student Guide Version 1.0


Experiment #5: Time Varying Signals

freqout 10, 100,D_Sharp


Debug "Frequency of PWM sine wave output is ", dec4 D_Sharp, " Hz.", cr
freqout 10, 200,G
Debug "Frequency of PWM sine wave output is ", dec4 G, " Hz.", cr

The Output

The output sample shown in Figure 5.9 is the last of the eight that are played. The tones sound significantly
better than the equivalent pulse trains, which in general have more of a kazoo sound to them.

Frequency of PWM sine wave output is 2093 Hz.


Figure 5.9: Debug Frequency of PWM sine wave output is 2349 Hz.
output displaying Frequency of PWM sine wave output is 2489 Hz.
the frequencies Frequency of PWM sine wave output is 3136 Hz.
played by Program Frequency of PWM sine wave output is 3498 Hz.
Listing 5.3.
Frequency of PWM sine wave output is 2349 Hz.

About the Code

The only new command introduced is freqout. The freqout command is used as follows:

freqout, pin, duration, frequency 1, frequency 2

We already know that pin is a number between 1 and 15 that refers to your choice of BASIC Stamp I/O pin,
P1 through P15. The duration is a number between 1 and 65535 that specifies how long the tone is played in
milliseconds (ms). The term frequency 1 is used to specify the frequency of the tone that gets played. A
second frequency (frequency 2) can be played simultaneously for some interesting effects. For example, the
tones you hear when you dial the telephone are actually two tones played simultaneously. The BASIC Stamp
also has a command for telephone tones called dtmf, which uses the same principle.

Basic Analog and Digital Student Guide Version 1.0 Page 99


Experiment #5: Time Varying Signals

What have I
learned? On the lines below, insert the appropriate words from the list on the
left.

voltage An oscilloscope is a tool used by many electronics technicians and engineers, and it
measures and displays ________________ signals. Amplitude, DC offset, phase shift,
period period, and ________________ are useful signal characteristics that can be measured
with an oscilloscope.
amplitude
An oscilloscope typically displays ________________ on the horizontal scale and
time ________________ on the vertical scale. ________________ and DC offset are two
quantities related to voltage that are measured differently for different signals.
inverse
For a pulse train, the amplitude is the voltage between the high and low signal. For a
Amplitude _________________ triangle wave, as with the sine wave, the amplitude is the
maximum deviation from the center line of the signal. For the sine wave and triangle
RC circuit wave, the ________________ is the voltage between the center line and 0-Volts.

frequency The frequency is the number of times a waveform repeats itself and the
________________ is the amount of time the waveform takes to repeat itself. The
symmetric frequency is the ________________ of the period.

sine Time varying voltage signals sent to a speaker can result in audible tones. Adjusting the
________________ of a voltage signal adjusts the volume of the tone. Adjusting the
time-varying frequency of the signal adjusts the ________________ .

pitch Musical notes are represented by ________________ waves oscillating at certain


frequencies. The BASIC Stamp uses pulse width modulation (PWM) sent to the input of an
DC offset ________________ to generate a sine wave at the output.

Page 100 Basic Analog and Digital Student Guide Version 1.0
Experiment #5: Time Varying Signals

Questions

1. What's the difference between the Stamp-O-Scope display and a regular oscilloscope display?

2. If the frequency of a signal is 1000 Hz, what's the period?

3. How can you adjust the scale to display finer variations in voltage using the Stamp-O-Scope? Hint: The
answer involves an adjustment to the PBASIC code for Program Listing 5.1.

4. How can you increase the refresh rate of the Stamp-O-Scope? Hint: examine the code again; what
factor limits the speed at which the signal is measured?

Challenge!

1. Modify Program Listing 3.1 so that it plays two notes simultaneously.

2. Modify the code and add a second lead that measures only 0 and 1 logic levels. Modify the code to display
voltage activity of this second lead and the Stamp-O-Scope input simultaneously on the same display.
Good luck!

3. If you succeeded with Challenge #1, add a potentiometer to the Board of Education and wire it as a
voltage divider. Hook the new, second input lead to the wiper terminal of the pot. Vary the pot above
and below threshold voltage and see if you can match the frequency of the triangle wave.

Basic Analog and Digital Student Guide Version 1.0 Page 101
Experiment #5: Time Varying Signals

4. A really cool thing to do would be to discover a phenomenon called phase shift. Connect the input lead of
the second channel you developed in Challenge 2 to the D/A converter output. Also, connect the channel 1
lead (ADC0831 Vin(+)) to the D/A converter output. Adjust the D/A converter to up count and down count
between 4 and 15. Note that there's a delay between the mid point of the triangle wave and the
transition of the pulse train. Adjusting the lower limits of the counting variables and notice that the delay
shifts. This delay is called phase shift.

The oscilloscope is an essential tool in the electronics industry, and many


hobbyists use them as well. This is a good first exposure to using the
Why did I oscilloscope and to viewing time-varying waveforms. If you find yourself
learn it? learning how to use an oscilloscope, some of the concepts introduced
here will make some of the functions of the buttons and dials easier to
learn.

Familiarity with the oscilloscope and with time-varying waveforms will


make it easier to understand explanations of various phenomena that
How can I vary with time. They appear in many chemistry, physics and electronics
apply this? texts.

Page 102 Basic Analog and Digital Student Guide Version 1.0
Experiment #6: Recording Frequency Data

Experiment #6: In the previous experiment we used the BASIC Stamp to


control a D/A converter to produce audible tones. In this
Recording Frequency experiment, we'll use a 555 timer to generate frequencies in
Data the audible sound range, then we'll use the BASIC Stamp to
sample and process the frequency data.

We'll start by viewing a pulse train generated by a 555 timer on a simplified version of the Stamp-O-Scope.
Two potentiometers will be used to control the frequency and duty cycle of the pulse train. After viewing the
pulse train's signal characteristics, the 555's output will be directed to a piezoelectric speaker. The 555's
output will also be connected to a BASIC Stamp I/O pin set to input. The BASIC Stamp will be programmed to
monitor and record the frequencies generated by the 555 timer.

Parts Required
This experiment requires the following parts:

(2) 100 K ohm potentiometers


(1) piezoelectric speaker
(1) 555 Timer
(1) 10 uF electrolytic capacitor
(1) 0.1 uF ceramic capacitor
(1) 1.0 uF electrolytic capacitor
(2) 2 K ohm resistor
(1) 100 ohm resistor

Not all the parts will get used at once on the same circuit. Certain capacitors and resistors are substituted in
the second circuit to increase the 555 timer's output frequency.

Figure 6.1 shows the circuit symbol and part drawing for the 0.1 uF capacitor from the Analog and Digital
Parts Kit. Unlike the electrolytic capacitors, this capacitor has no polarity. In other words, it doesn't matter
which terminal receives the higher voltage level. There's also no + and terminals, and the shape of the
circuit symbol is slightly different.

Basic Analog and Digital Student Guide Version 1.0 Page 103
Experiment #6: Recording Frequency Data

Figure 6.1: A 0.1 Micro Farad


capacitor. There is no polarity on this 0.1uF
capacitor.

Figure 6.2 shows the symbol and pin map for the 555 timer. As with the ADC0831, the circuit symbol for the
555 timer is drawn for convenience in the circuit diagram. This means that the locations of the pins on the
symbol and its size may change from one diagram to the next. The pin map, on the other hand, does not
change. Make sure to locate the index mark, and use the pin map in conjunction with the schematic while
wiring your circuits.

Index Mark
pin #1
4 8

Figure 6.2: Symbol and 7


1 8
pin map for 555 Timer.
As always, make sure to 6
2
2 7
locate the index mark NE555
when you place the part 3 6
on the breadboard. 555 Timer
4 5

1 3

The circuit in Figure 6.3 is essentially the same "astable multivibrator"


circuit used in Whats a Microcontroller. The circuit is used to
Build It generate a steady stream of pulses. There are two differences
between this circuit and the one from "What's a Microcontroller". The
first difference is that the 555 timer's output drives a piezoelectric
speaker circuit instead of an LED circuit. The second difference is that
this circuit has two potentiometers used as variable resistors instead of the single pot used previously. This
allows control the pulse width and duty cycle, of the output.

Page 104 Basic Analog and Digital Student Guide Version 1.0
Experiment #6: Recording Frequency Data

Build the circuit shown in Figure 6.3. Note that there is a lower case "nc" below two potentiometer terminals
in the figure. This stands for "not connected". Since the potentiometer is used as a single variable resistor
instead of a voltage divider, the third terminal doesn't get connected to anything. It's OK to plug the nc
terminal it into a row on the breadboard; just don't plug anything else into the same row.

Vdd
Vdd

8 P0
100k
POT A 7
4

nc

100k 555 Timer


POT B 6
3
100
nc 2 +

+
+

1uF
Figure 6.3: Astable 10uF -
-
Multivibrator circuit with 1
Piezo
adjustable high and low -
times.

Vss

After you've built the circuit, adjust the potentiometers until the piezoelectric speaker makes a steady, slow
tic-toc sound. A frequency of 1 Hz is desirable. You can make the tic-toc stop any time you want by
connecting pin-5 of the 555 Timer to ground (Vss).

Basic Analog and Digital Student Guide Version 1.0 Page 105
Experiment #6: Recording Frequency Data

Program It
How to predict the 555 Timer's frequency?

f = 1.45/[C*(RA + 2RB)

Another fact acquired from a data sheet, this one on the 555 family of In the previous experiment, the Stamp-O-
timers. TH, the pulse width, is given by: Scope digitally sampled and displayed signal
data. Program Listing 6.1 is a greatly
0.69 C (RA +RB),
simplified version of the Stamp-O-Scope
where C, RA and RB are the values of the capacitor and two resistance (the Stamp-O-Scope 2), and it only displays
values of pot A and pot B as shown in Figure 6.3. TL, the duration of the variation in logic level (0 or 1). Since the 555
low signal (the time between pulses) is given by: timer's output is a pulse train that varies
between 0 and 5 Volts, A/D conversion is not
0.69 C RB.
required. The Stamp-O-Scope 2 is all that's
needed.

'Program Listing 6.1


'Stamp-O-Scope 2

'START DISPLAY
debug cls

DISPLAY:

debug rep " "\in0*20, "*", cr


pause 100

goto DISPLAY

About the Code

The command debug rep " "\in0*20, "*", cr uses the input value measured at pin P0 to dictate how
many spaces are printed. No variables are used. When the input is zero, the asterisk gets printed without any
spaces before it, indicating a 0 at the input. When the value at P0 is 1, twenty spaces are printed before the
asterisk, indicating a measured input value of 1.

Page 106 Basic Analog and Digital Student Guide Version 1.0
Experiment #6: Recording Frequency Data

The Output

Figure 6.4 shows the Stamp-O-Scope 2 display. You can adjust the potentiometers and change the frequency
characteristics of the waveform. For example, pot B directly effects the amount of time the signal is low. It
also indirectly affects the amount of time the signal is high. Try adjusting pot B until the low signal is 5
asterisks wide. Then, you can adjust pot A so that the pulse-width varies. Try adjusting A so that the pulse-
width is also 5-asterisks wide. Newer versions of the debug window include a pause and resume button that
you can click to freeze and unfreeze the display.

Figure 6.4: Output Sample


This is a time-varying display
of the pulse train generated
by the 555 timer as
measured by pin P0. Again,
the display has been turned
sideways to match
conventional displays and
graphs.

Now, try adjusting pot B and make the low signal two asterisks wide. What happened to the pulse width? It
should also have gotten narrower too.

Next, try adjusting pot B as far as it will go to increase the frequency (making the pulse widths narrower). The
piezoelectric speaker should be clicking pretty fast now, and the Stamp-O-Scope 2 is probably not working
very well any more, as shown in Figure 6.5. We'll replace it with another program that lends itself to
measuring audible sound.

Figure 6.5: Output Sample


The pulse train is now
repeating itself several
times as fast as the
sampling rate. So the
Stamp-O-Scope 2 display is
no longer valid.

Basic Analog and Digital Student Guide Version 1.0 Page 107
Experiment #6: Recording Frequency Data

Carefully adjust pot A and you should be able to hear an audible tone out of the piezo speaker. It's not a pretty
tone; it sounds about like a kazoo.

Now back way off on pot B so that all you get is a periodic clicking out of
the piezoelectric speaker. We'll want to crank pot B back up in a little
while to get that tone again, but first, let's consider what happened to
When is aliasing a concern? the Stamp-O-Scope 2 display as the frequency of the 555 Timer was
A recommended sampling rate increased.
depends on the characteristics of
the signal being measured. Some
signals are sampled just a few times The display shown in Figure 6.5 still showed signal activity, even though it
per cycle while others are sampled was erroneous. This is called aliasing. Aliasing happens when you don't
thousands of times per cycle. sample something fast enough to get a true representation of what's
The absolute minimum sampling rate,
going on. Aliasing can cause problems because sometimes the signal that
in theory, that can be used to gather gets displayed actually looks valid.
valid signal data is twice the
frequency being sampled. When the For the most part, the debug window is the limiting factor for sampling
sampling rate is less than twice the rate. So let's make a program that allows the BASIC Stamp take turns
frequency of the signal being
sampled, aliasing is guaranteed. This between working at full speed and sending messages to the debug
minimum frequency is called the window.
Nyquist rate.

A BASIC Stamp I/O pin can be monitored to check the number of threshold voltage crossings per time interval.
The BASIC Stamp can be programmed to track these changes once every two microseconds. The period of the
sample is 2 microseconds.

From Experiment #5, we know that frequency is given by the inverse of the period:

f=1T

So, the sampling rate is:

1 2 10-6 seconds = 250 103 = 500 kHz

Since the sampling rate is 500 kHz, the theoretical maximum frequency we could sample is 250 kHz. The
audible sound range is between 20 Hz and 20 kHz, and the sounds we will work with in this experiment will
vary between 50 Hz and 3.5 kHz. Clearly, aliasing is not a concern.

Page 108 Basic Analog and Digital Student Guide Version 1.0
Experiment #6: Recording Frequency Data

Let's make a program that counts how many times the pulse train
repeats its self. In effect, we will make a program that determines the
Program It frequency of the pulse train. The BASIC Stamp has a built in feature
for counting frequency, and the PBASIC command is the count
command.

The BASIC Stamp increments the counter when the input voltage passes the 1.4 Volt I/O pin threshold twice.
This makes programming and interpreting the frequency data easy for periodic signals such as the pulse train,
triangle wave and sine wave. Figure 1.6 shows why there are two threshold crossings per repetition of the
waveform. When a waveform repeats itself, it's called a cycle.

1 full cycle
Figure 6.6: Full Cycle of 5 Volts
a Pulse Train with a 5
Volt amplitude and a 0
Volt DC offset. Notice
how the waveform 1.4 Volts
crosses the threshold 0 Volts
voltage twice per cycle.

Two crossings of the


threshold voltage

Enter Program Listing 6.2 into the Stamp Editor and save it as P6_2R0.bs2.

'Program Listing 6.2, Revision 0

f var word

main:
count 0,1000,f
debug home, "Frequency: ", dec4 f, " Hz.", cr, cr
goto main

When you run the program, and adjust pot B to its maximum, the output should be somewhere in the
neighborhood of the frequency shown in Figure 6.7.

Basic Analog and Digital Student Guide Version 1.0 Page 109
Experiment #6: Recording Frequency Data

Frequency: 0280 Hz.


Figure 6.7: Debug Output for
Program Listing 6.2.

Remember that you can turn the sound (noise, racket, whatever you want to call it by now) off by shorting pin
5 on the 555 timer to Vss. When you want the sound back on, just disconnect the wire from the Vss terminal
again.

Modify the test circuit by replacing pot A with two 2 k resistors in series, and replace the 10 uF capacitor
with the 0.1 micro Farad capacitor from your parts kit. Figure 6.8 shows how the circuit should look when the
changes to the circuit have been made.
Vdd

2k 2k
8 P0

7
4

100k 555 Timer


POT B 6
3
100
nc 2 +
+

0.1uF 1uF
-
Figure 6.8: Astable Piezo
1
Multivibrator Circuit -
with fixed RA=4 k. RB
is can still be adjusted
with pot B.

Vss

Page 110 Basic Analog and Digital Student Guide Version 1.0
Experiment #6: Recording Frequency Data

Adjusting pot B, you should now be able to measure sound on a frequency range from about 60 Hz to about
3.5 kHz. You can log frequency data as you adjust the pot with the revised version of Program Listing 6.2
below.

'Program Listing 6.2 Revision 1.

f var word(10)
n var nib

main:
debug cls

for n = 0 to 9
count 0,1000,f(n)
debug home, "Frequency ", dec4 f(n), " Hz.", cr, cr
next

pause 1000

for n = 0 to 9
debug "Frequency at ", dec1 n, " seconds was ", dec4 f(n), " Hz.", cr
next

pause 5000

goto main

The debug window data shown in Figure 6.9 was generated by adjusting the pot back and forth to some
random frequencies (tones).

Frequency at 0 seconds was 0067 Hz.


Frequency at 1 seconds was 0067 Hz.
Frequency at 2 seconds was 0131 Hz.
Frequency at 3 seconds was 1742 Hz.
Figure 6.9: Debug Output Frequency at 4 seconds was 1095 Hz.
for Program Listing 6.2, Frequency at 5 seconds was 0440 Hz.
Revision 1. Frequency at 6 seconds was 3168 Hz.
Frequency at 7 seconds was 2014 Hz.
Frequency at 8 seconds was 0850 Hz.
Frequency at 9 seconds was 3541 Hz.

Basic Analog and Digital Student Guide Version 1.0 Page 111
Experiment #6: Recording Frequency Data

About the Code

Program Listing 6.2 Revision 2 introduces the concept of data storage using an array. We used the command:

f var word(10)

to reserve 10 words of space in the BASIC Stamp's RAM. There's a word labeled f(0), another word labeled f(1),
and so on through f(9). Each of these words are stored adjacent to each other in the BASIC Stamp's RAM.

As the value of n is incremented in the for-next loop, so is the index of the array. The first time through the
array, a value is loaded into word f(0), the second time through the array, a value is loaded into word f(1), and
so on through word f(9).

for n = 0 to 9
count 0,1000,f(n)
debug home, "Frequency ", dec4 f(n), " Hz.", cr, cr
next

The same concept worked for printing the values back to the debug window.

for n = 0 to 9
debug "Frequency at ", dec1 n, " seconds was ", dec4 f(n), " Hz.", cr
next

The time varying waveforms we've looked at in this experiment and in Experiment #5 have been periodic. That
is, they've repeated themselves. In the next two experiments, we'll take a look at waveforms that vary with
time, but they aren't necessarily periodic.

Page 112 Basic Analog and Digital Student Guide Version 1.0
Experiment #6: Recording Frequency Data

What have I
On the lines below, insert the appropriate words from the list on
learned? the left.

Sounds can be characterized by _____________ waveforms. The frequency range for


audible sound is between 20 and 20,000 Hz. When a time varying waveform such as a
sampling rate pulse train of sufficient frequency and amplitude is sent to a speaker, the speaker emits
audible sound.
pulse train
The 555 timer in an astable multivibrator circuit can be adjusted to generate a
time-varying _____________ . The frequency, pulse width, and _____________ can be adjusted by
changing the values of the passive elements in the circuit, i.e. the capacitor, and the two
amount resistors.

array variable The pulse width is the _____________ of time a signal remains high, and the duty cycle
is the ratio of the pulse width to the _____________ of the waveform.
incremented
Aliasing is a phenomenon that occurs when the _____________ is less than twice the
period frequency of the signal being sampled. This can cause significant misinterpretations of
the signal data.
duty cycle
Data can be conveniently stored and accessed in RAM using an _____________ . The
index of an array variable can be _____________ using a for-next loop. When you
specify an array of 10 bytes, they are indexed as bytes 0 through 9.

Basic Analog and Digital Student Guide Version 1.0 Page 113
Experiment #6: Recording Frequency Data

Questions

1. Given four different frequencies of sound, 3.5 Hz, 350 Hz, 3,500 Hz, 35,000 Hz, which ones can you hear
and which ones can't you hear? Explain your answers. Also, compare the pitch of the sounds you can hear.

2. Explain aliasing. If a signal is sampled at 1 kHz, how low can the signal's frequency get before aliasing is
guaranteed?

3. For the circuit in Figure 6.7, what resistance value does the pot have to be to make the astable
multivibrator circuit generate a 2 kHz signal? This requires some algebra.

4. Construct a PBASIC command to declare an array of 5 nibbles. Make a command that sets the fist nibble
in the array equal to the fifth nibble in the array.

Challenge!

1. In Program Listing 6.2 Revision 2, the frequency samples we took were once every 1-second because the
count command counted for a second. Revise the program listing to count the frequency samples for of
a second. Make sure your output data is correct by comparing output of the revised program to output of
the original for a known frequency. Fix any bugs

2. Design a program to record and play back tones. Make it so that the recorded tone is played on one
speaker, and the playback tone is sent to a second speaker. Add a function to the program that shuts the
555 timer off by sending a low signal to pin-5 on the timer when you want to hear the playback signal.
Hint: You can combine two of one of the program listings from Experiment #5 with a program listing
from this experiment, and you'll be almost done. All you'll have to do is program the control signal that
disables the 555 timer.

Page 114 Basic Analog and Digital Student Guide Version 1.0
Experiment #6: Recording Frequency Data

3. Design and build the circuit to implement the design from Challenge 2. You'll need to be creative about
finding enough space on the breadboard.

4. Add two pushbuttons to the system developed in Challenge 2 and 3 so that you can control when to
record and play back single sound samples. Now you'll need to be really creative about finding enough
space on the breadboard. Use 10 kW resistors with the pushbuttons, and design them to send either high
or low signals. Hint: Review Experiment #1 for circuit and program techniques for implementing the
pushbuttons.

Digital processing of audio signals is still expanding in the audio


industry. New, more efficient ways of storing and transmitting sound
Why did I are being developed so that you can transmit music more quickly over
learn it? the internet and so that your voice sounds more like your voice to the
person on the other end of the phone line.

Digital signal processing is also the crux of the telecommunications industry with cellular phones and normal
telephones. When you talk on the phone, your voice signal is converted to 0s and 1s and sent via the
telephone network in binary format. Your telephone still sends and receives analog voice signals, but your
voice information is A/D and D/A converted at various points in the telephone network.

Frequency is an effective way to think about sound, but there is a


myriad of other uses for frequency counting. For example, engine
How can I speed and car speed are determined by how fast certain moving parts
apply this? on the car turn. When something rotates, each time it turns full circle
it has repeated itself. If a shaft is rotating at 100 turns per second, its
frequency of rotation is 100 Hz. Machine vibration can also be
measured in terms of frequency, and so can many metabolic signals such as breathing, heart rate, and so on.

Basic Analog and Digital Student Guide Version 1.0 Page 115
Experiment #6: Recording Frequency Data

Page 116 Basic Analog and Digital Student Guide Version 1.0
Experiment #7: Digital to Analog the Easy Way Using PWM

Experiment #7: A resistor, capacitor, BASIC Stamp, and a single line of


PBASIC code. That's all it takes to build a D/A converter with
Digital to Analog the 8-bit resolution. Sound too good to be true? In a sense it is
Easy Way Using PWM because a buffer is almost necessary for this circuit to
maintain a given voltage. Even so, it's easy to build and
offers a higher degree of accuracy than its resistive ladder
counterpart. Figure 7.1 shows the circuit that's used - it's a simple RC circuit. The input receives a pulse width
modulated (PWM) signal, and the output rises or falls to the desired voltage level.

PWM D/A
Input Output

P8
10k
Figure 7.1: RC
Circuit which can be
connected to the +
BASIC Stamp for D/A 1uF
conversion. -

Vss

How can sending pulses of varied width and frequency control or set a voltage level at the D/A output? The
answer is the RC circuit shown in Figure 7.1. This circuit behaves like a rechargeable battery. Figure 7.2 shows
an example of the simplest kind of capacitor, the parallel plate capacitor. The charges migrate from the
battery terminals and accumulate on the two metal plates until the voltage across the capacitor is the
essentially the same as the battery voltage.

Basic Analog and Digital Student Guide Version 1.0 Page 117
Experiment #7: Digital to Analog the Easy Way Using PWM

//////////////////
Figure 7.2: Parallel Plate ///
Capacitor Charged by a
////////////////////
Battery The opposed charges
congregate at the their
+ ///
respective plates. They want
to get across the gap
between the two metal 000000000000
plates, but there is an
insulating material called a 000000000
dielectric in-between the
plates, so they can't get
across. -
0000000000
00000000

You could also disconnect the battery from the capacitor, and it would maintain its voltage. Typically, there is
a small amount of current that does make it through the dielectric material that separates the plates. It's
called leakage current. Leakage current on a charged capacitor will cause the voltage to slowly dissipate.

The RC circuit shown can charge to within 1% of 5 Volts very quickly. Assume that a single pulse is applied to
the circuit in Figure 7.1 instead of the many pulses sent via a PWM signal. If the values of the components are
exact, it would take about 6.93 milliseconds for the capacitor to charge up to 2.5 Volts, and would take 46.1
milliseconds for the output to get all the way to 4.95 Volts, which is 99% of the full 5 Volts.

For advanced math enthusiasts, let's take a look at the proof. The modeling equation for the RC circuit from
Figure 7.1 responding to a pulse that goes from 0 to 5 Volts is:

t

VOutput = VInput 1 e RC

The modeling equation is rearranged to isolate the exponential term:

t
VOutput
1 = e C
R
VInput

Page 118 Basic Analog and Digital Student Guide Version 1.0
Experiment #7: Digital to Analog the Easy Way Using PWM

The natural log of both sides is taken to remove the exponential term, and the terms are rearranged:

VOutput t V V
ln1 = ln e RC t = ln1 Output t = R C ln1 Output
VInput RC VInput VInput

All that's left is to plug in the numbers to solve for t2.5 Volts and t4.95 Volts. R and C are the resistance and
capacitance values shown in Figure 7.1, and VInput = 5 Volts. The first VOutput is 2.5 Volts.

VOutput
t 2.5 Volts = R C ln1 = (10 10 3 ) (1 10 6 ) ln1 2.5 = 6.93 10 3 sec onds
VInput 5.0

Then, the same calculation can be done for t4.95 Volts.

VOutput
t 4.95 Volts = R C ln1 = (10 10 3 ) (1 10 6 ) ln1 4.95 = 46.1 10 3 sec onds
VInput 5. 0

An oscilloscope could be used to monitor the output voltage of the RC circuit from Figure 7.1. The response
when a single, very wide pulse (a voltage step) is applied would resemble that shown in Figure 7.3. As you can
see, it takes just a fraction of a second for the capacitor to charge up to 5 Volts. Nonetheless, it is a gradual
change when compared to pulses sent by the BASIC Stamp, which can be as narrow as 2 microseconds.

Basic Analog and Digital Student Guide Version 1.0 Page 119
Experiment #7: Digital to Analog the Easy Way Using PWM

RC Circuit Response to Step


Input vs. Time
Output 5
Voltage
(Volts) 4

3
Figure 7.3: RC circuit
Step Response shows 2
the voltage response to a
single voltage step 1
applied at the input.
0
5
Input
Voltage 4
(Volts)
3

0
-0.02 -0.01 0 0.01 0.02 0.03 0.04 0.05

Time, (Seconds)

Applying many narrow pulses as opposed to the single very wide pulse applied in Figure 7.3 has advantages in
terms of accuracy. As you will soon find out, this D/A conversion technique is surprisingly accurate. Especially
since the resistor has a 10% tolerance and the capacitor is only accurate to 20%!

Page 120 Basic Analog and Digital Student Guide Version 1.0
Experiment #7: Digital to Analog the Easy Way Using PWM

Parts
Required
This experiment requires the following parts:

(1) ADC0831 A/D converter


(1) LM358 op-amp
(2) 10 k-Ohm resistor
(1) 1.0 uF electrolytic capacitor
(1) Photoresistor
(1) 470 ohm resistor
(1) Yellow LED

The photoresisitor senses light level. Under a bright light, the resistance can drop to as low as a few Ohms. In
darkness, the resistance can climb as high as 50 K ohms. Figure 7.4 shows the circuit symbol for a
photoresistor and a drawing of the component.

Figure 7.4:
Photoresistor
Circuit Symbol and
Component

Build the circuit shown in Figure 7.5. Recall from Experiment #4 that
the inputs of the ADC0831 have very high resistance, and they
Build It resemble an open circuit. Because of this, it's okay to connect the
output of the D/A converter to the ADC0831's Vin(+) input without the
buffer.

Basic Analog and Digital Student Guide Version 1.0 Page 121
Experiment #7: Digital to Analog the Easy Way Using PWM

Vdd

8 5
Vdd Vref
2
P8 Vin(+) ADC0831
10k 1
/CS P0
Figure 7.5: RC Circuit for
PWM D/A Donversion 4
connected to the Vin(+) Gnd
7
+

terminal of the ADC0831. 1uF CLK P1


The ADC0831 is connected -
3 6
to the output of the D/A Vin(-) DO P2
converter to measure the
output voltages.

Vss Vss

We are going to use the pwm command to send pulses to the RC circuit for D/A conversion. Then we'll measure
the voltage using the ADC0831 as a DVM.

The format of the pwm command is:

pwm pin, duty, cycles

The term pin refers to a BASIC Stamp I/O pin, and you can specify a pin number between 0 and 15 to select a
pin. Since the converter input is connected to BASIC Stamp pin P8 in the schematic, we need to set the pin
value to 8.

Now, what about duty? Remember from the Experiment #5 that duty cycle is the ratio of the pulse width to
signal period. The term duty is different in the sense that it isn't the duty of a cycle. It's the duty of all the
pulses over a certain period of time. In other words, the term duty specifies the ratio of high signal to the
time duration of all the pulses in a specific interval of time.

When the duty is 255, that means that all the pulses are high, and there is no low signal between them. When
all the pulses are high, it means that the capacitor will charge all the way to 5 Volts, the high value of the
pulses. In theory, the capacitor can never actually charge to 5 Volts, but in practice, a time of 5RC brings
the voltage to within 99.3% of 5 Volts.

Page 122 Basic Analog and Digital Student Guide Version 1.0
Experiment #7: Digital to Analog the Easy Way Using PWM

Therefore, duty is what controls the voltage level, but how do we figure out what we want the duty to be? It's
actually pretty simple because it works on a scale from 0 to 255, where 0 is 0 Volts and 255 is 5 Volts. This
looks like a method we already covered in Experiment #3.

Assume we want 3.25 Volts. In Experiment #3, we learned how to normalize a scale of 0 to 5 Volts to a scale of
0 to 255. Remember that the measured voltage was to 5 as the A/D output was to 255. This translated to
fractions as:

Voltage Decimal A / D input


=
5 255

In this case, the D/A output voltage is to 5 as the duty is to 255, which translates to fractions as:

D/A Output duty


=
5 255

Usually, we know what voltage we want, so we can rearrange the equation to tell us what duty we need:

duty = 255 (D/A Output 5)

Since we want our D/A output to be 3.25 Volts:

duty = 255 (3.25 5) = 165.75

The number 165.75 should be rounded to 166 so that we can set the duty to an integer value.

The last quantity we need to determine for the pwm command is cycles, which specifies how many
milliseconds the PWM output lasts, and it can be a number up to 65,535. The "rule of thumb" for choosing how
many cycles to charge is:

cycles = 4 R C, in milliseconds

Since we used a 1.0 uF capacitor and a 10 k resistor,

cycles (In mili-seconds) = 4 0.000001 10,000 = 0.04 = 40 10-3 = 40 mili-seconds

For the components we are using, we need to set the cycles value in the pwm command to 40.

Basic Analog and Digital Student Guide Version 1.0 Page 123
Experiment #7: Digital to Analog the Easy Way Using PWM

Now we know that to generate a 3.25 Volt output, our pwm command needs to be:

pwm 8, 166, 40

Let's try it.

Program It

Modify the DAC: subroutine from Program Listing 4.1 as follows:


DAC:
n = 166
pwm 8,n,40
return

Also modify the DISPLAY: subroutine so that it only displays the voltage, as shown below.

DISPLAY:
debug CR, CR, "DVM Reading: ", dec1 v, ".", dec2 v2, " Volts"
return

Also modify the first line of the program for future reference, and save the modified program as P7_1R0.bs2.
Then, run the program and check the output.

The Output

Take a look at Figure 7.6; not bad!

DVM Reading: 3.25-Volts


Figure 7.6: Debug Output for
Program Listing 7.1.

Page 124 Basic Analog and Digital Student Guide Version 1.0
Experiment #7: Digital to Analog the Easy Way Using PWM

Try setting n to a few different values.

Important: This circuit must be isolated from


High input impedance other circuits. The input impedance of the V(+)
BASIC Stamp I/O pins set to input mode, op-amp input terminals,
and the ADC0831's Vin terminals all have an important aspect in
pin on the ADC0831 is very high, high enough to
common that makes them invisible to other circuits. It's high input make it invisible to the RC circuit. But if you
impedance. tried to use this circuit to drive an LED-resistor
circuit without the buffer, all the charge that
The term impedance includes both resistance and capacitance. built up in the capacitor would exit through the
High input impedance means that the resistance is huge, and there
is a very small capacitance as well. LED and resistor.

The impedance at the input terminals of these devices is so high Try connecting a 10k Ohm resistor from the D/A
that it fools the most circuits into behaving as if the inputs to these converter output to Vss. Figure 7.7 shows what
devices are open circuits. So, for the most part, you can connect
the output of just about any circuit to these inputs.
happens when you try to send 3.25 Volts with a
load on the D/A converter.
On the other hand, we've seen how comparatively low resistance
circuits such as a 10k resistor or an LED circuit can drastically Since the D/A pwm repeats itself without a
change the output of D/A circuits. pause in the program, the capacitor does not
discharge all the way to 0 Volts.
One advantage of many D/A converter integrated circuits is that
they provide reliable, buffered output.
If the program were set to carry out the pwm
command only once, the capacitor would
discharge very quickly.

Figure 7.7: Debug Output for DVM Reading: 1.25-Volts


Program Listing 7.1 with an
Unbuffered 10 k load.

As you can see, a buffer is essential to keep the voltage steady. You can use the same voltage follower that we
used in Experiments #2, #4 and #5 to buffer the output.

Place a voltage follower in between the D/A output and the LED circuit input as shown in Figure 7.8, then run
Program Listing 7.1 again.

Basic Analog and Digital Student Guide Version 1.0 Page 125
Experiment #7: Digital to Analog the Easy Way Using PWM

Vdd

Vdd

8 5
8 Vdd Vref
2
- 2
A Vin(+) ADC0831
1
P8 + 1
LM358
3 4 /CS P0
10k
4
Figure 7.8: PWM Gnd
DAC with Op-amp 7
Vss CLK P1
+

Buffer and a Load 1uF 3


470 6
Consisting of an - Vin(-) DO P2
LED in Series with a
Resistor.

Vss Vss Vss

Figure 7.9 indicates that the buffer is doing its job.

Figure 7.9: Debug Output for DVM Reading: 3.25-Volts


Program Listing 7.1 ith a
Buffered LED Circuit for a
Load.

Next, add a photoresistor in series with a 10 k Ohm resistor as shown in Figure 7.10. The positive lead of your
Stamp DVM should be connected to the node where the photoresistor connects to the 10 kW resistor. This is
a voltage divider output, and as the resistance of the photoresistor varies, so will the voltage seen at the
output of the voltage divider. Also, point the top of the yellow LED directly at the face of the photoresistor as
shown.

Page 126 Basic Analog and Digital Student Guide Version 1.0
Experiment #7: Digital to Analog the Easy Way Using PWM

Figure 7.10: Transmitting an Optical Signal.


PWM sets the RC circuit's output voltage, which
in turn drives an LED circuit via a voltage
follower.

Vdd The light from the LED is transmitted to the


photoresistor. Face the 2 devices at each other
as shown. The voltmeter from Experiment #3
2 8 senses the changes in voltage divider output.
-
A
1
P8 +
3 4 LM358
10k Vdd
LED

Vss Vdd
+

1uF
- 470

8 5
Vss Vdd Vref
Vss
2
Vin(+) ADC0831
1
/CS P0
10k 4
Gnd
7
CLK P1
3 6
Vin(-) DO P2
Vss

Vss

Let's try adjusting the brightness of the LED and see what happens to output at the voltage divider. Make the
changes to the main:, DISPLAY:, and DAC: subroutines shown below. Then save the program as P7_1R1.bs2,
and run it.

main:

for n = 82 to 192
n = n + 9
pause 4000
gosub subroutines

next

Basic Analog and Digital Student Guide Version 1.0 Page 127
Experiment #7: Digital to Analog the Easy Way Using PWM

subroutines:
gosub DAC
gosub ADCDATA
gosub CALC_VOLTS
gosub DISPLAY
return

goto main

DAC:
pwm 8,n,40
return

DISPLAY:
debug home
debug "Value to DAC: ", dec3 n
debug cr, cr, "DVM Reading: ", dec1 v, ".", dec2 v2, "-Volts", cr, cr
return

As you can see, the output of the voltage divider varies as the LED gets brighter and dimmer. To get the
highest swings in measured voltage, turn the lights off in the room. The circuit should work fine under normal
lighting conditions. If your circuit is in direct sunlight, the differences in output voltage may be too small to
measure.

The voltage divider equation can be used to determine the resistance of the photoresistor. From Experiment
#3, the voltage divider equation is:

R2
VOutput = VInput
R1 + R 2

R2 is a known resistor value, and R1 is the unknown resistance value of the photoresistor. Vinput is 5 Volts, and
Voutput should be noted from the debug window. It takes some algebra to rearrange the terms; the final result
is:

VInput
R1 = R 2 R2
VOutput

This is one method of using a variable resistor as a sensor. Clearly it can detect different levels of light, and
the ADC0831 handles converting the analog information into digital information. In the next experiment, we'll
introduce another method for measuring variable resistance that uses significantly less hardware and code.

Page 128 Basic Analog and Digital Student Guide Version 1.0
Experiment #7: Digital to Analog the Easy Way Using PWM

What have I
On the lines below, insert the appropriate words from the list on the
learned? left.

entire The BASIC Stamp has a built in feature for D/A conversion that uses pulse width
modulation. The technique uses a series of pulses to charge the capacitor in an
analog __________ circuit to the desired voltage. PWM relies on the duty, which is different
from duty cycle, to control the voltage the capacitor is charged to. Duty refers to a
RC series of pulses instead of a single cycle. It's the total amount of time the signal is
__________ divided by the total amount of time for the __________ pulse train.
buffer
A __________ is essential for this circuit when driving a load. Without it, the
voltage divider __________ will quickly loose its charge. A capacitor also looses its charge due to
leakage current, so the PWM should be repeated periodically to refresh the voltage.
high
A photoresistor is a device whose resistance value changes with the brightness of light
capacitor that shines on a collecting surface. The photoresistor or any resistor whose value
changes with some analog value can be used in a __________ and the result is a variable
voltage output. This information can be interpreted using the ADC0831 and the BASIC
Stamp to measure the __________ voltage output.

Basic Analog and Digital Student Guide Version 1.0 Page 129
Experiment #7: Digital to Analog the Easy Way Using PWM

Questions

1. Can changing the capacitor or resistor values improve the resolution of the PWM D/A converter? Explain
your answer.

2. Given the command: pwm 14,51,50, approximately how many milliseconds does the command take to
execute? How many milliseconds is the pulse train high?

3. Why does the capacitor loose its charge if you attach a resistive element to the output of the PWM D/A
converter?

4. If you want a 2.5 Volt output, what do you have to set the duty to? Assume you are using the pwm
command in Program Listing 7.1. Explain your reasoning.

5. If you want to do DAC using a 10uF capacitor and a 47 k-Ohm resistor, what should your cycles be?

6. If the measured voltage in a voltage divider with a photoresistor as shown in Figure 7.10 is 2.3 Volts, what
is the value of the photoresistor?

Challenge!

1. Write a program that controls the voltage on 2 separate D/A converters that maintain different voltage
values.

2. Design and build the circuit for the program in Challenge 1. You will need to make use of the second op-
amp in the LM358. Refer to Figure 1.5 for the schematic.

3. Program your dual output DAC to make the LED load on channel 1 get gradually brighter as the LED on
channel 2 gets gradually dimmer.

Page 130 Basic Analog and Digital Student Guide Version 1.0
Experiment #7: Digital to Analog the Easy Way Using PWM

4. Write a program that tells you the measured resistance value of the photoresistor from Figure 7.8. Hint:
Apply the voltage divider equation and use the existing DVM program. You will need to modify the
CALCULATIONS: and DISPLAY: subroutines.

Using a simple RC circuit with a buffer is an inexpensive and easy way to


get 8-bit DAC. It's also really easy to program, and the accuracy is much
Why did I closer to that of a D/A converter integrated circuit than it is to the
learn it? accuracy of the resistive ladder network with 10% resistors.

There are many instances in which analog quantities will change the
resistance of a device. The voltage divider can be an effective way to track these changes in resistance. The
measured voltage at the output of a voltage divider can give us information, not only about the resistance
value, but about the analog quantity that causes the resistance value to change.

The optics industry has many applications where the levels of light are
controlled and sensed. In the communications industry, fiber optic cables
How can I are used to send your phone conversation across long distances. In the
apply this? robotics industry, sensing light is an important aspect of controlling the
movement of the mechanical parts of the robot.

The application you're probably most familiar with is the remote control on your television set. When you
point the remote control at your television and press a button to change the channel, that information is sent
using light, which is received by a sensor on the front of your TV.

Many industrial processes need to use feedback to sense the level of light and adjust it to keep it in a
particular range. In photography, many cameras depend on analog measurements taken by a light meter.
These measurements can in turn be used to control the aperture of the shutter when taking a photograph.
The aperture is how far the shutter opens to let light into the camera. In the next experiment, we'll build a
light meter.

Basic Analog and Digital Student Guide Version 1.0 Page 131
Experiment #7: Digital to Analog the Easy Way Using PWM

Page 132 Basic Analog and Digital Student Guide Version 1.0
Experiment #8: Light Meter Gizmo

Experiment #8: In this experiment, we'll be using concepts we learned in


Light Meter Gizmo previous experiments to develop a light meter gizmo. Here
is the list of gizmo specifications:

The gizmo should beep every half-second.


When the light level in the room gets brighter, the gizmo should beep at a higher pitch.
When the light level in the room gets dimmer, the gizmo should beep at a lower pitch.

This experiment introduces a way of using a BASIC Stamp I/O pin to measure variable resistance or
capacitance. A number of sensors aside from the photoresistor vary in either resistance or capacitance. So, a
simple and straightforward way of measuring these quantities can make interfacing with these sensors
immensely easier.

In this experiment, we'll begin by building our gizmo, next we'll look more closely at the measurement
technique to see how it can be used to monitor variable resistance or capacitance. Figure 8.1 shows a
generic CR circuit that can be used to take RC time constant measurements.

Vdd

+
C
-

Figure 8.1: CR
Circuit for P15
measuring values of 220
C or R.
R

Vss

Basic Analog and Digital Student Guide Version 1.0 Page 133
Experiment #8: Light Meter Gizmo

In Experiment #7, the amount of time it takes a capacitor to charge in an RC circuit with a step input was
introduced. The same principle applies here. A step will be applied to the circuit, and the amount of time it
takes the capacitor to charge will be measured. Here's how it works.

The BASIC Stamp must be programmed to set P15 (the I/O pin we'll be using) high for a few milliseconds to let
the voltage across the capacitor approach 0 Volts. The reason the voltage across the capacitor approaches 0
Volts is because Vdd is 5 Volts at the positive terminal of the capacitor, and P15 is set to 5 Volts at negative
terminal. So, the voltage across the capacitor is 5-5 Volts = 0 Volts.

As soon as the voltage across the capacitor is close enough to 0 Volts, P15 is set to function as an input.
Immediately, the BASIC Stamp starts counting in 2 microsecond increments. As soon as P15 becomes an input,
it doesn't have an output voltage of 5 Volts any more. P15 behaves like an open circuit as far as the CR circuit
is concerned.

All of the sudden, the circuit is different. It's a resistor and a capacitor in series. The capacitor starts with no
charge, but the circuit has 5 Volts across it (Vdd Vss), so the capacitor starts to charge up. As the capacitor
starts charging, the voltage at P15 starts falling. The voltage at P15 will fall until it crosses the BASIC Stamp's
I/O pin threshold voltage. It takes a certain amount of time for the voltage at P15 to decay from 5 Volts, to the
1.4 Volt threshold voltage of P15.

The BASIC Stamp can be used to measure the amount of time it takes, and this measurement can be used to
determine an unknown capacitance or resistance.

The equation for the voltage at P15 is given by:

t
VP15 = Vdd e C
R

This equation is widely used in many fields, and it's called the exponential decay equation. In our case, it's an
equation of exponentially decaying voltage. Figure 8.2 shows the decays of three CR circuits that differ only in
resistance. Each of the voltage outputs takes a different amount of time to decay from 5 Volts to 1.4 Volts.

Page 134 Basic Analog and Digital Student Guide Version 1.0
Experiment #8: Light Meter Gizmo

CR Circuit Response to
Negative Step Input vs. Time

Figure 8.2: CR circuit Output 5


Voltage V1 for R1 = 5k
Responds to a negative step
(Volts) 4
input for three different V2 for R2 = 10k
resistance values. Note how
3 V3 for R3 = 15 k
each output takes a different
amount of time to decay from 5 Vt (threshold) = 1.4 V
2 V1 V2 V3 Vt
Volts to 1.4 Volts.
1
The difference in time it takes
the three different circuit 0
outputs to decay can be used to -0.02 -0.01 0 0.01 0.02 0.03 0.04 0.05
5
determine a resistance value if Input
the capacitance value stays the Voltage 4
same. Likewise, if the (Volts)
resistance is fixed but the 3
capacitance varies, the Intersection with Vt
capacitance can be determined 2 occurs at 3 different
by measuring the time between times.
the step input and the threshold 1
voltage.
0
-0.02 -0.01 0 0.01 0.02 0.03 0.04 0.05

Time, (Seconds)

A PBASIC command called rctime can be used to make the BASIC Stamp determine the amount of time it
took the CR output to decay from 5 Volts to 1.4 Volts, which is the value of t in the exponential decay
equation. The value of t that gets measured is t1.4 Volts. The value of t1.4 Volts is the amount of time it takes for
the voltage at I/O pin P15 to fall from 5 Volts to 1.4 Volts.

It turns out that the amount of time it takes for the voltage to decay is directly proportional to R multiplied by
C. R C is called the RC time constant, and it is often represented by the Greek letter tau.

At the instant the voltage at P15 reaches 1.4 Volts, the input value at pin P15 goes from 1 to 0, and the BASIC
Stamp stops counting 2 us intervals.

Basic Analog and Digital Student Guide Version 1.0 Page 135
Experiment #8: Light Meter Gizmo

Parts
This experiment requires the following parts:
Required

(1) 0.1 uF poly capacitor


(2) 1 uF electrolytic capacitors
(1) 10 uF electrolytic capacitor
(1) Piezoelectric speaker
(1) 220 ohm resistor
(1) Photoresistor
(1) 100 ohm resistor

Build the circuit shown in Figure 8.3. Note that the resistor in the circuit
Build It on the left uses the variable photoresistor. The circuit on the right is the
circuit we used to play music in Experiment #5.
Vdd
P7

100
+

1uF
-
Figure 8.3: Ambient
Light Meter Circuit.
P15
220 + +

1uF
Piezo -

Vss Vss

Page 136 Basic Analog and Digital Student Guide Version 1.0
Experiment #8: Light Meter Gizmo

You will have to calibrate both your circuit and program due to varying light conditions. Do not point the
photoresistor directly at the sun. We'll use the slot in the center of the breadboard as our light collector.
Point the photoresistor at the slot as shown in Figure 8.4

Figure 8.4: Placement of the


Photoresistor.
Face the photoresistor into the slot in
the middle of the breadboard. This
way the photoresistor will detect the
light reflected off the white
breadboard. This will make the
photoresistor less subject to wide
resistance swings that can happen
when the photoresistor is faced
directly at bright light sources.

The PBASIC instruction set has a command called rctime, which measures the amount of time it takes a
capacitor to discharge under the conditions just described. The format of the rctime command is:

rctime pin, state, result

As usual, pin refers to a BASIC Stamp I/O pin. Referring to Figure 8.1, we are using pin P15. Now, what about
state? The operator state is set to 1 when we are using the CR circuit shown in Figure 8.1. If we used an RC
circuit instead, the state would be set to 0. The result is a number of 2 microsecond time increments that
the BASIC Stamp counted during discharge. How does this work?

First I/O pin 15 must be set high, to charge the capacitor to 5 Volts. When the BASIC Stamp gets to the
rctime command, it switches I/O pin 15 to input. The voltage starts to drop as shown in Figure 8.2. The BASIC
Stamp counts the number of 2 microsecond increments between switching to input and the time the voltage
at P15 crosses the 1.4 Volt logic threshold. The number of 2 microsecond increments then gets saved as the
result variable.

We'll use this segment of code in Program Listing 8.1 to measure the RC time. We will first wait 100 micro
seconds with pin P15 high. This gives the capacitor enough time to charge up.

high 15
pause 100

Basic Analog and Digital Student Guide Version 1.0 Page 137
Experiment #8: Light Meter Gizmo

Then rctime takes care of the time measurement and data storage.

rctime 15,1,light

Program It Enter Program 8.1 in your BASIC Stamp editor, and download to the BASIC
Stamp

'Program 8.1

light var word


discharge_time var word
sound var word

a con 40

loop:

high 15
pause 100
rctime 15,1,light

discharge_time = light*2

sound = (65535 - light)/a

'freqout 7,500,sound

debug home
debug "Discharge time = ",dec5 discharge_time, " u-seconds."
debug cr,cr, "Sound Frequency = ", dec5 sound, " Hz."
pause 500

goto loop

Page 138 Basic Analog and Digital Student Guide Version 1.0
Experiment #8: Light Meter Gizmo

The Output

The piezoelectric speaker should beep every half second or so. If you put your hand over the circuit to shade
it, the tone of the beep should get lower. If you face your breadboard directly at a light in the room, the pitch
should get higher. Figure 8.5 a sample output for a well-lit room.

Figure 8.5: Sample Debug Discharge time = 03190 u-seconds.


Output in a Well-lit Area with
no Direct Sun Sound frequency = 01598 Hz.

Figure 8.6 shows a sample output with a book casting a shadow over the light meter. The tone emitted by the
speaker is audibly lower.

Discharge time = 22706 u-seconds.


Figure 8.6: Sample Debug
Output in Shade Sound frequency = 01357 Hz.

Figure 8.7 shows the output under low light conditions.

Discharge time = 53912 u-seconds.


Figure 8.7: Sample Debug
Output Low Light Sound frequency = 00964 Hz.

Figure 8.8 shows a sample of the output with the lights out. Overflow occurred. The discharge time was more
than 65,536 microseconds. As a result, the variable reset to zero because the light variable also overflowed.
Since both discharge_time and light reset to zero, the variable sound reached its maximum. This is
because sound was programmed as: sound = (65535 light)/40. Light was reset to zero due to
overflow, so sound became (65535 -0)/40 = 1638.

Basic Analog and Digital Student Guide Version 1.0 Page 139
Experiment #8: Light Meter Gizmo

Figure 8.8: Sample Debug Discharge time = 00000 u-seconds.


Output in After Somebody
Turned Out the Lights Sound frequency = 01638 Hz.

Under brighter light conditions, the resolution is poor. You can replace the 1.0 uF capacitor with a 10.0 uF
capacitor to increase the resolution at higher light levels. For full sun, some kind of shade for the
photoresistor would help. If you are dealing with low light conditions, use a 0.1 uF capacitor instead.

The reason for using different capacitors is because the range of resistances for the photoresistor varies for
different ranges of light levels. Under lower lighting, the photoresistor has a much higher range of resistance
values than it does in a well-lit or full sun area.

As discussed earlier, the discharge time depends on the RC time constant, R C. If R tends toward a relatively
high range of resistances, using a smaller value of C will bring the value of R multiplied by C back down.
Likewise, if R is low, using a larger value of C helps bring the value of RC back up.

Do the Math

The RC time measurements along with the exponential decay equation can be a powerful tool for determining
an unknown resistance or capacitance.

t
VP15 = Vdd e C
R

Since we'll use PBASIC to make the BASIC Stamp tell us the measured amount of time, t, we have the following
information shown in Table 8.1.

Page 140 Basic Analog and Digital Student Guide Version 1.0
Experiment #8: Light Meter Gizmo

Table 8.1: Known Values at the Instant VP15 Crosses the Threshold Voltage

Values Comments
Vdd = 5.0 Volts The initial condition of the voltage at P15.
VP15 = 1.4 Volts The final condition of the voltage at P15.
e 2.718 The value of e is a constant found in many algebra books, physics texts, etc.
C = Can solve for If the value of resistance (R) is known, then the capacitance (C) can be determined.
t = Known The BASIC Stamp counts the time for us in 2 microsecond increments.
R = Can solve for If the value of capacitance (C) is known, then resistance (R) can be determined.

Algebra can be applied to the exponential decay equation to solve for R or C. First, take the natural log of
both sides of the equation. It eliminates the e term.

t
t
ln(VP15 ) = ln Vdd e C
R ln(VP15 ) = ln(Vdd )
RC

Rearranging terms yields:

t
= ln(Vdd ) ln(VP15 )
RC

Using properties of logarithms, this simplifies to:

t V
= ln dd
RC VP15

Rearranging again gives us an equality in terms of R and C and t:

t
RC =
V
ln dd
VP15

Basic Analog and Digital Student Guide Version 1.0 Page 141
Experiment #8: Light Meter Gizmo

If R is the unknown value, divide both sides by C. If C is the unknown value, divide both sides by R. The resulting
two equations are useful for determining an unknown R if C is known, or visa versa.

t t
R= or C=
V V
C ln dd R ln dd
VP15 VP15

Try a few different resistor and capacitor combinations from the Analog and Digital Parts Kit. Remember that
capacitor values can vary as much as 20% from their nominal (named) value. This will in turn cause error in
your measured values. However, if a resistor with a very low tolerance, such as 1% is available, the
measurements of capacitance can be pretty accurate. Once the capacitor has been calibrated, then it's
possible to take accurate resistance measurements with the CR circuit as well.

An alternative method of calibration is to take two resistors and measure their voltage divider output using a
DVM. Then swap the resistors and take the measurement again. The two voltage divider equations can be used
with these measurements to set up and solve two equations in two unknowns. The two resistance values are
the unknowns that get solved. Then the one of the resistors of known value can be used with rctime to
determine a capacitance with pretty good accuracy.

Page 142 Basic Analog and Digital Student Guide Version 1.0
Experiment #8: Light Meter Gizmo

What have I On the lines below, insert the appropriate words from the list on the
learned? left.

threshold Analog sensors that vary in resistance or capacitance are used to measure a variety of
physical quantities. An ______________ circuit can be used in conjunction with a BASIC
capacitance Stamp binary input pint to measure resistance or capacitance.

capacitor The ______________ is charged to 5-Volts, then it is allowed to discharge , and the
time it takes to get from 5-Volts to the ______________ voltage of a BASIC Stamp
RC input pin is measured. The equation for ______________ decay can then be used to
determine a value of resistance or capacitance if the other quantity is known.
exponential
An RC circuit where the resistance varies can be calibrated to a certain range of
discharge ______________ times by changing the value of the capacitor. This method can be
used because the resistance multiplied by the ______________ is logarithmically
related to the rate of decay.

Basic Analog and Digital Student Guide Version 1.0 Page 143
Experiment #8: Light Meter Gizmo

Questions

1. Given the circuit in Figure 8.3, how long will it take to discharge if the value of the photoresistor is 47 k?

2. For the discharge time in Question 1, would you expect any of the variables in Program Listing 8.1 to
overflow? If so, which ones? Explain your answer.

3. If the light conditions are so low that none of the capacitors in the kit work any more, a store bought
capacitor might be the answer. What values of capacitor might you try to find? Explain your answer.

4. For better resolution in the higher end of the light level scale, you can also reduce the value of a in
Program 8.1. How would that affect your debug window readout and the sound of the piezoelectric
speaker?

Challenge!

1. Design a circuit which has two photoresistors that are monitored. Assume that you will be displaying the
light intensity information on the debug Window, and that you won't be using a piezoelectric speaker.

2. Program the BASIC Stamp to monitor the light level at both of the photoresistors and display the
information using the debug window.

3. Try holding different colored papers in front of the photoresistors; black and white will work best. Write
a program to distinguish which photoresistor senses white and which sees black.

4. Make sure your program from Challenge #3 is not affected by the ambient light level in the room. Hint:
You will need to compare the RELATIVE intensities of the light measured by both photoresistors instead of
comparing them to some fixed number that was experimentally determined using a fixed value of
ambient light.

Page 144 Basic Analog and Digital Student Guide Version 1.0
Experiment #8: Light Meter Gizmo

Pretty neat, huh? We used light for our input and sound was our output.
Why did I We measured light intensity and generated a particular tone based on that
learn it? measured intensity.

This experiment illustrates how the concepts introduced in this series of


experiments can be mixed and matched to actually design an electronic device. It also demonstrates that
capacitors are not the exact value they are stated to be due to tolerances. You now know how to calculate the
capacitor value.

While learning all this, we've covered a number of circuit designs and a
wide variety of programming techniques. We've also gained some first
How can I hand experience with analog phenomenon. We've also covered how to
apply this? electronically interface, process, and in general, do things with a digital
device, the BASIC Stamp microcontroller. Below is a list of key concepts
that we've worked with in these experiments.

Experiment #1: Serial and parallel data, and synchronous and asynchronous communication.
Experiment #2: The comparator, the buffer, and threshold voltage.
Experiment #3: Analog to digital conversion, voltage dividers, and normalized voltage measurements.
Experiment #4: Digital to analog conversion, the resistive ladder network, and sound frequency and volume.
Experiment #5: The oscilloscope and time varying signals.
Experiment #6: The 555 timer, frequency and measuring frequency signals.
Experiment #7: The optical couple and pulse width management for D/A conversion.
Experiment #8: Building an electronic gizmo - a light meter, and A/D conversion using RC time constants.

These 8 experiments provide a first exposure to analyzing a variety of analog phenomenon, the basics of
electric circuits, and the essentials of digitally processing information about analog measurements using a
digital electronic device.

If you are an electronics hobbyist, hopefully there were a few items to add to your bag of electronic design
tricks. If you are a high school or college student continuing on to an electrical technical or engineering field,
you will undoubtedly revisit many of the concepts covered here in much grater detail. The BASIC Stamp can be
exceedingly useful for a wide variety of projects, in the sciences as well as in engineering.

Basic Analog and Digital Student Guide Version 1.0 Page 145
Experiment #8: Light Meter Gizmo

Many of the parts used in this series of experiment are vary basic and inexpensive. Applications kits and a
myriad of components are available that can be used to add a new level of functionality to the BASIC Stamp.
Some examples of these are digital keypads, liquid crystal displays and servo motors.

If you have completed this series of experiments as well as the Whats a Microcontroller series, connecting
these application kits will be a relatively simple matter. In addition, imagine what you can design and build
using a digital keypad, a liquid crystal display, and the analog interface concepts learned. Build an interface for
a factory automation process, a temperature and altitude sensor for your rocket system, or a weather
monitoring station.

Page 146 Basic Analog and Digital Student Guide Version 1.0
Appendix A: Parts Listing and Sources

All components (next page) used in the Basic Analog and Digital
experiments are readily available from common electronic suppliers.
Parts Listing Customers who would like to purchase a complete kit may also do so
through Parallax. To use this curriculum you need three items: (1) a
BASIC Stamp II module (available alone, or in the Board of Education
- Full Kit); (2) a Board of Education (available alone or in a Board of Education Full Kit); and 3) the Analog and
Digital Parts Kit. The typical setup consists of the Board of Education Full Kit and the Analog and Digital Parts
Kit.

Board of Education Kits

The BASIC Stamp II (BS2-IC) is available separately or in the Board of Education Full Kit. If you already have a
BS2-IC module, then purchase the Board of Education Kit. Individual pieces may also be ordered using the
Parallax stock codes shown below.

Board of Education Full Kit (#28102)


Parallax Code# Description Quantity
28150 Board of Education 1
800-00016 Pluggable wires 6
BS2-IC BASIC Stamp II module 1
750-00008 300 mA 9 VDC power supply 1
800-00003 Serial cable 1

Board of Education Kit (#28150)


Parallax Code# Description Quantity
28102 Board of Education and pluggable wires 1
BS2-IC Pluggable wires 6

This printed documentation is very useful for additional background information:

BASIC Stamp Documentation


Parallax Code# Description Internet Availability?
27919 BASIC Stamp Manual Version 1.9 http://www.stampsinclass.com
28125 Robotics Text http://www.stampsinclass.com
27951 Programming and Customizing the Table of Contents only from
BASIC Stamp Computer http://www.stampsinclass.com

Basic Analog and Digital Student Guide Version 1.0 Page 147
Appendix A: Parts Listing and Sources

The Basic Analog and Digital experiments require the Analog and Digital Parts Kit (#28128)

Similar to all Stamps in Class curriculum, you need a Board of Education with BASIC Stamp and the Parts Kit.
The contents of the Basic Analog and Digital Parts Kit is listed below. These replacement parts are available
from Parallax but may also be sourced from common electronic suppliers.

Analog and Digital Parts Kit (#28128)

Parallax Code# Description Quantity


150-01011 100 ohm resistors 5% 4
150-01020 1K ohm resistors 5% 8
150-01030 10K ohm resistors 5% 3
150-02020 2K ohm resistors 5% 10
150-02210 220 ohm resistors 5% 2
150-02710 270 ohm resistors 5% 2
150-04710 470 ohm resistors 5% 4
152-01040 100K ohm potentiometer 2
200-01040 0.1 uF mono-radial capacitor 1
201-01050 1.0 uF electrolytic capacitor 2
201-01062 10.0 uF electrolytic capacitor 1
350-00006 LED, red 3
350-00007 LED, yellow 1
350-00009 photoresistor 2
400-00002 tact switch 2
602-00015 LM 358 Op-amp IC 1
604-00009 555 timer IC 1
800-00016 3" jumper wires (bag of 10) 2
900-00001 piezo speaker 2
ADCO831 ADC 0831 8-bit A/D converter 1

Page 148 Basic Analog and Digital Student Guide Version 1.0
Appendix A: Parts Listing and Sources

The Parallax distributor network serves approximately 40 countries


Sources world-wide. A portion of these distributors are also Parallax-authorized
Stamps in Class distributors qualified educational suppliers. Stamps in
Class distributors normally stock the BASIC Stamp and Board of
Education (#28102 and #28150). Several electronic component companies
are also listed for customers who wish to assemble their own Robotics Parts Kit.

Country Company Notes


United States Parallax, Inc. Parallax and Stamps in Class source.
3805 Atherton Road, Suite 102 Manufacturer of the BASIC Stamp.
Rocklin, CA 95765 USA
(916) 624-8333, fax (916) 624-8003
http://www.stampsinclass.com
http://www.parallaxinc.com

United States Digi-Key Corporation Source for electronic components. Parallax


701 Brooks Avenue South distributor. May stock Board of Education.
Thief River Falls, MN 66701 Excellent source for components.
(800) 344-4539, fax (218) 681-3380
http://www.digi-key.com

Australia Microzed Computers Parallax distributor. Stamps in Class distributor.


PO Box 634 Excellent technical support.
Armidale 2350
Australia
Phone +612-67-722-777, fax +61-67-728-987
http://www.microzed.com.au

Australia RTN Parallax and Stamps in Class distributor.


35 Woolart Street
Strathmore 3041
Australia
phone / fax +613 9338-3306
http://people.enternet.com.au/~nollet

Canada Aerosystems Parallax distributor and Stamps in Class


3538 Ashby distributor.
St-Laurent, QUE H4R 2C1
Canada
(514) 336-9426, fax (514) 336-4383

Basic Analog and Digital Student Guide Version 1.0 Page 149
Appendix A: Parts Listing and Sources

Canada HVW Technologies Parallax distributor and Stamps in Class


300-8120 Beddington Blvd NW, #473 distributor.
Calgary, AB T3K 2A8
Canada
(403) 730-8603, fax (403) 730-8903
http://www.hvwtech.com

Germany Elektronikladen Parallax distributor and Stamps in Class


W. Mellies Str. 88 distributor.
32758 Detmold
Germany
49-5232-8171, fax 49-5232-86197
http://www.elektronikladen.de

New Zealand Trade Tech Parallax distributor and Stamps in Class


Auckland Head Office, P.O. Box 31-041 distributor.
Milford, Auckland 9
New Zealand
+64-9-4782323, fax 64-9-4784811
http://www.tradetech.com

United Kingdom Milford Instruments Parallax distributor and Stamps in Class


Milford House distributor.
120 High St., S. Milford
Leeds YKS LS25 5AQ
United Kingdom
+44-1-977-683-665
fax +44-1-977-681-465
http://www.milinst.demon.co.uk

Page 150 Basic Analog and Digital Student Guide Version 1.0
Appendix C: Manufacturer's Data Sheets

Most common types of resistors have colored bands that indicate


Resistor Color their value. The resistors that were using in this series of
Code experiments are typically 1/4 watt, carbon film, with a 5%
tolerance. If you look closely at the sequence of bands youll
notice that one of the bands (on an end) is gold. This is band #4, &
the gold color designates that it has a 5% tolerance.

The resistor color code is an industry standard in recognizing the value of resistance of a resistor. Each color
band represents a number and the order of the color band will represent a number value. The first two color
bands indicate a number. The third color band indicates the multiplier or in other words the number of zeros.
The fourth band indicates the tolerance of the resistor +/- 5, 10 or 20 %.

Color 1st Digit 2nd Digit Multiplier Tolerance


black 0 0 1
brown 1 1 10
red 2 2 100
orange 3 3 1,000
yellow 4 4 10,000
green 5 5 100,000
blue 6 6 1,000,000
violet 7 7 10,000,000
gray 8 8 100,000.000
white 9 9 1,000,000,000
gold 5%
silver 10%
no color 20%

Basic Analog and Digital Student Guide Version 1.0 Page 151
Appendix C: Manufacturer's Data Sheets

A resistor has the following color bands:

Band #1. = Red


Band #2. = Violet
Band #3. = Yellow
Band #4. = Gold

Looking at our chart above, we see that Red has a value of 2.

So we write: 2.
Violet has a value of 7.
So we write: 27

Yellow has a value of 4.


So we write: 27 and four zeros or 270000.

This resistor has a value of 270,000 ohms (or 270k) & a tolerance of 5%.

Page 152 Basic Analog and Digital Student Guide Version 1.0

You might also like