HOME > > ELECTRONICS MAIN PAGE > > ELECTRONICS PROJECTS CONTENTS
Delicious Bookmark this on Delicious    StumbleUpon.comRecommend at StumbleUpon

Using a PC's serial port



If you want to write a program in Delphi or Kylix which reads from or writes to a device using RS-232 (i.e. over the serial port, aka COM1), then the place for you is my Delphi tutorial on the subject.

This is a Hodge-Podge of things I "harvested" from the internet. I was looking... largely in vain!... for a simple answer to "How do I access the serial port in a Delphi program written by me, for Windows 95 and higher?" I will try to go through this again, and edit it down to something even more organized, more readable in due course. It is NOT typical of my other web-pages!! References to "I" in the following do not all refer to the editor of this page.

I have a much more polished page with information to help you use a parallel port.... My Parallel Port FAQ Answers

PLEASE NOTE: You CAN damage your computer if you make ill-advised connections to it. Any use you make of anything you find here must be AT YOUR OWN RISK

I've also published information and an offer about a small, hobbyist friendly circuit with relays and opto-isolators, which may be of interest. It is for protecting your PC.



Don't let the warning above worry you too much... I want to stress that there is a lot of fun to be had with electronics projects. Find yourself an 'antique' PC. If you can't rescue one from a dusty corner, you can buy one for almost nothing. You can use the same monitor as you use on your main machine. If you wreck the antique, it hasn't cost you much! (I got one, with monitor, off a sidewalk once!)


Before we get to the serial port stuff, two ads from our sponsors...

1) If you are going to use this page, you are probably not a computing novice. Ever set up a web server? It isn't hard! If you have an always- on broadband connection, FarWatch may be of interest. I have written pages for you explaining how to use an old Win98 box (or better) to give yourself a way to monitor the premises the old Win98 box is at from anywhere on the internet. Nothing to buy! And if you connect something to that PC via it's serial port, you can "see" the data from the serial port from afar, too.

2) If you would be willing to help bring this information about the serial port to a wider readership, please check out my plea for translators?


One of the best "answers" to "how can I add serial comms to my program??" I found was at....

Robert Clemenzi's helpful page

The following is taken from there, with alterations. I think the author was working with Delphi 5; Other sources suggested that a similar approach will work with Delphi 2. For Delphi 1, you'd take a different approach.

Subsequently, a Google search on "commtimeouts delphi" turned up Peter Johnson's useful page. He has written a number of articles, components and applications. Search Google for "peter johnson" delphi, and you'll find all sorts of good things. Among other things, his page shows how to programmatically set baud rate, etc, too.

Writing a Port

The following code from Borland's FAQ 16400 shows how to write to the comm port as a file. The code in the FAQ also verifies a valid handle before writing to it. Warning: There may be an error in the FAQ - it may be that NumberWritten must be dword not LongInt
var NumberWritten:dword;
     PhoneNumber, CommPort:string;
     hCommFile:THandle;
- - - -
PhoneNumber := 'ATDT 1-555-555-1212' + #13 + #10;
CommPort := 'COM2';
hCommFile := CreateFile(PChar(CommPort),
                          GENERIC_WRITE,
                          0,
                          nil,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL,
                          0);
WriteFile(hCommFile,
            PChar(PhoneNumber)^,
            Length(PhoneNumber),
            NumberWritten,
            nil)
From the same source.....

Reading a Port

Well, reading the port is almost trivial ... if you know the trick. You must configure the TimeOutBuffer. I don't know what good values should be, so I used 300.
var
//hCommFile : THandle;   // Global variable set elsewhere
TimeoutBuffer: PCOMMTIMEOUTS;
begin
  GetMem(TimeoutBuffer, sizeof(COMMTIMEOUTS));
  GetCommTimeouts (hCommFile, TimeoutBuffer^);
  TimeoutBuffer.ReadIntervalTimeout        := 300;
  TimeoutBuffer.ReadTotalTimeoutMultiplier := 300;
  TimeoutBuffer.ReadTotalTimeoutConstant   := 300;
  SetCommTimeouts (hCommFile, TimeoutBuffer^);

  FreeMem(TimeoutBuffer, sizeof(COMMTIMEOUTS));
Having done that, ReadFile waits until I scan a barcode. Eventually, I will use ReadFileEx because it will call a routine when a barcode is scanned. Once the port is open and configured, here are 2 routines that will read the port. For test purposes, each was connected to its own button. Uh, both routines work when run from the IDE ... the second refuses to work if you double click on the exe file. I have no idea why.
procedure TForm1.Read_ComPort_UIButtonClick(Sender:TObject);
var
 InputBuffer : string;
 NumberOfBytesRead : dword;
 Buffer : array[0..255] of char;
 i: Integer;

begin
  if hCommFile=INVALID_HANDLE_VALUE then exit;

  for i := 0 to 255 do    // This is just for test
       Buffer[I] := #42;  // It demonstrates why InputBuffer
                                 // is built inside a "for" loop

  if ReadFile(hCommFile, Buffer, sizeof(Buffer),
              NumberOfBytesRead, nil) = false then
    begin
     ShowMessage('Unable to read from comport');
     exit;
    end;
  InputBuffer := '';
  for i := 0 to NumberOfBytesRead - 1 do
      InputBuffer := InputBuffer + Buffer[i];

  Test_UIEdit.Text := InputBuffer;
end;
This next routine works from the IDE, but not if you run the app by double clicking the exe file.
procedure TForm1.ReadToString_UIButtonClick(Sender:TObject);
var
 InputBuffer : string;
 NumberOfBytesRead : dword;
 MaxBytesToRead : dword;
begin
  if hCommFile=INVALID_HANDLE_VALUE then  exit;

  InputBuffer := '11111111111111'; // the string must be longer than
                                            // the number of bytes you expect to read
  InputBuffer :='';      // This fails, the string must have a length

  MaxBytesToRead := 14;  // could use sizeof(InputBuffer) instead

  if ReadFile(hCommFile, PChar(InputBuffer)^,
              MaxBytesToRead,
              NumberOfBytesRead, nil) = false then
    begin
      ShowMessage('Unable to read from comport');
      exit;
    end;
  InputBuffer := copy(InputBuffer, 1,
NumberOfBytesRead);
  Test_UIEdit.Text := InputBuffer;
end;
When CreateFile, ReadFile, and WriteFile are used, Delphi does not use MSComm. Instead, it uses the following Kernel32 commands (found using Depends.exe)

SetCommTimeouts, SetCommConfig
GetCommTimeouts, GetCommConfig
CommConfigDialogA
If you try to search the Delphi 5 help for ReadFile, there are no hits. This is because ReadFile is a Windows API command ... not a Delphi command. Instead, click on it in your code and press F1.

===
Additional information on parallel port, serial, USB (Some great pages from Jan Axelson.)

===
TCommPort
On the Internet, there are several TCommPort type components (see the references below or just search for them).

I have been successful using TCommPort...
http://users.pandora.be/dirk.claessens2/downloads/tcomport.zip ... by Dirk Claessens...
http://users.pandora.be/dirk.claessens2/
(freeware with full source code).

I strongly suggest using someone else's component rather than trying to build one yourself. Why? Because they have already been tested on numerous systems and various undocumented "features" have been taken into account.

(Here ends the quotes from http://www.cpcug.org/..../Delphi_SerialIO.htm), and here begins a quote from what was once on a Borland site, that subsequently re-directed to http://dn.codegear.com/article/16400 which at 1/2010 was unavailable. It said "article withdrawn... and had comments from people interested in it, but I'm done chasing what was once a good company. Hope you can find that if other sources don't give you what you're looking for!


How can I dial out through the modem under Win32? - by Borland Developer Support Staff

Question and Answer Database

FAQ1400D.txt How can I dial out through the modem under Win32?
Category :Windows API
Platform :All
Product :All 32 bit

Question:
How can I dial out through the modem under Win32?

Answer:
You can use the Windows API function CreateFile() to get a handle to the com port, and use standard file I/O to communicate with the given port.

Example:
var
  hCommFile : THandle;

procedure TForm1.Button1Click(Sender: TObject);
var
  PhoneNumber : string;
  CommPort : string;
  NumberWritten : LongInt;
  {N.B.: I saw the following in a newsgroup post:
  Warning: There is an error in the FAQ - NumberWritten must be
  dword not LongInt}
begin
  PhoneNumber := 'ATDT 1-555-555-1212' + #13 + #10;
  CommPort := 'COM2';
 {Open the comm port}
  hCommFile := CreateFile(PChar(CommPort),
                          GENERIC_WRITE,
                          0,
                          nil,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL,
                          0);
  if hCommFile=INVALID_HANDLE_VALUE then
  begin
    ShowMessage('Unable to open '+ CommPort);
    exit;
  end;

 {Dial the phone}
  NumberWritten:=0;
  if WriteFile(hCommFile,
               PChar(PhoneNumber)^,
               Length(PhoneNumber),
               NumberWritten,
              nil) = false then begin
    ShowMessage('Unable to write to ' + CommPort);
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
 {Close the port}
  CloseHandle(hCommFile);
end;
Article ID: 16400 Publish Date: July 16, 1998 Last Modified: September 01, 1999


There were a whole bunch of promising files at Programmers Heaven, including....
========
http://www.programmersheaven.com/zone2/cat55/5764.htm
CATE - Communication component
A free, Win95 serial comms component. For Delphi. 20k

====
http://www.programmersheaven.com/zone2/cat55/2884.htm
Port95
Another free, probably Win95 serial comms component.
For Delphi. 1k zip.

===
http://www.programmersheaven.com/zone2/cat55/409.htm
TSerial for Delphi 2
This is a no-frills serial component that saves you
having to tangle with the Windows Comms
API functions to handle a serial port. Uses overlapped
I/O for full Windows NT
functionality. Only basic serial comms are provided -
no terminals, protocols etc.

The above is another free(?), probably Win95 serial comms
component.  26k zip... 5 star rated by Programmer's Heaven.

When I checked with Groups.google.com, there was praise for
Rick Crowther's TSerial, said to be exactly what someone wanted,
"not free, but at GBP10 last time I bought it, you can hardly grumble."....

That discussion continued.....

TSerial is great, but it's not free and so I searched
the web again and again and found AsyncFree which is free
and offers the same if not better functionality.

I searched for AsyncFree, and came up with....

http://www.synchrondata.com/pheaven2/www/area48.htm...
a list of Good Stuff from AsyncFree's source. For AsyncFree...

http://delphree.clexpert.com/pages/projects/asyncfree/default.htm...

Described itself as follows....

Serial communication in Delphi and related components.
The goal is to offer quality and open solution of
serial communication in Delphi including
closely related components e.g. terminal window, TAPI,
etc. My idea is to split the problem
to several parts, create independent components for
each part and thus limit the usage of
extensive and complicated code for simple
applications: Suggested project parts:

Basic serial communication (input and output buffer, line events)
Data and event dispatcher (user timers, input data-driven events...)
Opened for linking to other communication enabling components,
e.g. WinSocket, DCOM,...
Visual components (terminal window,...) compatible
with dispatcher by means of a link (like TDataLink with databases).
Events will be both synchronized with VCL and without this
synchronization. technology enabling remote connection of serial lines
through the network (without the need for cabling from one point
to individual computers). I have something prepared, but the code should be rewritten as it is rather closed and not divided according
to the above description.

Current version: 1.03
Supported Delphi versions: 3,4,5

Download: AsyncFree.ZIP, 105kB, 17.10.1999

===
http://www.programmersheaven.com/zone2/cat55/14284.htm
WINDOWS STANDARD SERIAL COMM LIB for Delphi.
Win16 & Win32 DLLs. Version 2.1, . Serial comm library
based on the Windows API. Includes

25 functions plus modem control, XMODEM & YMODEM, and
5 example programs. Requires Delphi compiler.
By MarshallSoft Computing, Inc.


File name: WINDOWS STANDARD SERIAL COMM LIB for
Delphi.
Product homepage: Unknown
Order page: Unknown
Language: Delphi 2
Platform: Windows 95
Release Date: Unknown
File type: Unknown
Size: 68 KBytes
Price/ fee (US$): 0.00$
Number of downloads: 4944

=======
http://www.programmersheaven.com/zone2/cat55/14573.htm

TPort Component Version 1.5 (not rated)
This component will read and write from the computer's
I/O ports.

File name: TPort Component Version 1.5
Product homepage: Unknown
Order page: Unknown
Language: Delphi 2
Platform: Windows 95
Release Date: Unknown
File type: Unknown
Size: 8 KBytes
Price/ fee (US$): 0.00$
Number of downloads: 11056

===
The following looked like it might be what I wanted.....
http://www.programmersheaven.com/zone2/cat55/18804.htm
SerialNG V2.0.15
Full featured Serial Communication Component for
Delphi 2.0.15 Fully Serial Communication
with Delphi and Windows 95/98/NT/Me/2000. This tool is
a fully redesign of my former Tool for Windows 98/98.
It enables an Application to communicate through an serial port.
It uses only WinAPI and Delphi functions, so no other third
party software is needed. It comes with several Demos
and Source Codes.


File name: SerialNG V2.0.15
Product homepage: Product homepage
Order page: Unknown
Language: Delphi 3-4-5-6-7
Platform: Windows 2000-95-98-ME-NT-XP
Release Date: 11/13/2002
File type: Public Domain
Size: 48 KBytes
Price/ fee (US$): 0.00$
Number of downloads: 2514

===
http://www.programmersheaven.com/zone2/cat55/14247.htm
Comm32
Is a simple Communications VC for Borland Delphi 2.0
which demonstrates the Win32 Communications functions and the
new Delphi 'TThread' class. It is implemented using two threads:
one for reading from, and one for writing to a Comm Port.


File name: Comm32
Product homepage: Unknown
Order page: Unknown
Language: Delphi 3 (Yes: That conflicts with description above)
Platform: Windows 95
Release Date: Unknown
File type: Unknown
Size: 13 KBytes
Price/ fee (US$): 0.00$
Number of downloads: 4687

========
http://www.programmersheaven.com/zone2/cat55/22553.htm
QCCom32 1.4.0
A Delphi 5 component for doing simple serial (RS232)
I/O in Windows 95/98/NT or 2000. Has
built-in dialogs for choosing a port, displaying error
messages, etc... Includes full
source code, and a help file. It should work with
Delphi 3, 4 or 6, but I can't say for sure.

File name: QCCom32 1.4.0
Product homepage: Product homepage
Order page: Unknown
Language: Delphi 5
Platform: Windows 2000-95-98-ME-NT-XP
Release Date: 7/1/2002
File type: Freeware
Size: 14 KBytes
Price/ fee (US$): 0.00$
Number of downloads: 4109

========
(Also at Programmer's Heaven, I think... Not just serial port stuff, but
telephony support, too......)
KDTele Tools 3.0 (ActiveX/VCL)
KDTele is a collection of controls that provide to
your application advanced telephony
features, such as: -Make and answer phone calls
-Detect tone and pulse digit from the phone
line -Capture Caller ID -Play and record on the phone
line or sound card -Silence detection
when recording -Send and ...
Size: 4865 Kb  Downloads: 2801 Updated: 2002-11-5
Rating: (Not Rated) $77

Other possibly useful links, probably at least checked by me in at least a cursory way...
things that looked like they might be worth further investigation.....

Once at...http://sunsite.icm.edu.pl/archive/delphi/ftp/freeware/simpterm.zip: (4,082 bytes) Simple terminal by David Powell from Borland... but link bad 5/07

=======

http://www.lvr.com/serport.htm Serial Port Central....
Many resources- serial port use within programs and otherwise.

========

Quotes from newsgroup discussions...

In Visual Basic, use the MSComm control included with the Professional and Enterprise editions. Visual Basic's Learning Edition doesn't include MSComm. But you can use the freeware XMComm ActiveX control... (Once at http://ourworld.compuserve.com/homepages/richard_grier/xmcomm.htm) ...which wraps the MSComm32.ocx. From Richard Grier's Hard & Software.... but link bad 5/07

========

EasyIO. An Active X control for very basic serial I/O under Windows 95/NT. From Stephen Payne.... Link WAS...http://members.aol.com/easyio/easyio.html (Seems dead 1/2010)

Quotes from EasyIO site...

I/O ActiveX Control

This I/O ActiveX control allows easy reading and
writing to and from both parallel and
serial ports under Windows 95/98 and NT4.0. Use it as
a Win32 communications library.
I/O access under Windows 95/98 and Windows NT4.0 with
an easy, quick to learn interface.

I THINK the following is quotes relating to the EasyIO product.... if not, if you can find where they came from (using Google), I'd welcome the information!



There are three functions for binary data transfers.
1) WriteData(Data, Length); Writes a data buffer of
Length characters.
2) ReadData(Length); Reads binary data and returns it
in a string.
3) BytesRead(); Returns the number of bytes read by
the ReadData() function.

 ---
There is a function to check various things....
SerialStatus (Property) R

Remarks
This reflects the current status of the serial port as
follows:
Example:
If (IOStatus And SERIAL_RXEMPTY) Then
NewText = NewText + "RX Buffer Empty, "
else
NewText = NewText + "RX Buffer Not Empty, "
End If

Some of the things that can be checked. See web for details not given here.
SERIAL_RXOVER
SERIAL_OVERRUN
SERIAL_RXPARITY
SERIAL_FRAME
SERIAL_BREAK
SERIAL_TXFULL The application tried to transmit a character, but the output buffer was full.
SERIAL_TXEMPTY The transmit buffer is empty.
SERIAL_RXEMPTY The receive buffer is empty.
SERIAL_CTS_TXHOLD
SERIAL_DSR_TXHOLD
SERIAL_RLSD_TXHOLD
SERIAL_XOFF_TXHOLD
SERIAL_CTS_ON
SERIAL_DSR_ON
SERIAL_RING_ON
SERIAL_RLSD_ON


NumCharsInQue (Property) R


Remarks
This reflects the number of bytes/ characters in the
input buffer (waiting to be read).

---

Dim Result as Integer
Dim DataStr as String
Dim NumBytes as Integer

Result = IO1.WriteData("String1" + Chr(00) + "String2"
+ Chr(00) + "String3" + Chr(00) +

Chr(00)) 'Sends 3 null terminated strings to the port,
with the total data being double null terminated.

DataStr = IO1.ReadData(30) 'Reads data from a port.

NumBytes = IO1.BytesRead() 'returns number of bytes
read.

See WriteData, ReadData, and BytesRead in I/O OCX Control Functions

=========

Recommended at groups.google:

"Unless you like digging in the dark or when you don't want to spend too much time on some buggy communication use the Asych Pro toolbox of turbopower software at : http://www.turbopower.com"

(1/2010 update: Sadly, TurboPower closed... but first they kindly released their software into the open source world! There is a sourceforge page for Async Pro! To quote from that: "Async Professional is a comprehensive communications toolkit for Embarcadero Delphi, C++Builder, & ActiveX environments. It provides direct access to serial ports, TAPI, and the Microsoft Speech API. It supports faxing, terminal emulation, VOIP, & more." From the same source: TurboPower Async Pro CLX: "Async Professional CLX is a comprehensive communications toolkit for Borland Kylix. It provides direct access to serial ports, and supports terminal emulation, file transfer protocols, & more.". At least at 1/2010 there was still a TurboPower.com page, listing what the former company has given to open source.)

Unfortunately, when I went to the TurboPower site, I found a notice that they had discontinued retail business.... but... to quote from their site....


"TurboPower announces sweeping open source initiative

Colorado Springs: TurboPower Software Company today
announces their immediate withdrawal
from the retail component and developer tools market.
As part of the move, TurboPower
announces its intention to release their award winning
component libraries as open source
to the maximum extent possible.

We've been a big part of the developer community for
nearly 18 years, said TurboPower
President Gary Frerking. Open sourcing our products
seems like an appropriate gesture of
appreciation to the community that supported us so
well over the years. We sincerely hope
these products take on a life of their own and
continue to prosper for many years to come.

TurboPower's component libraries cover a wide spectrum
of development needs including
compression, serial communication, faxing, Internet
communication, scheduling, data entry,
encryption, and XML manipulation. There are nearly
twenty commercial-quality libraries
being considered for release, containing hundreds of
components and thousands of classes
and routines | over one million lines of source code
in all!

The process of preparing the libraries for release to
open source is already underway, and
the current goal is to have the libraries released to
the maximum extent possible by the
end of January (2003?). The resulting open source projects
will be hosted on SourceForge." (end quote from TurboPower page)

However, at 16 Apr 03, I didn't find AsyncPro or TurboPower at SourceForge... :-(

===

http://www.arcelect.com/rs232.htm has lots of good stuff on low level electronics, cables, connectors of RS-232

http://mc-computing.com/Languages/SerialIO.htm Lots of good links

* * * *========
(Mentioned on a Delphi directory of serial port stuff):

LOOKS REALLY GOOD!!! BUT... SEE TEXT...

TCommPortDriver. Freeware serial-communications component for Delphi. Includes source code that shows how to use Windows API calls to access serial ports. 16- and 32-bit versions available. From Marco Cocco. It used to be available from the Delphi Download Page., http://sdiclub.tms.ru/files_table.phtml?ipath=ACE, and looked pretty good! Seems to have been used by numerous people. But, of course, I hadn't downlaoded it myself, and the link above is dead 1/2010. Anyone know of a source?? TCommPortDriver is a component for Borland Delphi 2 that lets you handle COM ports (com1-com16) and all standard communication settings (baud rate, data bits, stop bits, parity, hardware and software flow control). Supports sending data in binary blocks or text strings. Supports asynchronous and synchronous data RX.

Freeware, 55k

========

Dirk's TComPort (Link seems out of date 1/2010):

http://users.pandora.be/dirk.claessens2/downloads/tcomport.zip

===
In a newsgroup, I saw: "the TDLPort IO 'wrapper' can be installed as a Delphi component. This allows IO under Win95/98 and (using a different file) Win NT. I know the latter normally blocks attempts to Write to/Read from specific addresses but the DLL (legally) get around the problem. I'm hoping that the Win95/98 version will do the same rather than just re-duplicate inpout32. It comes with a nice manual and is FREE!

Even thought there was a lysdexic error in the above, Google found for me this, which leads to....
Name: TDLPortIO 1.3 Date: 12/7/99
Environment: Delphi 3.0, Delphi 4.0, C++ Builder 3.0, C++ Builder 4.0 Download
Type: Freeware with Source Size: 851 Kb
Description:
TDLPortIO is a wrapper for the free DriverLINX kernel mode driver (included).
It allows full port IO under Windows 95/98/NT.
Comes with a C++ Builder and Delphi components,
ActiveX control (for Visual BASIC) and DLL version.
Compatible with the shareware package TVicPort.

This isn't really the time or the place to tell you about the following, but until I can write it up properly....

If you are into making your own electronic devices, you might be interested in the USB modules from www.ftdichip.com's products page. For about $20, you can buy a little unit that plugs into a Win98 or higher machine via USB. On the "outside world" side, it has 8 bi-directional digital input/ outputs, and a few handshake lines. The programming isn't trivial, but there is great material about accessing the device. Illustrations in Delphi are provided. You either install a TComPort component (a freeware one, with Delphi source code is available from Dejan Crnila and then access the 8 bits as if (to Win98) they were on a COM port, OR you use a DLL (supplied royalty free from FTDI). It is not exactly a parallel port via USB, but that's roughly the idea.


For Delphi 2 (and above) programmers: Tutorial: How To Access A Joystick.

Ad from page's editor: Yes.. I do enjoy compiling these things for you... hope they are helpful. However.. this doesn't pay my bills!!! If you find this stuff useful, (and you run an MS-DOS or Windows PC) please visit my freeware and shareware page, Sheepdog Software (tm), download something, and circulate it for me? At least (please) send an 'I liked the parallel port use page, and I'm from (country/ state)' email? (No... I don't do spam) Links on your page to this page would also be appreciated!
Click here to visit editor's freeware, shareware page.

Don't forget to check out the programs for controlling the state of the parallel port at my shareware site. There are two free programs there... one for toggling bits, the other for using the computer as a timer via the parallel port.


Here is how you can contact this page's editor.
Click here to go up to general page about electronics by editor of this page.
Click here to go up to general page about electronic projects by editor of this page.
Why does this page have a script that loads a tiny graphic? I have my web traffic monitored for me by eXTReMe tracker. They offer a free tracker. If you want to try it, check out eXTReMe's site. The Google panels and the search panel are also script based.

Valid HTML 4.01 Transitional Page tested for compliance with INDUSTRY (not MS-only) standards, using the free, publicly accessible validator at validator.w3.org


....... P a g e . . . E n d s .....