Solved

Read/Write serial port?

Posted on 2000-03-10
10
1,253 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
Comment Utility
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
Comment Utility
Listening
0
 

Author Comment

by:jlislo
Comment Utility
Is their a easy way to do this?
0
 
LVL 17

Expert Comment

by:inthe
Comment Utility
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
Comment Utility
async32 is for D4 did they have D5?
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 15

Expert Comment

by:simonet
Comment Utility
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 50 total points
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks
0
 

Author Comment

by:jlislo
Comment Utility
Indefrei,

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

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now