Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Read/Write serial port?

Posted on 2000-03-10
10
Medium Priority
?
1,269 Views
Last Modified: 2010-05-18
I try those procedure
-------------------------------
procedure PortOut(IOport:word; Value:byte); assembler;
asm
  xchg ax,dx
  out dx,al
end;

procedure PortOutW(IOport:word; Value:word); assembler;
asm
  xchg ax,dx
  out dx,ax
end;

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


procedure SetPort(Address: Word;OutValue: Byte);
  asm
    mov DX, Address
    mov AL, OutValue
    out DX, AL
  end;
----------------------------
None of it work. I have D5 Win2K all I want to do is send a byte and receive a byte. Thanks,

0
Comment
Question by:jlislo
10 Comments
 
LVL 1

Expert Comment

by:Indefrei
ID: 2606171
Well, didn't check this one by simonetti
perhaps it can help
Sorry, if not

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;
0
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2606248
Listening
0
 

Author Comment

by:jlislo
ID: 2606280
Is their a easy way to do this?
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 17

Expert Comment

by:inthe
ID: 2606282
Hi
why not just use a component made for the job from here:
http://www.torry.ru/comms.htm

async32 or ComDrv32 are the better ones..

0
 

Author Comment

by:jlislo
ID: 2606467
async32 is for D4 did they have D5?
0
 
LVL 15

Expert Comment

by:simonet
ID: 2606468
Remember that Win2k is NT techonology, not Win9x technology. Thus, everything that applies to Windows NT 4 also applies to Win2k. You cannot, for example, have direct access to a port.

YOu have to either use one of the DeviceIO functions or the API (like in the code I wrote and Indefrei posted).

Yours,

Alex
PS: Indefrei, finally someone spelled my name right! Thanks!
0
 
LVL 17

Accepted Solution

by:
inthe earned 200 total points
ID: 2606485
async32 comes with full source therefore can also work in d5.

after unzipping the zip file do file open in delphi and open comreg.dpk and delphi will probably convert this package to d5 then install as usual.
i doubt you get any errors installing it but if you do post em here and we help get it installed.


0
 
LVL 7

Expert Comment

by:Motaz
ID: 2607311
I have a unit which works well for a months, if you write your E-Mail here I could send it to you.

Motaz
motaz1@yahoo.com
0
 

Author Comment

by:jlislo
ID: 2612506
Thanks
0
 

Author Comment

by:jlislo
ID: 2612512
Indefrei,

Thanks for the help,I put another 50points for you to pick up. Under the subject "For Indefrei"
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

810 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