• No results found

The Windows Serial Port Programming Handbook


Academic year: 2021

Share "The Windows Serial Port Programming Handbook"


Loading.... (view fulltext now)

Full text




Serial Port




The ABCs of IP Addressing

Gilbert Held

ISBN: 0-8493-1144-6

The ABCs of LDAP: How to Install, Run, and Administer LDAP Services

Reinhard Voglmaier ISBN: 0-8493-1346-5

The ABCs of TCP/IP

Gilbert Held

ISBN: 0-8493-1463-1

Building a Wireless Office

Gilbert Held

ISBN: 0-8493-1271-X

The Complete Project Management Office Handbook

Gerald M. Hill ISBN: 0-8493-2173-5

Enhancing LAN Performance, 4th Edition

Gilbert Held

ISBN: 0-8493-1942-0

Information Security Management Handbook, 5th Edition

Harold F. Tipton and Micki Krause, Editors ISBN: 0-8493-1997-8

Information Security Policies and Procedures: A Practitioner’s Reference 2nd Edition

Thomas R. Peltier ISBN: 0-8493-1958-7

Information Security Policies, Procedures, and Standards: Guidelines for Effective Information Security Management

Thomas R. Peltier ISBN: 0-8493-1137-3

Information Security Risk Analysis

Thomas R. Peltier ISBN: 0-8493-0880-1

Information Technology for

Manufacturing: Reducing Costs and Expanding Capabilities

Kevin Aki, John Clemons, and Mark Cubine ISBN: 1-57444-359-3

Interpreting the CMMI: A Process Improvement Approach

Margaret Kulpa and Kurt Johnson ISBN: 0-8493-1654-5

IS Management Handbook, 8th Edition

Carol V. Brown and Heikki Topi ISBN: 0-8493-1595-6

ISO 9000:2000 for Software and Systems Providers

Robert Bamford and William Deibler, III ISBN: 0-8493-2063-1

Managing a Network Vulnerability Assessment

Thomas R. Peltier and Justin Peltier ISBN: 0-8493-1270-1

A Practical Approach to WBEM/CIM Management

Chris Hobbs ISBN: 0-8493-2306-1

A Practical Guide to Security Engineering and Information Assurance

Debra Herrmann ISBN: 0-8493-1163-2

Practical Network Design Techniques, 2nd Edition: A Complete Guide for WANs and LANs

Gilbert Held and S. Ravi Jagannathan ISBN: 0-8493-2019-4

Real Process Improvement Using the CMMI

Michael West ISBN: 0-8493-2109-3

Six Sigma Software Development

Christine B. Tayntor ISBN: 0-8493-1193-4

Software Architecture Design Patterns in Java

Partha Kuchana ISBN: 0-8493-2142-5

Software Configuration Management

Jessica Keyes ISBN: 0-8493-1976-5

A Technical Guide to IPSec Virtual Private Networks

James S. Tiller ISBN: 0-8493-0876-3

Telecommunications Cost Management

Brian DiMarsico, Thomas Phelps IV, and William A. Yarberry, Jr. ISBN: 0-8493-1101-2

AUERBACH PUBLICATIONS www.auerbach-publications.com

To Order Call: 1-800-272-7737 • Fax: 1-800-374-3401 E-mail: orders@crcpress.com



A CRC Press Company

Boca Raton London New York Washington, D.C.



Serial Port



Ying Bai


This book contains information obtained from authentic and highly regarded sources. Reprinted material is quoted with permission, and sources are indicated. A wide variety of references are listed. Reasonable efforts have been made to publish reliable data and information, but the author and the publisher cannot assume responsibility for the validity of all materials or for the consequences of their use.

Neither this book nor any part may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, microfilming, and recording, or by any information storage or retrieval system, without prior permission in writing from the publisher.

The consent of CRC Press LLC does not extend to copying for general distribution, for promotion, for creating new works, or for resale. Specific permission must be obtained in writing from CRC Press LLC for such copying.

Direct all inquiries to CRC Press LLC, 2000 N.W. Corporate Blvd., Boca Raton, Florida 33431.

Trademark Notice:Product or corporate names may be trademarks or registered trademarks, and are used only for identification and explanation, without intent to infringe.

Visit the Auerbach Web site at www.auerbach-publications.com

© 2005 by CRC Press LLC Auerbach is an imprint of CRC Press LLC No claim to original U.S. Government works International Standard Book Number 0-8493-2213-8

Library of Congress Card Number 2004053125 Printed in the United States of America 1 2 3 4 5 6 7 8 9 0

Printed on acid-free paper

Library of Congress Cataloging-in-Publication Data

Bai, Ying, 1956–

The windows serial port programming handbook / Ying Bai. p. cm.

Includes bibliographical references and index. ISBN 0-8493-2213-8

1. Computer interfaces. 2. Parallel programming (Computer science) 3. Ports (Electronic computer system) I. Title.

TK7887.5.B35 2004 005.2'75—dc22

2004053125 AU2213_C00.fm Page iv Thursday, September 30, 2004 10:24 AM


Dedicated to my wife, Yan Wang,

and my daughter, Susan Bai

AU2213_C00.fm Page v Thursday, September 30, 2004 10:24 AM



Visual C++ 6.0TM is a trademark and a product of Microsoft Corporation. Visual Basic 6.0TM is a trademark and a product of Microsoft Corporation. MSDNTM Library is a trademark and a product of Microsoft Corporation. MAXIMTM is a registered trademark of Maxim Integrated Products, Inc.

Texas Instruments TM is a registered trademark of Texas Instruments Incorporated. MATLAB is a trademark and product of The MathWorks, Inc.

MATLAB Compiler is a trademark and product of The MathWorks, Inc.

MATLAB Instrument Control Toolbox is a trademark and product of The MathWorks, Inc. VisualWorksTM is a trademark of CinCom Systems, Inc.

VisualWorks DLL & C ConnectTM is a trademark of CinCom Systems, Inc. LabViewTM is a trademark of National Instruments Corporation.

JavaTM is a trademark of Sun Microsystems, Inc.


Table of Contents

About the Author ...xv

Acknowledgments ... xvii

Chapter 1 The Fundamentals of Serial Port Communications ...1

1.1 Introduction...1

1.2 Why Serial Port Communications Are Necessary...2

1.3 What Is Serial Port Communication? ...3

1.3.1 RS-232 ...3

1.3.2 RS-422 ...3

1.3.3 RS-485 ...4

1.3.4 Universal Serial Bus (USB) ...5

1.3.5 Controller Area Network (CAN)...6 CAN Standard Frame...8 CAN Extended Frame...8 Detecting and Signaling Errors...8

1.3.6 Firewire...9

1.4 Serial Port Communication Protocols...11

1.4.1 ASCII Code ...11

1.4.2 DTE and DCE ...12

1.4.3 Serial Data Format in TTL...12

1.4.4 Serial Data Format in Transmission Lines ...14

1.4.5 Baud Rate ...15

1.4.6 Parity...15

1.4.7 Serial Signal Handshaking and the Physical Connector ...16 DB-9 Connector ...18 DB-25 Connector ...21

1.4.8 Serial Signal Timing...23

1.5 Serial Port Cabling ...24

1.5.1 PC-to-Modem Cabling ...24

1.5.2 Null Modem Cabling...25

1.6 The Universal Asynchronous Receiver Transmitter (UART) ...26

1.6.1 Two Types of UARTs...28

1.6.2 UART Model Numbers ...30

1.6.3 The UART Transmitter...30

1.6.4 The UART Receiver ...32

1.6.5 Addressing the UART ...33

1.6.6 The 8250 UART ...33 8250 Architecture ...34 8250 Internal Registers ...35 8250 Register Functionality...37

1.6.7 The 8250 UART Interrupt Operations ...45

1.6.8 The 16550 UART ...50 The Receiver Buffer Register (RBR) ...50 AU2213_C00.fm Page vii Thursday, September 30, 2004 10:24 AM

(9) The FIFO Control Register (FCR) ...51 The Line Status Register (LSR) ...51

1.7 Modems and Flow Control ...52

1.7.1 Modem and Modem Control...52 Internal Modem and External Modem ...54 Modulation and Demodulation ...54 Amplitude Modulation ...54 Frequency Modulation ...55 Phase Modulation...55 Other Modulations ...56 Modem Control ...57

1.7.2 Flow Control and File Transfer Control ...57 Hardware Flow Control ...57 Software Flow Control...58 File Transfer Control...59 The XMODEM Protocol ...59 The XMODEM-CRC Protocol ...61 The XMODEM-1K Protocol ...62 The YMODEM Protocol...63 The YMODEM-G Protocol...64 The ZMODEM Protocol ...64 The Kermit Protocol ...65

1.8 Serial Communication Errors and Error Detection ...67

1.8.1 Block Redundancy—Checksum...67

1.8.2 The Classical CRC Algorithm ...68

1.8.3 Variations of CRC ...70

1.9 Serial Communications with the RS-422 and RS-485 ...70

1.9.1 Basics of the RS-422 Standard ...72

1.9.2 Basics of the RS-485 Standard ...73

1.9.3 The Operational Principle of the RS-485 ...73

Chapter2 Serial Port Programming for MS-DOS in ANSI C and Assembly Languages ...89

2.1 Introduction ...89

2.1.1 Virtual Machines ...89

2.1.2 MS-DOS-Compatible ANSI C Programming...89

2.2 A Loopback Serial Port Testing Program Developed in ANSI C...91

2.2.1 A Loopback Testing Program Developed in C...92 The _outp() and _inp() Functions...92 The Detailed Program Code ...92

2.3 Embedding Assembly Code into C Programming...95

2.3.1 Inline Assembly Code ...96

2.3.2 The _asm Keyword ...97

2.3.3 Using C/C++ in _asm Blocks ...98

2.3.4 Using Operators and Symbols in _asm Blocks ...98

2.3.5 Accessing C/C++ Data in _asm Blocks ...99

2.3.6 Using and Preserving Registers in Inline Assembly Code...100

2.3.7 Jumping to Labels in _asm Blocks...100

2.3.8 Calling C/C++ Functions in _asm Blocks ...100

2.3.9 Defining _asm Blocks as C Macros...102 AU2213_C00.fm Page viii Thursday, September 30, 2004 10:24 AM


2.3.10 Embedding Inline Assembly Code Within C Code ...103

2.4 A Serial Port Communication Program Developed in ANSI C...112

2.4.1 The Serial Port Communication Program on the Master Side ...114

2.4.2 The Serial Port Communication Program on the Slave Side...125

2.4.3 Testing the Serial Port Communication Program Using Two Computers ...132

2.5 A Serial Port Communication Program Developed in ANSI C and Inline Assembly Code...136

2.5.1 Embedding Inline Assembly Code with the Master and the Slave Computers...137

2.6 An Interrupt-Driven Serial Communications Program...139

2.6.1 The Interrupt Mechanism of the 8250 and 16550 UARTs ...140

2.6.2 A Sample Interrupt Program ...141

2.7 Programming the Interface Between PCs and A/D Converters ...145

2.7.1 An Eight-Bit A/D Serial Interface Developed in ANSI C ...146 The TLC548 Analog-to-Digital Converter ...146 The TLC548 Serial Interface Program ...148

2.7.2 An Eight-Bit A/D Serial Interface Developed in ANSI C and Inline Assembly Code ...154

2.7.3 A 12-Bit A/D Serial Interface Developed in ANSI C ...160 The MAX187—12-Bit Serial A/D Converter ...160 The MAX220—Multichannel RS-232 Drivers and Receivers ...162 The 12-Bit Serial A/D Converter Interface Circuit ...163 The 12-Bit Serial A/D Converter Interface Program ...165

2.7.4 A 12-Bit A/D Serial Interface Developed in C and Inline Assembly Code ...173

2.8 Chapter Summary...180

Chapter 3 Serial-Port Interfaces Developed in VC++ 6.0 ...183

3.1 Introduction...183

3.1.1 Configuring a Serial Port ...184

3.1.2 Writing Data to the Serial Port ...186

3.1.3 Reading Data from the Serial Port...187

3.2 A Single-Loop Serial Port Communication Test in C/C++ ...190

3.2.1 Hardware Installation ...190

3.2.2 Developing a Console Application Testing Program...190

3.2.3 A Serial Port Application in Visual C++ ...205 Developing the Document Class ...209 Developing the View Class...212 Developing the Dialog Box Classes ...220

3.3 A Double-Loop Serial Port Test in Visual C++ ...243

3.3.1 Hardware Connection ...243

3.3.2 A Console-Based Double-Loop Serial-Port-Testing Project ...245

3.3.3 A Double-Loop Serial-Port-Testing Project Using MFC ...260

3.4 RS-485 Serial Port Communication...288

3.4.1 Overview...288

3.4.2 An RS-485 Application for Real-Time Control ...289 Installing and Setting Up the NI-485 ...290 NI-485 Serial Port Setup and Installation ...291 Software Implementation with the NI-485...293

3.5 Chapter Summary...293 AU2213_C00.fm Page ix Thursday, September 30, 2004 10:24 AM


Chapter 4

Serial Port Programming in Visual BASIC ...295

4.1 Introduction...295

4.2 Calling Windows API Functions to Interface The Serial Ports...297

4.2.1 Windows API Functions...297 Mapping to a Subroutine ...300 Mapping to a Function...301

4.2.2 The API Viewer ...301

4.2.3 The API Functions, Structures and Constants in Serial Communications...304 Nonoverlapped I/O...305 Overlapped I/O...306

4.2.4 A Visual Basic Program Using Win32 API Functions...307 Developing Two Graphical User Interfaces...309 Adding Win32 API Functions to the VBAPISerial Project ...312 Developing the Setup Form ...316 Developing the frmSerial Form...318

4.2.5 Testing and Running the VBAPISerial Project...328

4.3 Using the Active-X MSComm Control to Interface with the Serial Ports ...331

4.3.1 Overview of the Active-X MSComm Control...331 Configuration Properties for the MSComm Control...332 Data Transfer Properties for the MSComm Control ...333 Handshaking Properties for the MSComm Control ...333 Identification Properties for the MSComm Control...335 The Operation of the MSComm Control ...335

4.3.2 A Serial Port Communication Program Developed with MSComm ...337 The Serial Interface Program for the Master Computer ...338 The Serial Interface Program for the Slave Computer ...360

4.3.3 A Serial Interface for the File Flow Control Between Two Computers...376 The File Transfer Program for the Master Computer ...376 The File Transfer Program for the Slave Computer ...398

4.3.4 Developing a Serial Interface For the TLC548 8-Bit A/D Converter...411 The Interface Circuit of the 8-Bit Serial A/D Converter ...411 The Interface Program Design...412 Implementation of the Serial Interface for the 8-Bit Serial A/D Converter...425

4.3.5 Developing a Serial Interface for the MAX187 12-Bit A/D Converter...427 The Interface Circuit of the MAX-187 A/D Converter ...428 Designing the Graphical User Interfaces...429 Coding the Project ...430 Implementation of the Serial Interface for a 12-Bit Serial A/D Converter...442

4.4 Calling Dynamic Link Library to Interface with the Serial Ports ...444

4.4.1 Review of the DLL...444

4.4.2 General Requirement for Calling a User-Defined DLL ...445

4.4.3 An Example of Calling DLL to Interface the Serial Port ...446 Configuring the Hardware for the Loop-Back Test ...447 Developing a Dynamic Link Library in Visual C++ ...447 Developing a Visual Basic Testing Project...460

4.5 Chapter Summary...472 AU2213_C00.fm Page x Thursday, September 30, 2004 10:24 AM


Chapter 5

Serial Port Programming in LabVIEW ...475

5.1 Introduction...475

5.2 A Basic Serial Port Interface for Writing and Reading Data ...475

5.2.1 Designing the Front Panel for the Loopback Testing Program...476

5.2.2 Designing a Block Diagram for the Loopback Testing Program...477

5.2.3 Running and Testing the Loopback Testing Program ...480

5.3 Advanced Serial Port Interfaces...481

5.3.1 Using VISA to Interface with an 8-Bit Serial A/D Converter, TLC548...481 Designing a Front Panel for the Main Program...483 Develop a Block Diagram for the Main Program...485 Designing a Front Panel for the Data Collection SubVI ...488 Developing a Block Diagram for the Data Collection SubVI ...490 Testing and Running the Project ...497

5.3.2 Using VISA to Interface with an 12-Bit Serial A/D Converter MAX187...499 Designing a Front Panel for the Main Program...501 Developing a Block Diagram for the Main Program...502 Designing a Front Panel for the GetMAXData SubVI ...505 Developing a Block Diagram for the GetMAXData SubVI ...507 Configuring the GetMAXData VI as a SubVI...514 Testing and Running the Project ...515

5.4 Calling the DLL from LabVIEW to Interface with the Serial Port...517

5.4.1 Using Call Library Function and the Code Interface Node ...517

5.4.2 Using the Call Library Function to Access DLLs...517 The Calling Conventions ...519 The Calling Parameters...520 Calling Functions That Expect Other Data Types ...521 The Create.c File...522 Multiple Calls to the Shared DLL Function ...522

5.4.3 Using the Call Library Function to Interface with the TLC548 Serial A/D Converter ...523 Interface Circuit of the TLC548 Serial A/D Converter ...523 Building the Function Protocol in LabVIEW ...524 Building the Block Diagram in LabVIEW ...528 Building DLL Functions in Visual C++...530

5.5 Calling the CIN from LabVIEW to Interface with the Serial Port...547

5.5.1 The Calling Procedure of the CIN...548 Creating a CIN ...548 Creating a .c File...550 Using the Visual C++ IDE to Compile the CIN Source Code ...551 Loading the CIN Object Code...552

5.5.2 Using CIN to Interface with a Serial A/D Converter ...552 The Hardware Interface Circuit ...552 Designing of a Front Panel for the Project ...553 Using CIN to Develop a Block Diagram ...553 Using the Visual C++ 6.0 IDE to Develop the CIN Object Code...559 Loading the CIN Object Code and Running the Project ...582

5.6 Other Methods for Interfacing with the Serial Port ...585 AU2213_C00.fm Page xi Thursday, September 30, 2004 10:24 AM


Chapter 6

Serial Port Programming in MATLAB...587

6.1 Introduction...587

6.2 Using MEX-files to Interface with Serial Ports ...587

6.2.1 The MEX-File Format...588

6.2.2 System Setup and Configuration...589 Select a Compiler...589

6.2.3 The Ingredients of a MEX-file...591 Header File mex.h...591 The mxArray ...591 Using the Gateway Function mexFunction in C/C++ ...592 API Functions ...595

6.2.4 Creating a MEX-file in C/C++ ...596

6.2.5 Using a MEX-file to Interface with the MAX187 ADC...597 Configuring the C/C++ MEX-file...599 Designing the Header File for the MEX-file ...600 Designing the DEF File ...603 Designing the Source File of the MEX-file ...603 Compiling and Building the Target MEX-file...617 The Design of the MATLAB M-Function ...618 Testing and Running the Project ...619

6.2.6 Creating a MEX-file to Interface with the TLC548 ADC ...621

6.3 Using the Shared DLL to Interface with the Serial Ports ...622

6.3.1 Installing the Loadlibrary Interface ...622

6.3.2 Loading and Unloading the Shared Library ...624

6.3.3 Obtaining Information from the Library...624

6.3.4 Calling Library Functions and Passing Arguments ...625

6.3.5 Converting Data Between MATLAB and External Functions ...626 Primitive Data Types...627 Converting Data to Other Primitive Data Types ...627 Converting Data to References ...628 Converting to Strings ...628 Converting and Passing Structures ...629 Creating References ...631 Creating a Structure Reference...633 Creating Reference Pointers ...634

6.3.6 Calling a Shared DLL ...635 Developing a Standard Win32 Dynamic Link Library ...635 Developing a MATLAB M-Function to Call the DLL ...638 Testing and Running the DLL Project ...645

6.4 Using the Serial Object to Interface with the Serial Ports...647

6.4.1 The Instrument Control Toolbox...647

6.4.2 Creating and Configuring a Serial Port Object ...648

6.4.3 Writing and Reading the Serial Port Object...649

6.4.4 Event and Callback Functions...650 The BytesAvailable Event and Its Callback Function BytesAvailableFcn...651 The Output Empty Event and Its Callback Function OutputEmptyFcn...651 The PinStatus Event and Its Callback Function PinStatusFcn..651 AU2213_C00.fm Page xii Thursday, September 30, 2004 10:24 AM

(14) The Timer Event and Its Callback Function TimerFcn...652 The Break Interrupt Event and Its Callback Function BreakProcess()...652

6.4.5 Using the Serial Port Object to Perform Data Transmission ...652 Using the Graphical Tool to Create and Configure a Serial Port ...652 Developing a User-Defined Callback Function...656 Developing the Main Serial Port Interface Program...656 Testing and Running the Main Serial Port Interface Program ...658

Chapter 7 Serial Port Programming in Smalltalk...659

7.1 Introduction...659

7.2 Overview of VisualWorks...659

7.2.1 The VisualWorks Application Framework ...660

7.2.2 Installing and Starting VisualWorks...661

7.3 A Simple Serial Port Interface Program ...664

7.3.1 Serial Port Testing Configuration...664

7.3.2 Developing a Domain Model Class ...665

7.3.3 Developing an Application Model Class and a GUI...668

7.3.4 Developing an External Interface Class...669

7.3.5 Finish Coding of the SerialPort Project in VisualWorks...674 Code for the Application Model...675 Code for the Domain Model...677

7.3.6 Parceling and Filing Out the Project Files ...680

7.3.7 Develop a Dynamic Link Library in the Visual C++ Domain...681 Creating the Header File for the DLL...681 Developing the Source File for the DLL ...681 Developing the Definition File for the DLL ...690

7.3.8 Finishing Coding of the SerialPort Project in VisualWorks...691

7.4 An Advanced Serial Port Interface Program ...694

7.4.1 The Interface Circuit ...695

7.4.2 Developing the Dynamic Link Library...696 The Header File for the DLL ...696 Code for the Source Files of the DLL ...698 Developing the Definition File for the DLL ...707 Building and Installing the DLL Target File...708

7.4.3 Developing a Domain Model Class ...708

7.4.4 Developing an Application Model Class and a GUI...712

7.4.5 Developing an External Interface Class...715

7.4.6 Finish Coding of the SmallMAXDLL Project in VisualWorks ...719 Code of the Application Model Class ...719 Code for the Domain Model Class...721

7.4.7 Testing and Running the Project...724

7.4.8 Parceling and Filing Out the Project Files ...726

Chapter 8 Serial Port Programming in Java ...729

8.1 Introduction...729

8.2 Overview of the Java Native Interface...729 AU2213_C00.fm Page xiii Thursday, September 30, 2004 10:24 AM


8.2.1 Why We Need an Interface Between Java and the Native Code ...729

8.2.2 The JNI Development Environment ...730

8.2.3 How to Develop an InterFACE ...731

8.3 A Simple Serial Port Testing Program Using the JNI ...732

8.3.1 Setting Up the Java Development Environment in Windows 95/98/Me...732

8.3.2 Setting Up the Java Development Environment in Windows 2000 ...733

8.3.3 Setting Up the Java Development Environment in Windows XP ...734

8.3.4 Setting Up the Hardware for the Single-Port Loopback Test ...734

8.3.5 The Operation of the Interface Program...735

8.3.6 Developing a GUI in Java ...736

8.3.7 Developing the Model Class File...741

8.3.8 Developing the Interface Class File...743

8.3.9 Developing the MSG Class File...745

8.3.10 Developing a JNI-Style Header File ...746

8.3.11 Mapping Variables and Objects Between Java and C/C++...747 Mapping String Variables...749 Mapping Array Variables ...751

8.3.12 Developing a Dynamic Link Library as the Native Library...754 Developing the Header File ...755 Developing the Source File ...757

8.3.13 Building and Installing the Native Library...766

8.3.14 Running and Testing the Project...767

8.4 An Advanced Interface Between the Serial A/D and Java...769

8.4.1 Developing the View Class—Java GUI Window ...770

8.4.2 Developing the Model Class ...773

8.4.3 Developing the Interface Class ...775

8.4.4 Creating a JNI-Style Header File...775

8.4.5 Developing the Native Library (the DLL Target File) ...777 Developing the DLL Header File ...778 Developing the DLL Source File ...778

8.4.6 Building and Installing the DLL Target File ...789

8.4.7 Testing and Running the MAX187 Project ...790

8.5 Chapter Summary...792

Appendix ...795

Index ...797 AU2213_C00.fm Page xiv Thursday, September 30, 2004 10:24 AM


About the Author

Dr. Ying Bai is an Assistant Professor in the Department of Computer Science and Engineering at Johnson C. Smith University. His special interests include computer architecture, software engi-neering, mixed-language programming, embedded controllers, automation and robot control, and robot calibration. His industry experience includes positions as a software engineer and senior software engineer at such corporations as Motorola MMS, Schlumberger ATE Technology, Immix TeleCom, and Lam Research. His work with these companies has involved applying various programming languages in the Windows environment to solutions for automation control, automa-tion testing, and accuracy measurements.



The first thanks I give should go to my wife, Yan Wang. I could not have finished this book without her sincere encouragement and support, especially during the hard times.

Special thanks also to Mr. John Wyzalek, who has made my dream into a fact by making this book available to you readers. You would not have found this book on the market without John’s deep perspective and hard work. The same thanks go to the editing team. Without these people’s contributions, publishing the book would have been impossible.

I’d like to thank Mr. Jonathan Champ for taking the time to review my preface.

I also appreciate the help given by Dr. Attia Magdy and Dr. Bahalla Satish, both of whom provided me with very useful opinions as I was writing the book.

Finally, but not least, I wish to extend my thanks to all the people who supported me and helped me to finish this book.




The Fundamentals of Serial Port



With the rapid development of modern communications and computer technologies, communication between individuals, between individuals and groups, and between individuals and society has become more and more important. Almost all communication devices used today are closely related to computer technologies; these tools include digital telephones, cell phones, pagers, mobile phones, the Internet and Internet services, image phones, server/client communications, and fiber commu-nication. All these modern communication technologies play a vital role in our society today.

The different communication technologies applied in all fields can be divided into two categories: • Wire communications

• Wireless communications

Wire communication can be further divided into two subcategories: • Electronic wire communications

• Fiber wire communications

Electronic wire communications can be categorized into analog and digital communication technologies. Most modern communication technologies use digital data transfer. Generally, the electronic wire communications used in computer technologies are digital technologies, and they come in two styles:

• Parallel communications • Serial communications

Parallel communications can exchange or translate data between two devices in a parallel style, which means that multiple bits of data (such as 8-bit, 16-bit, or 32-bit data) can be transferred between two pieces of equipment simultaneously. Obviously, in parallel communication, the two devices must be connected with multiple wires; the relationship between the connected wires and the data to be translated is one to one, which means that one data bit travels over one wire.

Serial communications, on the other hand, can exchange or translate data between two devices only in a bit-by-bit fashion, like a sequence, by using a single wire. It should be noted that serial communication needs fewer wires, so the hardware connections are simpler. Figure 1.1 shows diagrams of both parallel and serial communications.

It can be seen in Figure 1.1 that a parallel interface port (a) needs to use more wires, which makes the interface more complicated. To compensate, those wires provide a high-speed data translation because the data is processed simultaneously by all the wires. The serial interface port (b) uses only a single wire to translate all the data bit by bit, which means that at any moment, only one bit of data can be translated from device I to device II. Figure 1.1 illustrates the translation of a binary data byte (01100101) through both parallel and serial interface ports. Relatively speaking, a slower translation speed is expected in the serial communication style.


2 The Windows Serial Port Programming Handbook


Why are serial communications so important if the parallel interface port is available? To answer this question, an understanding of the following facts is required.

In the early days of computers, most data communications utilized parallel ports due to the slow running speed of the central processing unit (CPU). The typical CPU processing speed was between 10 and 200 MHz. The devices that used parallel port communications were hard disks, floppy disks, printers, scanners, and zip disk drives. The processing speed was the first priority for any slow computer. The disadvantages of using a parallel port interface included the complicated interface circuits, the high cost, and a limited data translation distance (less than 10 feet).

Since the twenty-first century, the running speed of CPUs has increased significantly. Today most normal computers can run at a speed of 1 or 2 GHz. Because running speed is no longer an obstacle, long-distance translation and low cost have become the main priorities in today’s data communications. Serial port communications can now handle much longer-distance data translation (over 4,000 feet) at very low cost. Also, the hardware used for serial port communications is much simpler than that used for parallel port communications.

Most operating systems provide the appropriate communication drivers for serial ports; there-fore, users aren’t required to spend time developing (and learning to develop) serial port device drivers. Instead, they can spend time directly developing the user programs that talk to the serial ports to perform the data communications between computers, between servers and clients, and between the different devices that use serial ports.

For parallel port interfaces, it is a different story. Different parallel devices require that the associated device drivers be developed and installed, which is not an easy job even for experienced software developers. Some general-purpose parallel port interfaces are available, such as IEEE-488. If a user adopts such a general-purpose parallel port interface tool, he or she still needs to learn how to modify the equipment’s subroutine to match the requirements of the interface.

Based on these facts, more and more peripheral devices (such as printers, zip drives, and scanners) are being expected to communicate with computers via serial port interfaces. Today universal serial bus (USB) drivers are the tools used most often for connecting computers to printers, scanners, floppy drives, and even hard disks (for example, the Iomega__HDD 250GB USB2.0/FireWire External Desktop Hard Drive). You can even find different sizes of USB flash memory on the market to increase the memory size of your computer.

It can be expected that the serial port interface will play an increasingly important role in today’s computer technologies and communications. For this reason, it is important that developers understand the principles of serial communications so that they can develop sophisticated programs to support a variety of serial interfaces. Helping you achieve these dual goals is the objective of this book.

FIGURE 1.1 (a) Parallel and (b) serial data communications.



1 0 Device-II 1 0 0 1 0 1 0 1 1 0 0 1 0 1


The Fundamentals of Serial Port Communications 3


In the early 1960s, a standards committee, today known as the Electronic Industries Association (EIA), developed a common interface standard for data communications equipment. At that time, data communication was thought to mean a digital data exchange between a centrally located mainframe computer and a remote computer terminal, or possibly between two terminals without a computer involved. These devices were connected by telephone voice lines and consequently required a modem at each end for signal translation. Although simple in concept, the many opportunities for data errors that occurred when transmitting data through an analog channel required a relatively complex design. It was thought that a standard was needed first to ensure reliable communication, and second to enable the interconnection of equipment produced by different manufacturers, thereby fostering the benefits of mass production and competition. From these ideas, Recommended Standard Number 232, Revision C (RS232C) was born. It specified signal voltages, signal timing, signal function, protocols for information exchange, and mechanical connectors.

Over the more than 40 years since this standard was developed, the EIA published three modifications, the most recent being the EIA232E standard introduced in 1991. Beyond changing the standard’s name from RS232 to EIA232, some signal lines were renamed and various new ones were defined, including a shield conductor.

Serial communications can be divided into different groups based on their operation principles. The following sections describe the different serial port communication groups.

1.3.1 RS-232

As previously mentioned, RS-232 is a protocol developed and defined by EIA in the 1960s that was used in early serial data communications. Because of its simplicity and popularity, RS-232 has been widely applied in all data communication fields, including industrial, commercial, edu-cational, and even consumer electronics. RS-232 belongs to the full-duplex communication protocol, which means that both senders and receivers can exchange information simultaneously. The half-duplex communication protocol allows users (senders and receivers) to send or receive information between one another only at different periods of time; they cannot send and receive simultaneously. This means that the receiver has to wait until the sender finishes sending information; then the receiver can pick up and respond to the sender’s information. At any moment, only one user, either sender or receiver, can control the transmission of data.

The simplest RS-232 protocol utilizes three wires: One wire is used to send information, one is used to receive information, and a third wire works as the ground or reference between the two devices. The information transmitted on RS-232 wires is represented as a sequence of binary bits, and the values of those binary bits are associated with two voltage levels: 12 volts (Space, or logical 1) and 12 volts (Mark, or logical 0). The data transmission speed is controlled by the baud rate, (the number of binary bits that can be transmitted per second), which can be indicated and set up by the user before the data transmission. In the early days, data transmission speed was relatively slow because of the slow CPU speeds, and typical baud rates were 1,200, 4,800, and 9,600. Baud rates applied in today’s serial data communication have increased significantly and are typically 19,200, 38,400, and even higher. In short, the RS-232 port is designed to communicate with local devices and will support one driver and one receiver.

The typical transmission distance of the RS-232 protocol is less than 50 feet. To increase this distance and reduce noise and disturbance, RS-422 was developed.

1.3.2 RS-422

RS-232 serial port communication is part of a single-ended protocol, meaning that the value of each binary bit has an absolute voltage level relative to the ground. This single-ended protocol has


4 The Windows Serial Port Programming Handbook

shortcomings when it comes to data transmission. One of the most important disadvantages is its inability to overcome or reduce noise and disturbances during the information transmission. Even when 12 volts is utilized as its signal level, the RS-232 still may encounter big, sharp pulses or other disturbances during data transmission or receipt, increasing the possibility that mistakes will occur in the signal transmission and that information will be made invalid.

To solve this problem, another serial communication protocol, RS-422, has emerged. RS-422 uses a differential signal transmission mode, which means that at any time, a binary bit value has a relative voltage flowing from the positive signal terminal to the negative signal terminal. Unlike the transmission wires used with RS-232, the wires for both the sending and receiving lines are doubled, and these double wires are twisted together to work as a single line (either a sending or a receiving line) to further reduce environmental disturbances.

When communicating at high baud rates or over long distances in real-world environments, single-ended methods are often inadequate. A differential data transmission (or a balanced differ-ential signal) offers superior performance in most applications. Differdiffer-ential signals can help nullify the effects of ground shifts and induced noise signals that can appear as common mode voltages during the communication of data.

RS-422 is designed for greater distances and higher baud rates compared with RS-232. In its simplest form, a pair of converters from RS-232 to RS-422 (and back again) can be used to form an “RS-232 extension cord.” Baud rates of up to 100 kbps and distances up to 4,000 feet can be accommodated with RS-422. RS-422 is also specified for multidrop (nodes) applications, where only one driver is connected to, and transmits on, a bus of up to 10 receivers.

Although a multidrop-type application has many desirable advantages, RS-422 devices cannot be used to build truly multipoint communication systems. A true multipoint communication system consists of multiple drivers and receivers connected on a single “bus,” where any node can transmit or receive data.

Quasi-multidrop systems (four-wire systems) are often constructed from RS-422 devices. These systems are often used in a half-duplex mode, where a single master in a system sends a command to one of several slave devices on a network. Typically, one device (node) is addressed by the host computer, and a response is received from that device. This kind of system (four-wire, half-duplex) is often constructed to prevent data collision (or bus contention) problems on a multidrop network. 1.3.3 RS-485

RS-485 is similar to RS-422 in the differential signal transmission protocol, but the former has the capability to build a truly multipoint communication system. This means that multiple terminals or computers, which are considered nodes, can be connected to a common bus, and each node can work as either a sender or receiver of information from this bus. Each terminal or computer connected to the bus has a tristate control functionality and a unique address (or ID), and the communication between the sender and receiver is performed based on this ID.

RS-485 will support 32 drivers and 32 receivers in bidirectional, half-duplex, multidrop com-munications over single or dual twisted-pair wires. An RS-485 network can be connected in a two-or four-wire mode. The maximum cable length can be as much as 4,000 feet because of the differential voltage transmission system used. The typical use of RS-485 is for a single PC connected to several addressable devices that share the same cable. You can think of RS-485 as a party-line communications system. (The addressing is handled by the remote computer unit.) RS-232 may be converted to RS-485 with a simple interface converter; it can have optical isolation and surge suppression.

Electronic data communications between elements will generally fall into two broad cate-gories: single-ended and differential communications. RS-422 and RS-485 belong to the differ-ential mode data transmission category, but RS-232 is from the single-ended transmission mode. The specification of RS-232 allows for data transmission from one transmitter to one receiver at


The Fundamentals of Serial Port Communications 5

relatively slow data rates (up to 20 kbps) and short distances (up to 50 feet at the maximum data rate).

To solve the data collision problem often present in multidrop networks, hardware units (converters, repeaters, microprocessor controls) can be constructed to maintain a receive mode until they are ready to transmit data. Single-master systems (many other communications schemes are available) offer a straightforward and simple means of avoiding data collisions in a typical two-wire, half-duplex, multidrop system. The master initiates a communications request to a slave node by addressing that unit. The hardware detects the start bit of the transmission and automatically enables (on the fly) the RS-485 transmitter. Once a character is sent, the hardware reverts back to a receive mode in about one to two microseconds.

Any number of characters can be sent, and the transmitter will automatically be restarted with each new character (or in many cases a bit-oriented timing scheme is used in conjunction with network biasing for a fully automatic operation, including any baud rate and/or any communication specification). Once a slave unit is addressed, it can respond immediately because of the fast transmitter turn-off time of the automatic device. It is not necessary to introduce long delays in a network to avoid data collisions, because delays are not required and networks can be constructed to utilize the data communications bandwidth with up to 100 percent throughput.


USB provides an expandable, hot-plugging Plug and Play serial interface that ensures a standard, low-cost connection for peripheral devices such as keyboards, mice, joysticks, printers, scanners, storage devices, modems, and video conferencing cameras. Migration to USB is recommended for all peripheral devices that use legacy ports such as the PS/2, serial, and parallel ports.

USB was originally developed in 1995 by many of the same industry-leading companies currently working on USB 2.0. The major goal of USB is to define an external expansion bus that makes adding peripherals to a PC in a serial communication mode as easy as hooking up a telephone to a wall jack. The program’s driving goals are ease of use and low cost. An external expansion architecture enables these goals and has the following highlights:

• PC host controller hardware and software • Robust connectors and cable assemblies • Peripheral friendly master-slave protocols • Expandability through multiport hubs

The role of the system software is to provide a uniform view of the input/output (I/O) system for all applications software. It hides hardware implementation details so that application software is more portable. For the USB I/O subsystem in particular, the system software manages the dynamic attachment and detachment of peripherals. This phase, called enumeration, involves communicating with the peripheral to discover the identity of a device driver that it should load, if it is not already loaded. A unique address is assigned to each peripheral during enumeration to be used for run-time data transfers. During run run-time, the host PC initiates transactions to specific peripherals, and each peripheral accepts its transactions and responds accordingly. Additionally, the host PC software incorporates the peripheral into the system power-management scheme and can manage overall system power without user interaction.

All USB peripherals are slaves that obey a defined protocol. They must react to request transactions sent from the host PC. The peripheral responds to control transactions that, for example, request detailed information about the device and its configuration. The peripheral sends and receives data from the host using a standard USB data format. This standardized data movement to and from the PC host with interpretation by the peripheral gives USB enormous flexibility with


6 The Windows Serial Port Programming Handbook

little PC-host software changes. USB 1.1 peripherals can operate at 12 or 1.5 Mbps, but the USB 2.0 specification has a design data rate of 480 Mbps.

Although USB is a serial communication device, you cannot use serial device drivers to directly talk to any USB device because it works in a dynamic mode, and it can be plugged to or hot-unplugged from a host computer. A special device driver is needed to successfully interface to any USB device. Microsoft provides some useful tools, such as Windows NT Device-Driver Develop-ment Kits (NT DDK) and Windows 2000 and 98 Device-Driver DevelopDevelop-ment Kits (2000 and 98 DDKs), to help users to develop suitable drivers to interface with USB devices. Windows 2000 and 98 DDKs are free for downloading from the Microsoft Web site at www.microsoft.com/ddk. These DDKs also provide sample code and documentation to help you get started. Also, the developer’s Webboard at this site contains postings of questions and solutions for writing drivers. Today USB is enjoying tremendous success in the marketplace, with most peripheral vendors around the globe developing products to this specification. Virtually all new PCs come with one or more USB ports. In fact, USB has become a key enabler of the Easy PC Initiative, an industry initiative led by Intel and Microsoft to make PCs easier to use. This effort sprung from the recognition that users need simpler, easier-to-use PCs that don’t sacrifice connectivity or expand-ability. USB is one of the key technologies used to provide this.

Early versions of USB include USB 1.0 and 1.1. Today USB version 2.0 provides system manufacturers with the ability to connect to high-performance peripherals in the least expensive way. The additional performance capabilities of USB 2.0 can be added with little impact to the overall system cost. Indeed, high-bandwidth interfaces such as small computer system interface (SCSI) adapters may no longer be required in some systems, leading to a net savings of system cost. Simpler construction will result because only USB connectors will be needed on many future PCs. Today’s ubiquitous USB connectors will become USB 2.0, superceding USB 1.1, and today’s USB devices will operate with full compatibility in a USB 2.0 system.

The added capabilities of USB 2.0 will expand the market segment for USB peripherals while enabling retail products to transition with the installed base. Support of USB 2.0 is recommended for hubs and higher-bandwidth peripherals.

Designing a USB 2.0 peripheral is an engineering effort similar to designing a USB 1.1 peripheral. Some low-speed peripherals, such as human interface devices (HIDs), may never be redesigned to support the USB 2.0 high-speed capability to maintain the absolute lowest cost.


The controller area network (CAN) is a serial bus system specially suited to interconnect smart devices in order to build smart systems or subsystems. CAN was first developed from a Bosch internal project, which was to develop an in-vehicle network in 1983. In 1987, the first CAN controller chips from Intel and Philips Semiconductors emerged on the market. An international users and manufacturers group, CAN in Automation (CiA), was established in 1992.

Today you can find CAN in many different implementations, including a wide area of industrial and manufacturing fields. The automotive industry uses CAN as the in-vehicle network for engine management, body electronics such as door and roof control, air conditioning, lighting, and enter-tainment controls. Factory automation uses CAN to build smart factories, and the protocol known as DeviceNet is mainly used in this area. Such companies as Rockwell Automation (formerly Allen-Bradley) have made DeviceNet the most successful network in factory automation in the United States and in the Far East.

CAN is used as an embedded network for machine control within industries such as textiles, printing, injection molding, and packaging. Mainly, the protocol CANopen is used for such appli-cations. Embedded controls can also be found in building automation, maritime functions, the medical field, and railway applications.


The Fundamentals of Serial Port Communications 7

The CAN protocol is an international standard defined in ISO 11898. Beyond the CAN protocol itself, the conformance test for the CAN protocol is defined in the ISO 16845, which guarantees the interchangeability of the CAN chips. Figure 1.2 shows an operational diagram of a CAN system.

CAN is based on the broadcast communication mechanism. This broadcast communication is achieved by means of a message-oriented transmission protocol. Thus, it only defines messages, not stations or station addresses. These messages are identified by use of a message identifier. The message identifier has to be unique within the whole network, and the protocol defines not only the content, but also the priority of the message. The priority definition becomes important when several stations compete for bus access.

A high degree of system and configuration flexibility is achieved as a result of the content-oriented addressing scheme. It is easy to add stations to an existing CAN network without making any hardware or software modifications to the existing stations, as long as the new stations are purely receivers. This flexibility allows modular electronics to come into play, and it also permits multiple receptions and the synchronization of distributed processes. Data needed by several stations can be transmitted via the network in such a way that it is unnecessary for each station to have to know who the producer of the data is. Therefore, the servicing and upgrading of a network are relatively easy because the data transmission is not based on the availability of specific types of stations.

In real-time processing, the urgency to exchange messages over the network can differ greatly: A rapidly changing dimension (such as the engine load) has to be transmitted more frequently, and therefore with fewer delays, than do other dimensions (such as engine temperature).

The priority at which a message is transmitted, compared to another message, is specified by the identifier of each message. The priorities are laid down during system design in the form of corresponding binary values and cannot be changed dynamically. The identifier with the lowest binary number has the highest priority.

Bus access conflicts are resolved by bitwise arbitration of the identifiers involved by each station observing the bus level, bit for bit. This happens in accordance with the “wired and” mechanism, by which the dominant state overwrites the recessive state. The competition for bus allocation is lost by all stations (nodes) that have recessive transmission and dominant observation. All those “losers” automatically become receivers of the message with the highest priority and do not reattempt transmission until the bus is available again.

Transmission requests are handled by the messages’ order of importance to the system as a whole. This system proves especially advantageous in overload situations. Because bus access is prioritized on the basis of the messages, it is possible to guarantee low individual latency times in real-time systems.

The CAN protocol supports two message frame formats; the only essential difference between the two is the length of the identifier. The CAN standard frame, also known as CAN 2.0 A, supports FIGURE 1.2 The operational diagram of a CAN system. (This section is reprinted by the permission of the CIA Web site http:www.can-cia.de/can/protocol/)

Local Intelligence CAN Station 1 (Consumer) CAN Station 3 (Consumer) CAN Station 4 (Consumer) CAN Station 2 (Producer) Frame Filter Local Intelligence Frame Filter Local Intelligence Frame Filter Local Intelligence Frame Filter


8 The Windows Serial Port Programming Handbook

a length of 11 bits for the identifier, and the CAN extended frame (also known as CAN 2.0 B) supports a length of 29 bits for the identifier. CAN Standard Frame

A message in the CAN standard-frame format begins with the start bit called the start of frame (SOF). This is followed by the Arbitration field, which consists of the identifier and the remote transmission request (RTR) bit used to distinguish between the data frame and the data request frame, also called the remote frame. The subsequent Control field contains the identifier extension (IDE) bit used to distinguish between the CAN standard frame and the CAN extended frame. The field also includes the data length code (DLC) used to indicate the number of following data bytes in the Data field. If the message is used as a remote frame, the DLC contains the number of requested data bytes.

The Data field that follows is able to hold up to 8 bytes of data. The integrity of the frame is guaranteed by the following cyclic redundancy check (CRC) sum. The Acknowledge (ACK) field compromises the ACK slot and the ACK delimiter. The bit in the ACK slot is sent as a recessive bit and is overwritten as a dominant bit by those receivers, which have at this time received the data correctly. Correct messages are acknowledged by the receivers regardless of the result of the acceptance test. The end of the message is indicated by the end of frame (EOF). The intermission frame space (IFS) is the minimum number of bits separating consecutive messages. If there is no subsequent bus access by any station, the bus remains idle. CAN Extended Frame

A message in the CAN extended-frame format is likely the same as a message in CAN standard-frame format. The difference is the length of the identifier used. The identifier is made up of the existing 11-bit identifier (the base identifier) and an 18-bit extension (the identifier extension). The distinction between the CAN standard-frame format and the CAN extended-frame format is made by means of the IDE bit, which is transmitted as dominant if the frame is in CAN standard-frame format and is transmitted as recessive if the frame is in CAN extended-frame format. As the two formats have to coexist on one bus, the message with a higher priority on the bus is identified, in case of a bus access collision, with different formats and the same identifier or base identifier. A message in CAN standard-frame format always takes priority over a message in extended-frame format.

CAN controllers that support the messages in CAN extended-frame format are also able to send and receive messages in CAN standard-frame format. When CAN controllers covering only the CAN standard-frame format are used in one network, then only messages in CAN standard frame can be transmitted over the entire network. Messages in CAN extended-frame format will be misunderstood. However, some CAN controllers are available (such as version 2.0 B passive, for example) that support only CAN standard-frame format but that recognize messages in CAN extended-frame format and then ignore them. Detecting and Signaling Errors

Unlike other bus systems, the CAN protocol does not use ACK messages, but instead signals any errors immediately as they occur. For error detection, the CAN protocol implements three mech-anisms at the message level:

CRC: The CRC safeguards information in the frame by adding redundant check bits at the transmission end. At the receiving end, these bits are recomputed and tested against the received bits. If they do not agree, a CRC error has occurred.


The Fundamentals of Serial Port Communications 9

Frame check: This mechanism verifies the structure of the transmitted frame by checking the bit fields against the fixed format and the frame size. Errors detected by frame checks are designated as format errors.

ACK errors: As previously mentioned, received frames are acknowledged by all receiv-ers through a positive ACK. If no ACK is received by the transmitter of the message, an ACK error is indicated.

The CAN protocol also implements two mechanisms for error detection at the bit level: • Monitoring: The capability of the transmitter to detect errors is based on the monitoring

of the bus signals. Each station that transmits also observes the bus level and thus detects differences between each bit sent and the corresponding bit received. This permits the reliable detection of global errors, as well as errors local to the transmitter.

Bit stuffing: The coding of the individual bits is tested at bit level. The bit representation used by CAN is nonreturn to zero (NRZ) coding, which guarantees maximum efficiency in bit coding. The synchronization edges are generated by means of bit stuffing. This means that after five consecutive equal bits, the transmitter inserts into the bit stream a stuff bit with the complementary value, which is removed by the receivers.

If one or more errors are discovered by at least one station using the previous mechanisms, the current transmission is aborted by means of an error flag. This prevents other stations from accepting the message and thus ensures the consistency of data throughout the network. After the transmission of an erroneous message that has been aborted, the sender automatically reattempts transmission (automatic retransmission). There may again be competition for bus allocation.

However effective and efficient the method described may be, in the event of a defective station, all messages (including the correct ones) might be aborted. If no measures for self-monitoring are taken, the bus system will be blocked by this defective station. The CAN protocol therefore provides a mechanism for distinguishing sporadic errors from permanent errors and for local failures at the station. This is done by a statistical assessment of station error situations, with the aim of recognizing a station’s own defects and possibly entering an operation mode that would not negatively affect the rest of the CAN network. This process may go as far as the station switching itself off to preventing messages erroneously from being recognized as incorrect.


Firewire originally was developed by Apple Computer, Inc., as a high-speed serial bus. It was a kind of advanced digital broadcast (ADB) on lots of steroids. While it was being developed, many thought that it was actually too fast, and that some lower-speed interconnect devices, such as USB, would be cheaper to implement. After that, Firewire languished. Suddenly, in 1995, a tiny connector showed up on the first digital video (DV) camcorders shipped by Sony Corporation. DV was the killer application for Firewire. In late 1995, Firewire was accepted as a standard by the Institute of Electrical and Electronics Engineers (IEEE), henceforth called IEEE-1394.

The emergence of DV and multimedia applications have brought with them the need to move large amounts of data quickly between peripherals and PCs. As audio–video products migrate to digital technology, consumers and professionals alike stand to benefit from a simple high-speed connection that will make this transmission more efficient. Enter 1394, the digital cable. The IEEE-1394 serial bus is the industry-standard implementation of Apple Computer’s IEEE-1394 digital I/O system. It is a versatile, high-speed, low-cost method for interconnecting a variety of personal computer peripherals and consumer electronics devices. Developed by the industry’s leading tech-nology companies, the specification was accepted as an industry standard by the IEEE Standards


10 The Windows Serial Port Programming Handbook

Board on December 12, 1995, with succeeding revisions since then. The 1394 standard offers several advantages over other technologies. These benefits include the following:

• Guaranteed delivery of multiple data streams through isochronous data transport • The capability to connect up to 63 devices without the need for additional hardware,

such as hubs

• A flexible, six-wire cable

• Complete plug and play operation, including the hot-swapping of live devices

• Acceptance by over 40 leading manufacturers in the computer and electronics consumer industries

Figure 1.3 shows the physical structure of a typical Firewire port connector. The Firewire has two individually shielded pairs for data and two extra wires for power.

As shown in the figure, the standard Firewire cable actually consists of six wires. Data is sent via two separately shielded twisted-pair transmission lines. The two twisted pairs are crossed in each cable assembly to create a transmit–receive connection. Two more wires carry power (8 to 40V, 1.5A maximum) to remote devices. Currently, these power lines are rarely used. The wires terminate in Gameboy-style plugs, also shown in Figure 1.3.

Sony uses four-conductor cable for making connections to DV camcorders and DVCRs. Similar to the setup mentioned previously but without the power wires, these cables terminate in smaller, four-prong connectors. To connect a Sony DV camcorder or DVCR with a standard IEEE-1394 Firewire device or interface card, you need an adapter cable, with four prongs on one side and six on the other. It simply connects the data lines while omitting the power connection.

According to the standard, the IEEE-1394 “wire” is good for 400 Mbps over 4.5 meters. The standard cable uses 28 American wire gauge (AWG) signal pairs with 40 twists/meter. The power pair in the standard cable is 22 AWG.

Longer cable runs can be achieved by using thicker cable or by lowering the bit rate. DV users, keep in mind that the signaling rate of the Sony DV camcorders is only 100 Mbps. Can it use longer cables? The answer is Yes. Although such a connection lies outside of the product specifi-cations, several people have reported successful 100 Mbps transmissions over more than 20 meters using standard cable. Reports have also been made of thicker cables being used to span lengths of 30 meters or more at 100 Mbps.

If you are the adventurous type, you can try using unshielded twisted-pair (UTP) cable. Don’t notify the Federal Communications Commission (FCC) before doing this, and if your neighbors complain about strange stuff on their TV sets, stop the experiment. We have even heard reports about someone who was running 100 Mbps 1394 over 50 meters of Cat-5 UTP. According to lore, he ran isochronous video for several days without a single frame dropped due to errors.

FIGURE 1.3 The physical structure of a typical Firewire port connector. Power

Pair 1

Pair 2 Cable


The Fundamentals of Serial Port Communications 11


As previously mentioned, independent channels are established for two-way (full-duplex) commu-nications. RS-232 signals are represented by voltage levels with respect to a common system (power/logic) ground. How can a single wire be used to transmit a sequence of data bit by bit between two devices effectively and without errors? This is a key concern: making sure our data communication is successful and reliable. To answer this question, let us now examine some terminologies applied in the serial data communications arena. Because of the similarity of the serial data definitions in RS-232, RS-422, and RS-485, we offer only an overview of the RS-232 serial data communication protocol, including both hardware and software protocols.


Most serial data communications use ASCII code as the basic data unit for communicating among devices. ASCII code was defined by the American National Standards Institute (ANSI), and its full name is American Standard Code for Information Interchange. Basically, all information can be expressed in ASCII by a sequence or combination of 26 English characters, as well as some special characters, and each character can be expressed and transmitted by an associated 7-bit binary code. This representation method is the ASCII method. In serial communication programming, the ASCII code can be expressed in different formats, such as decimal or hexadecimal, and different subrou-tines can be utilized to translate between the different formats. Appendix A shows a typical ASCII code table that contains the popular characters used in normal data communications.

One point to remember is that in most computer data communications, each data unit is composed of 1 byte, or 8 bits, of binary code. For example, in Figure 1.1, a binary sequence, 01100101, which is equivalent to a decimal of 101 or a hexadecimal of 65h in the standard ASCII table, is an 8-bit binary code. Only 7 bits are occupied when this code is represented as an ASCII code: 1100101. The most significant bit (MSB) is not used. It can be concluded that the maximum binary code that can be expressed in ASCII code is 1111111, which is equivalent to a decimal of 127.

However, in the real world of serial data communications, instead of using 7 bits, a data unit or an ASCII character is actually represented by a byte, or 8 bits, of binary code traveling between two devices. The MSB bit in an 8-bit binary code is often used as a parity bit for error checking, thus making ASCII, in practice, an 8-bit code.

The ASCII table in Appendix A shows the binary sequence represented in Figure 1.1, 01100101, is equivalent to the ASCII character ‘A’. By using the ASCII code, the data can be successfully expressed and transmitted through a single wire, bit by bit, byte by byte, character by character, from one device to another.

A potential problem exists in using ASCII code during data communications. The incompati-bility of different spoken languages can be a challenge; for example, some countries use non-English languages. Special care must be taken to handle such incompatibilities.

Another issue is that most computers employ some human-readable characters as their data communication medium. One exception is IBM, which has developed its own character set, the Extended Binary Coded Decimal Interchange Code (EBCDIC); however, this character set is not compatible with ASCII code.

A solution to these potential problems has been the development of a new character set that extends the ASCII code to meet the requirements of different languages used for data communi-cations in different countries. IBM, Apple, and a number of UNIX vendors have developed a Unicode standard to improve compatibility; it includes 16-bit encoding that encompasses all existing national character code standards. The International Organization for Standardization (ISO) adopted this Unicode standard as a superset of ISO 10646 in June 1992, but the 16-bit encoding set will not be adopted worldwide for quite some time.


12 The Windows Serial Port Programming Handbook


For RS-232 serial port communication, if the full EIA232 standard is implemented as defined, the equipment at the far end of the connection is called the data terminal equipment (DTE). A DTE device is usually a computer or terminal. The interface connector can be either a DB-9 or DB-25 male connector, and it uses 6 of 9 or 22 of the 25 available pins for signals or grounding. Equipment at the near end of the connection (the telephone line or other device interface) is called the data communications equipment (DCE); it has a male DB-9 or DB-25 connector and uses the same 6 or 22 available pins for signals and grounding. The cable used for linking DTE and DCE devices is a parallel straight-through cable with no crossovers or self-connects in the connector hoods. Here the term crossover means that a null modem cable is used to connect two devices (in most cases, two computers). A more detailed discussion of null modem cabling will be given in Section 1.5.2. If all devices followed this standard exactly, all cables would be identical, and there would be no chance of an incorrectly wired cable being used. Figure 1.4 shows the orientation and connector types for DTE and DCE devices.

Throughout this book, DTE will always refer to a computer, and DCE will refer to equipment or a device interfaced to a computer.


Recall from Figure 1.1 that serial data communication uses three wires to transmit a sequence of binary bits, one by one, between two devices. This exact transmission has a certain requirement for data format and protocol. The actual data transmission between a DTE and a DCE utilizes two wires, or two RS-232 communication lines, a received data (RD) line and a transmitted data (TD) line, respectively. The TD line handles data to be transmitted from the DTE (PC computer) to the DCE, and the RD line works in reverse mode, processing data to be sent from the DCE to the DTE. The third line in Figure 1.1 is the common reference (or ground) line between the DTE and the DCE.

In the real world, serial data transmissions between the DTE and DCE can be divided into two categories: synchronous and asynchronous transmissions. A synchronous transmission takes place between the DTE and the DCE when both devices have the same transmission rate or speed. On the other hand, when the DTE has a different transmission rate than the DCE, an asynchronous transmission occurs. Wiring distances should be limited to 100 or 200 feet for asynchronous data and about 50 feet for synchronous data (and that may be pushing it in some cases). Synchronous data has a transmitting and receiving clock that limits the maximum distance that data can travel on a synchronous data line.

FIGURE 1.4 The connection between the DTE and the DCE. (This section is reprinted by the permission of the author, Christopher E. Strangio, CAMI Research Inc.)

DTE Data Terminal Equipment DCE Data Communications Equipment Male DB9 or DB25 Male DB9 or DB25 Interface Cable Telephone Line Modem or other Device Computer


Related documents

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

Key words: Ahtna Athabascans, Community Subsistence Harvest, subsistence hunting, GMU 13 moose, Alaska Board o f Game, Copper River Basin, natural resource management,

12 Data Science Master Entrepreneur- ship Data Science Master Engineering entrepreneurship society engineering. Eindhoven University of Technology

Тип ресурсу Призначення Алфавітний підхід Статистичний підхід Семантичний підхід Файлова система Персональний ресурс Автоматично Не застосовується

As consequence, this paper contains a study on the effect of the rotor bar number on the torque (average and quality) of five-phase induction machines under different supply

As inter-speaker variability among these the two groups was minimal, ranging from 0% to 2% of lack of concord in the 21-40 group and from 41% to 46% in the 71+ generation, we

All stationary perfect equilibria of the intertemporal game approach (as slight stochastic perturbations as in Nash (1953) tend to zero) the same division of surplus as the static

All the figures and tables should be labeled (Times New Roman 11) and included in list of figures and list of tables respectively.