Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Serial communcation

Posted on 1999-06-23
9
Medium Priority
?
286 Views
Last Modified: 2010-04-06
I want to read and write into serial port,
I mean I need the equivalent of Pascal Port in Delphi.

I use Delphi 3, win98

Thanks
0
Comment
Question by:Motaz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
9 Comments
 
LVL 15

Expert Comment

by:simonet
ID: 1384201
Try the unit below:

/////////////////////////////////////////////////////////
unit CommExample;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs,
  StdCtrls, ExtCtrls;

type
   TCommDemoObject = class(TObject)

   private
   public
       commPortHandle:THandle;
       dcbInfo:Tdcb;
       errorFlag:Boolean;

       commPortError:DWORD;
       commPortStatus:TComStat;

       numberOfCharsActuallyWritten:DWORD;
//       numberOfCharsToRead:DWORD;
       numberOfCharsActuallyRead:DWORD;

       commPortInputBuffer:array[0..100] of Char;

       commPortOpen:Boolean;


       function    OpenCommPort(whichPort:String):Boolean;
       procedure   CloseCommPort;

       procedure   TransmitSingleChar(theChar:Char);
       procedure   TransmitString(theString:String);

       function    ReadCommPort:Integer;
   end;

implementation


function  TCommDemoObject.OpenCommPort(whichPort:String):Boolean;
begin
   // undo comm port if open
   if (commPortOpen) then
       CloseCommPort();
   // set flag state
   commPortOpen:=false;
   // open COMM port
   // use 'COM1','COM2','COM3', and 'COM4' to choose which port
   // to open
   commPortHandle:=CreateFile(PChar(whichPort),GENERIC_READ OR
GENERIC_WRITE,0,
       nil,OPEN_EXISTING,0,0);
   // bail on failure
   if (commPortHandle=INVALID_HANDLE_VALUE) then
       begin
           Result:=false;
           exit;
       end;
   // get comm port state
   errorFlag:=GetCommState(commPortHandle,dcbInfo);
   // bail on failure
   if (NOT(errorFlag)) then
       begin
           CloseHandle(commPortHandle);
           Result:=false;
           exit;
       end;
   // setup COMM port settings
   dcbInfo.BaudRate:=9600;
   dcbInfo.ByteSize:=8;
   dcbInfo.Parity:=NOPARITY;
   dcbInfo.StopBits:=ONESTOPBIT;
   // set COMM port state
   errorFlag:=SetCommState(commPortHandle,dcbInfo);
   // bail on failure
   if (NOT(errorFlag)) then
       begin
           CloseHandle(commPortHandle);
           Result:=false;
           exit;
       end;
   // show opened port
   ShowMessage('Opened Comm Port: ' + whichPort);
   // set flag
   commPortOpen:=true;
   // set flag
   Result:=true;
end;

procedure  TCommDemoObject.CloseCommPort;
begin
   // close comm port handle if not nil
   CloseHandle(commPortHandle);
end;

procedure  TCommDemoObject.TransmitSingleChar(theChar:Char);
label
   CHECKSTATUS;
begin
//   // you can use escape function to manually raise/lower DTR
//   EscapeCommFunction(commPortHandle,SETDTR);
//   EscapeCommFunction(commPortHandle,CLRDTR);
//   // you can use escape function to manaully raise/lower RTS
//   EscapeCommFunction(commPortHandle,SETRTS);
//   EscapeCommFunction(commPortHandle,CLRRTS);
   // transmit char
   TransmitCommChar(commPortHandle,theChar);
   // wait for char to exit 1 char buffer
CHECKSTATUS:
   ClearCommError(commPortHandle,commPortError,@commPortStatus);
   if ( fTxim in commPortStatus.Flags) then
       begin;
           // read status again
           goto CHECKSTATUS;
       end;
end;

procedure  TCommDemoObject.TransmitString(theString:String);
var
   charBuffer:array[0..100] of Char;
begin
   // convert string to chars
   StrPCopy(charBuffer,theString);
   // send string to comm port
   WriteFile(commPortHandle,charBuffer,Length(theString),
       numberOfCharsActuallyWritten,nil);
end;

function  TCommDemoObject.ReadCommPort:Integer;
begin
   // read comm port status
   ClearCommError(commPortHandle,commPortError,@commPortStatus);
   // check input buffer count
   if (commPortStatus.cbInQue>0) then
       ReadFile(commPortHandle,commPortInputBuffer,
           commPortStatus.cbInQue,numberOfCharsActuallyRead,nil);
   // set number of chars actually read
   Result:=numberOfCharsActuallyRead;
end;

end.


This is yet another example of serial communication, FhCom is a variable of type THandle in your
private part.

procedure TMyFantasticProgram.OpenSerialPort;
var ComNameBuffer:array[0..12]of char;
     FDCB:TDCB;
     timeouts:TCommTimeouts;
begin
FPortNumber=1  // for COM1
StrPCopy(ComNameBuffer,'COM'+intToStr(FPortNumber));
FhCom:=CreateFile(ComNameBuffer,
                   (GENERIC_READ or GENERIC_WRITE),       //dwDesiredAccess
                   0,    //dwShareMode
                    nil,  //lpSecurityAttributes (forget it)
                   OPEN_EXISTING,  //dwCreationDistribution
                   0,//dwFlagsAndAttributes
                   THandle(0));
//check for errors
if FHCom=INVALID_HANDLE_VALUE then CreateFileFailed;
//set buffer sizes
  if SetupComm(FHCom,FInputBufferSize,FOutputBufferSize)=false then
SetupCommFailed;
//read current setting
  if GetCommState(FHCom,Fdcb)=false then GetcommStateFailed;
//change current settings
  with Fdcb do
  begin
    BaudRate:=9600;
    ByteSize:=8;
    Parity:=NOPARITY;
    StopBits:=ONESTOPBIT;
    flags:=flags or 1; //always binary mode in win32
  end;
//write back changes
if SetCommState(FHCom,Fdcb)=false then windowsFailed;
//set timeouts example
  timeouts.ReadIntervalTimeout:=MAXDWORD;
  timeouts.ReadTotalTimeoutMultiplier:=0;
  timeouts.ReadTotalTimeoutConstant:=0;
  timeouts.WriteTotalTimeoutMultiplier:=0;
  timeouts.WriteTotalTimeoutConstant:=0;
  SetCommTimeouts(FHCom,timeouts);
//set DTR if you want
EscapeCommFunction(FHCom,SETDTR)
//set RTS if you want
EscapeCommFunction(FHCom,SETRTS)

//ok, port is ready, use WriteFile and Readfile for transmission
end;

//procedure to close port
procedure TMyFantasticProgram.CloseSerialPort;
begin
if FHCom<>INVALID_HANDLE_VALUE then
   begin
      CloseHandle(FHCom);
      FHCom:=INVALID_HANDLE_VALUE;
   end;
end;


somthing to start with!

Yours,

Alex
0
 
LVL 7

Author Comment

by:Motaz
ID: 1384202
Thanks but I want some thing simple
0
 
LVL 7

Author Comment

by:Motaz
ID: 1384203
Thanks but I want some thing simple
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 15

Expert Comment

by:simonet
ID: 1384204
The above is extremely simple to use.

Just create an instance of TCommDemoObject and use its properties and methods to send/receive data to/from the serial port.

You have worked with classes before, haven't you?

Alex

0
 
LVL 15

Accepted Solution

by:
simonet earned 80 total points
ID: 1384205
Motaz,

as you insist on usin the similar to Port under D3/Win98, here it goes:

To access a port in Win32 (Windows 9x), use the following code:

Reading:
--------
function GetPort(Address : word) : Byte;
  asm
    mov DX, Address
    XOR EAX, EAX
    in AL, DX
  end;



Writing:
--------
procedure SetPort(OutValue: Byte; Address: Word);
  asm
    mov DX, Address
    mov AL, OutValue
    out DX, AL
  end;

Under Windows NT you will have to use a VxD for port I/O.

0
 

Expert Comment

by:chiro
ID: 1384206
Te fijaste de usar las funciones Api de Windows?, con delphi 1 yo me comunique con el Port serie, las Api de windows tiene las siguientes funciones:
Setport
Opencomm
closecomm
etc.
Pero yo no se si las funciones API se pueden usar en Delphi3.
0
 
LVL 15

Expert Comment

by:simonet
ID: 1384207
>Opencomm , closecomm

These calls do not exist in 32-bit land.

Alex
0
 

Expert Comment

by:chiro
ID: 1384208
Ok ... Alex you are right!!, it`s the first Answer ...and it´s wrong ...sorry ..
Alex do you remember me? .. you are very hard with me before ... why?.
I need more points, how do I? ....

0
 
LVL 7

Author Comment

by:Motaz
ID: 1384209
Thanks very mush Alex.

Motaz
0

Featured Post

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

671 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question