We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 321
Serial Port
Complete
Programming and Circuits for
RS-232 and RS-485
Links and Networks
Cables,
Network Connectors, &
Programming Terminations
Tips & Tricks
“IN
~~
_>
4
Sample Applications for
=Visual Basic
=Basic Stamp
™8052-Basic
incuves Jan Axelson
DISK! author of the best-selling
Parallel Port CompleteSerial Port
Complete
Programming and Circuits for
RS-232 and RS-485
Links and Networks
Jan Axelson
Lakeview Research
Madison, WI53704copyright 1998, 1999, 2000 by Jan Axelson. All rights reserved.
Published by Lakeview Research
Lakeview Research
5310 Chinook Ln.
Madison, WI 53704
USA
Phone: 608-241-5824
Fax: 608-241-5848
Email: [email protected]
WWW: hitp:/Wwww.lve.com
413 121110987654
Products and services named in this book are trademarks or registered trademarks of their
respective companies, The author uses these names in editorial fashion only and for the
benefit of the trademark owners. No stch use, or the use of any trade name, is intended to
convey endorsement or other affiliation with the book.
No part of this book, except the programs and program listings, may be reproduced in any
form, or stored in a database or retrieval system, or transmitted or distributed in any form,
by any means, electronic, mechanical photocopying, recording, or otherwise, without the
prior written permission of Lakeview Research or the author, except as permitted by the
Copyright Act of 1976. The programs and program listings, or any portion of these, may
be stored and executed in a computer system and may be incorporated into computer pro
grams developed by the reader.
The information, computer programs, schematic diagrams, documentation, and other
‘material in this book are provided “as is,” without warranty of any kind, expressed or
implied, including without limitation any warranty concerning the accuracy, adequacy, or
completeness of the material or the results obtained from using the material. Neither the
publisher nor the author shall be responsible for any claims attributable to errors, omis-
sions, or other inaccuracies in the material in this book. In no event shall the publisher or
author be liable for direct, indirect, special, incidental, or consequential damages in con
nection with, or arising out of, the construction, performance, or other use of the materi-
als contained herein,
ISBN 0-9650819-7-4Table of Contents
Introduction ix
1 Options and Choices 1
The Computers 1
‘The Programming 3
Languages and Operating Systems
Message Properties
‘The Link 5
Applications 7
2 Formats and Protocols 11
Sending Serial Data 11
Synchronous Format
Asynchronous Format
tem Support
ing a Byte 15
The Bit Format
Autodetecting the Bit Rate
Data Formats 18
Binary Data
Serial Port Complete iiiText Data
Preventing Missed Data 20
Handshakin;
Buffers
Polling and Interrupts
Acknowledgments
Error-checking
The PC’s Serial Port from the Connector In 25
Port Architecture 25
‘The UART
Enhancements
Port Resources 28
ing Ports
Port Information in the Registry
Configuring 31
‘New Systems
Adding a Port
Using Older Hardware
Internal vs. External Devices
IRQ Conflicts
Solutions for Multiple Ports
Inside the UART 40
Interrupt Sources
Control Registers
New Functions
PC Programming 45
Using MSComm 45
Properties
Text and Binary Transfers
Polled Communications
Using OnComm
Handshaking Options
A Template Application 55
‘The Main Form
General Routines
Selecting a Port
Saving Data
Other Ways to Access Serial Ports 80
API Functions
Direct Port Access
Serial Port CompleteUsing Older Basics 87
Visual Basic Versions
‘Accessing Ports under DOS
5 Microcontroller Serial Ports 91
Phe 8052-Basic 93
Communications Abilities
Processing Received Data
Custom Communications
‘The Basie Stamp 102
‘A Firmware UART
Signal Levels
Stamp-to-Stamp Links
Adding a Hardware Serial Port 113
Options
An SPI/Microwire UART
6 Linking Two Devices with RS-232 117
About RS-232 118
Features
Signals
Voltages
Timing Limits
Converting between SV Logic and RS-232 125
‘The MAX232
Other Interface Chips
Short-range Circuits
Port-powered Circuits 133
Alternate Interfaces 135
Direct Connection
Other Unbalanced Interfaces
7 Connectors and Cables for RS-232 139
Connectors 139
in Shells
9-pin Shells.
‘The Alt A Connector
Modular Connectors
Adapters.
Serial Port Completevi
Cables 146
Length Limits
How Many Wires?
Isolated Links 148
Ways to Achieve Isolation
‘About Grounds
Power Supply Grounds,
Optoisolating
Surge Protection
Troubleshooting Tools 155
RS-232 Applications 157
Linking Two Computers 157
‘A2-PC Link
Selecting a Remote CPU
PC-to-Basie Stamp Link 173
Exchanging Data
Ensuring that the Stamp Sees Incoming Data
PC-to 8052-Basic Link 177
Ensuring that the 8052-Basic Sees Incoming Data
Exchanging Data
Simple 1/0 179
Accessing the Signals
Connecting to a Stand-alone UART
Controlling Synchronous Interfaces
Operating System Tools 181
Direct Cable Connection
DOS InterInk and Intersvr
Links and Networks with RS-485 185
About RS-485 185
Balanced and Unbalanced Lines
Voltage Requirements
urrent Requirements
d
Adding an RS-485 Port 194
PC Expansion Cards
Converter Chips
Converting TTL
Converting RS-232
Short Links between Different Inte
Serial Port Complete10 RS-485 Cables & Interfacing 205
Long and Short Lines 205
When Is a Line Long?
Calculating Line Length
Line Terminations 210
Characteristic Impedance
Adding a Termination
Effects of Termi
Reflections
Terminations for Short Lines
Choosing a Driver Chip 222
Network Topologies 223
Open and Short-circuit Biasing 225,
Open-cireuit Protection
Short-cireuit Protection
Cable Types 230
How a Wire Picks Up Noise
Twisted-pair Cable
Selecting Cable
Grounds in a Differential Link 233
Ensuring a Common Ground
Isolated Links
Extending a Link with Repeaters 239
tions
11. Network Programming 241
Managing Traffic 241
‘Steps in Exchanging a Message
Protocols
Addressing 245
Assigning
Detecting
Other Information in Messages
Using Existing Protocols
‘Transmitter Enable Timing 249
12 Two Networks 253
An RS-485 Network 253
The Protocol
The Link
The Master's Programming
Selecting Nodes
Slave Programming
Serial Port Complete vilOne
viii
A Simple Stamp Network 259
Debugging Tips 275
Appendices
Resources 287
RS-232 Signals 291
Number Systems 293
Index 297
Serial Port CompleteIntroduction
Introduction
This book is a guide to designing, programming, installing, and troubleshooting
computer Tinks, including networks of multiple computers. Most of the links
described use one of two serial interfaces popularly known as RS-232 and
RS-485. The computers may be personal computers, embedded controllers, or any
devices that share a common interface. Common uses for these links include data
acquisition and control systems
What's Inside
Putting together a serial link of this type requires expertise both in circuit design,
to choose the components that make up the link, and in programming, to write the
code that controls the link. This book covers each of these.
PCs
For links that use PCs (personal computers), I describe the architecture shared by
the ports in all PCs, and show how to use a port’s features, with program code in
Visual Basic.
A template project gives a quick start for applications you write. The template
includes routines for finding ports in a system, enabling users to select and config-
Serial Port Complete ixIntroduction
lure a port, and other general-purpose functions commonly used in applications
that access serial ports.
Embedded Controllers
‘The examples for embedded controllers use one of two popular microcontroller
chips: Parallax’s Basic Stamp and the 80(C)52-
other sources. Both are based on popular microcontroller hardware: the PIC and
8051 families. Both can be programmed in dialects of Basic.
from Intel, Mieromint, and
Applications
The example applications include circuit designs and code for serial links between
two or more PCs and microcontrollers, us }-485, and simple direct
links. I also show how to use an RS-232 serial port as the power source for
low-power external circuits.
Cables and Interfacing
In a serial link, the proper cable and terminating components can prevent errors
due to electrical noise or malfunctioning hardware, This book shows how to
choose an appropriate cable and how to select or design the circuits that interface
to the cable
Who should read this book?
Readers from many backgrounds will find this book useful:
Programmers will find code examples that show how to use serial ports on PCs
and microcontrollers. Programming a network shared by multiple computers is
‘more involved than programming a link with just two computers. This book
explains the options and shows how to avoid the pitfalls
For hardware designers, there are details about serial-port circuits and how to
interface to them, including the design of converters to translate between RS-232,
RS-485, and 5V TTL logic. Examples show how to implement an RS-485 port on
PCs and microcontrollers and how to design links with features like bullet-proof,
failsafe circuits, high noise immunity, and low power consumption.
For system troubleshooters, there are hardware and software debugging tech-
niques, plus code for finding and testing ports and links,
Hobbyists and experimenters will find many ideas, along with explanations and
tips for modifying the examples for a unique application,
x Serial Port CompleteIntroduction
‘Teachers and students have found serial ports to be a handy tool for experiments
with electronics and computer control and monitoring. Many of the examples in
this book are suitable as a starting point for school projects
And last but not least, users, or anyone who uses a computer with serial ports, will
find useful information, including advice on configuring and adding ports.
How did you learn all this?
Readers who have found my books useful sometimes ask how I came to know the
information they contain. The short answer is that each of my books, including
this one, is the result of a continuous cycle of research and experiments.
Many companies do an excellent job of providing information to help customers
use their products. Manufacturers of the chips used in RS-232 and RS-485 inter-
faces have published dozens of application notes. The data sheets for the chips
themselves also hold many answers. All of this information is now easily avail-
able on the Internet. There are also many good books that cover related topics. See
the appendix of this book and Lakeview Research's web site for pointers to many
g00d sources of information.
But in the end there's no substitute for real-life experiments: putting together the
hardware, writing the program code, and watching what happens when the code
executes. Then when the result isn’t as expected—as it often isn’t—it means try-
ing something else or searching the documentation for clues. This book is result of
‘many, many hours of such research and experiments.
About the Program Code
Allof the code presented in the book (and more) is available for free downloading
from Lakeview Research's website (vww.lvr.com). All of the code uses some
variant of the Basic programming language.
| chose Basic for three reasons. First, much of this book is about trying things out
and learning how they work, and Basic’s interactive nature makes it a good choice
for this. Second, Basic is popular, so many readers will already be familiar with it
And third, Basic is what I know best. Throughout, I’ve tried to document the code
completely enough so that you can translate into another programming language if
you wish,
For each example, I assume you have a basic understanding of the language used,
whether it’s Visual Basic or a microcontroller Basic, and how to create and debug
programs. The book focuses on the details that relate specifically to serial commu
nications.
Serial Port Complete xiIntroduction
I developed the PC examples with Visual Basic 5. Because they're intended as
design tools, and not as finished applications, I provide the complete source code
but not compiled, executable programs. To compile the programs, you must have
copy of Visual Basic. I tested the code on a system running Windows 95. Visual
Basic code is generally compatible with Windows NT as well, but I didn’t test
under NT.
I also used Visual Basic to illustrate other short calculations. These use
Visual-Basic syntax, even when not presented explicitly as a code module. For
example, an asterisk (*) signifies multiplication,
For those programming for Windows 3.x, the example code won't load directly
into the older, 16-bit versions of Visual Basic, but you can copy and use many of
the routines with few or no changes. In some cases, I've provided DOS QuickBa-
sie code for use in systems using older or embedded PCs running DOS.
In a similar way, the microcontroller code examples are written for two popular
chips, but the ideas behind the code are adaptable to other controllers and lan-
guages,
‘The Visual Ba continuation character (_) to enable a single
line of code to extend over multiple lines thin each listing are
arranged alphabetically. The microcontroller code has no line-continuation char-
acter, and some program lines do carry over onto a second line in the listings in
the text. The listings you can download are formatted correctly and should load
and run without problems.
jc code uses the lin
‘The routines
About the Example Circuits
xii
ve included many schematic diagrams of circuits that you can use or adapt in
serial-port projects. In presenting the circuits, T assume you know the basics about
digital logic and electronic circuits. The circuit diagrams are complete, with these
exceptions:
Power-supply and ground pins are omitted when they are in standard locations
on the package (bottom left for ground, top right for power, assuming pin 1 is
top left
Power-supply bypass capacitors are omitted.
Some chips may have additional, unused gates or other elements that aren't
shown
In the schematics and text, active-low signals use a leading hyphen (-RESET) or
an overbar (RESET).
For more information on the components, see the manufacturers’ data sheets.
Serial Port CompleteIntroduction
Corrections and Updates
In putting together this book, I've done my best to ensure that the information is
complete and correct. Every schematic diagram with detail at the pinout level has
been built and tested by me, most of it multiple times, In a similar way, I've ran
and tested every line of code, But I know from experience that on the way from
test to publication, errors and omissions do occur.
Any corrections or updates to this book will be available at Lakeview Research's
World Wide Web site on the Internet at htip:/Avww.lvr.com. This is also the place
to come for links to other serial-port information on the Web, including software
tools, component data sheets, and web sites of vendors of related products,
Thanks!
Finally, I want to say thanks to everyone who helped make this book possible. As
with my previous Parallel Port Complete, I credit the readers of my articles in
The Microcomputer Journal, who first prompted me to write about these topics.
Some of the material in this book was first published in a different form in the
‘magazine. Others deserving thanks are the folks at compa
have generously provided information and answered questions about these topics
over the years.
jes large and small who
Serial Port Complete xiiiIntroduction
xiv
Serial Port CompleteOptions and Choices
Options and Choices
This book explores one corner of the computer universe: computers that are linked
together to monitor and control the world outside themselves. Each computer
exchange information with the others, and each can also calculate, decide, and
take action on its own, This type of link requires three things: computers to do the
work, programming that tells the computers what to do, and a link to connect
them. This chapter introduces options for each of these.
The Computers
Some projects need only a simple link between two computers, while others
require three or more computers that connect along a common path. In this book, 1
use the term /ink broadly, to refer (o a connection between two or more computers,
while a network is a link of at least three computers. Each computer in a link is a
node, of junction. Usually, each node can both send and receive, though in a sim-
ple link some nodes may communicate one-way only.
In the types of link described in this book, the computers may read sensors,
. They may control motors, relays, displays, or other out-
puts, Because the computers can communicate with each other, the result is an
integrated, intelligent system that enables one computer to react to or control
events at another.
switches, or other input
Serial Port Complete 1Chapter 1
‘The computers may be of any type, and they may be all the same, or a combina-
tion. This book focuses on two categories: personal computers and embedded
controllers
A personal computer (PC) may be a desktop machine or a laptop, notebook, or
subnotebook. The examples in this book use the family of computers that has
evolved from the IBM PC, including the models XT, AT, "386, "486, Pentium,
and their many clones and compatibles. But you can use any personal computer
that has an appropriate serial interface.
Anemibedded controller is a computer that’s dedicated to performing a single task
or a set of related tasks. Embedded controllers tend to be smaller and less complex
than PCs. Many are built into, or embedded in, the devices they control. An
embedded controller may have no keyboard or display and may be invisible to its
users. For example, PC peripherals such as printers and modems contain embed-
ded controllers that enable the peripherals to handle much of the work of printing
or communicating over the phone lines on their own,
Many embedded controllers have nothing at all to do with PCs. Cars, video-cas-
sette recorders, and microwave ovens are a few everyday items that contain
embedded controllers. Embedded controllers are also popular for one-of-a-kind or
small-scale, custom projects that involve simple control or monitoring tasks.
‘The CPU, or computer chip, in an embedded controller may be the same micto-
processor found in PCs, or it may be a microcontroller, which is a computer chip
designed specifically for use in control tasks
Microcontroller chips come in many varieties: 8-bit chips have an 8-bit data path
and are popular for use in monitoring and control links, but 4-, 16-, and 32-bit
chips are also available. Different chips have different features and abilities,
including serial ports of various types, varying amounts of memory for storing
programs and data, and low-power modes for battery-powered circuits. A moni-
toring and contro! link can use any microcontroller that can connect to the desired
interface.
‘The examples in this book use two microcontrollers: Parallax’s Basic Stamp and
Inte/Micromint’s 8052-Basic. Both are inexpensive and have on-chip Basic inter-
preters for easy programming and debugging.
One category of embedded controllers straddles both worlds. The embedded PC
has the architecture of a PC, but in a stripped-down form that may lack a
full-screen display, keyboard, or disk drives. Embedded PCs are popular because
they can use many of the PC’s familiar programming tools.
2 Serial Port Complete