Solved

Why this Win API serial port access doesn't work under W2k?

Posted on 2002-04-11
12
323 Views
Last Modified: 2010-04-04
I need to write to and read from the COM port. I have the following code which works under Win98, but fails under Win2k. What on earth I'm doing wrong?

Thank you for you help,
Levente

--------------------------------------------------------
function TComport.Open(const ComPort: String): boolean;
var DCB : TDCB;
begin
   Handle := CreateFile( PChar('\\.\' + ComPort),
                         GENERIC_READ or GENERIC_WRITE,
                         0,
                         nil,
                         OPEN_EXISTING,
                         FILE_FLAG_OVERLAPPED,
                         0);

   DCB.DCBlength := sizeof(TDCB);
   GetCommState(Handle, DCB);
   DCB.BaudRate := CBR_9600;
   SetCommState(Handle,DCB);
end;

procedure TComPort.Close;
begin
  CloseHandle(Handle);
end;

procedure TComPort.WriteStr(const Buffer: string);
var WriteBuffer:  array [0..15] of char;
    CharsToWrite, CharsWritten: cardinal;
begin
   CharsToWrite:= length(buffer);
   move(Buffer[1], WriteBuffer, CharsToWrite);
   WriteFile(Handle, WriteBuffer, CharsToWrite, CharsWritten, NIL);
end;

procedure TComPort.ReadStr(var Buffer: string; const CharToRead: Word);
var CharsRead: Cardinal;
    ReadBuffer: array [0..15] of char;
begin
  ReadFile( Handle, ReadBuffer, CharToRead, CharsRead, NIL);
  Buffer:= ReadBuffer;
end;

0
Comment
Question by:Levente
  • 3
  • 2
  • 2
  • +4
12 Comments
 
LVL 7

Expert Comment

by:Motaz
Comment Utility
I have a component called Async32, it works fine for me for more than 2 years without any problems, and it is very easy to use.

Tell me your E-Mail and I can send it to you if you want.
Motaz
0
 
LVL 6

Expert Comment

by:zebada
Comment Utility
Change FILE_FLAG_OVERLAPPED to FILE_ATTRIBUTE_NORMAL.

I don't know why/if it works on Win95 but if you open a com port with FILE_FLAG_OVERLAPPED you MUST supply a valid pointer to an overlapped structure as the last parameter to readfile and writefile. Since you are supplying a NIL pointer you should not have opened the file with FILE_FLAG_OVERLAPPED.
0
 

Author Comment

by:Levente
Comment Utility
Motaz,

I'd appreciate if you sent me that component to slv@freemail.hu. It may give me hints.

zebada,

I tried FILE_ATTRIBUTE_NORMAL but it still fails under Win2K.

Levente
0
 
LVL 3

Expert Comment

by:SteveWaite
Comment Utility
You do not say in what way it goes wrong!

Maybe you need to call:
SetupComm(Handle, RxBufferSize, TxBufferSize);
To ensure the buffer sizes are OK.
Or if you do not get data in/out:
NT/Win2k has a different default serial port setting for handshaking. Since you do not setup handshaking in your code the settings the com port had last are used. So you may need you to wire the cable slightly differently: i.e. connect DTR to DSR (at the plug on the NT machine) to get NT/Win2k to enable the port.
Let me know.....
 
0
 

Author Comment

by:Levente
Comment Utility
I tried SetupComm, but it doesn't work under W2k.

Is there any tool which catches and logs the bytes sent to the serial port? This way I may be able to debug what's going wrong.

Thanks,
Levente
0
 
LVL 6

Expert Comment

by:zebada
Comment Utility
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Expert Comment

by:TomazB
Comment Utility
Hi!

Like zebada already said you have problem in FILE_FLAG_OVERLAPPED. I tried your code and on my
Win2000 it definitively works. Try again nad change to FILE_ATTRIBUTE_NORMAL.

It should be

Handle := CreateFile( PChar('\\.\' + ComPort),
                        GENERIC_READ or GENERIC_WRITE,
                        0,
                        nil,
                        OPEN_EXISTING,
                        FILE_ATTRIBUTE_NORMAL,
                        0);

If ComPort is 'Com1' it is opened and it works for read and write. About your read procedure > Before open and close port you should always set handle to INVALID_HANDLE_VALUE and always check it before read or write. Also before read it is good to check how much to read. Perhaps like this.

function GetInCount:LongInt;
var statPort:TCOMSTAT;
    dwErrorCode:DWORD;
begin
 Result:=0;
 if Handle<>INVALID_HANDLE_VALUE then
  begin
   ClearCommError(Handle,dwErrorCode,@statPort);
   Result:=statPort.cbInQue;
  end;
end;

I am doing it like this for 5 years on NT and Win2000 mascines without problems, except that for ports beyond 8 I use sintaks '//./COM'+ value of port.
Good luck!
0
 

Author Comment

by:Levente
Comment Utility
TomazB,

Thank you for your help. I tried your code and the result is that GetInCount function returns 0, even under Win98.

What device do you attach to the COM port to test your code? I'm using a proprietary hardware device (a friend of mine has made a device to control stepping motors), so is it possible that our device works in a way that Win2k cannot read data from it?

Thank you,
Levente
0
 

Accepted Solution

by:
TomazB earned 300 total points
Comment Utility
Hello!

Well, actually I comunicate with annother PC while testing communication of my programs. I didn't have any problems with palette of PLCs and fire protection units which can communicate trough serial port. I you have problems it is possible that some flags of TDCB structure you set during initialisation of serial port are not properly set. Are you
sure that your device actualy send any characters to port? Check flag settings and control lines CTS, RTS, DTR and DSR if you use them. Serial port is standard device and if you made your device inside standards there should be no problems.

0
 

Expert Comment

by:FJani
Comment Utility
Szia!

Azt hiszem nem tévedek a neveddel kapcsolatban, úgyhogy írok magyarul inkább, mint angolul.
Nagyon nagy gondban vagyok, szakdolgozathoz kellene a soros port kezelés. Olvastam a te régi problémádat, hogy winNT alatt ment a programod, Win9x alatt nem. Nekem ez pont fordítva van! :-( Tudnál segíteni?

Üdv:
Jani
trantor@europe.com
0
 
LVL 1

Expert Comment

by:pnh73
Comment Utility
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Accept answer from TomazB

Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
Paul (pnh73)
EE Cleanup Volunteer
0
 
LVL 1

Expert Comment

by:pnh73
Comment Utility
Thank you for your response

Paul (pnh73)
EE Cleanup Volunteer
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
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…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 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

16 Experts available now in Live!

Get 1:1 Help Now