473,383 Members | 1,929 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

WriteFile says open comm port has invalid handle?

Howdy,

I'm trying to write data out the com port. I have taken the code from the
sample on the MSDN Library CD and used the parts that seem relevant. I can
open the com port with CreateFile and get a valid file handle back. But
when I try to write to it, the WriteFile comes back and tells me the handle
is invalid. The program has control of the port because using Hyperterminal,
I can't connect when the program is connected.

There must be something simple I'm missing but I can't see it.

Any ideas???

--
Frank Perry
LavaLeaf Software
Nov 17 '05 #1
3 5237
On Fri, 1 Apr 2005 08:51:04 -0800, "Frank Perry"
<Fr********@discussions.microsoft.com> wrote:
Howdy,

I'm trying to write data out the com port. I have taken the code from the
sample on the MSDN Library CD and used the parts that seem relevant. I can
open the com port with CreateFile and get a valid file handle back. But
when I try to write to it, the WriteFile comes back and tells me the handle
is invalid. The program has control of the port because using Hyperterminal,
I can't connect when the program is connected.

There must be something simple I'm missing but I can't see it.


Whittle your routine down to the smallest compilable code that
reproduces the error and let us see it.

--
Sev
Nov 17 '05 #2
Howdy,

Here is the code. It is a connect function that calls a config function, a
send function where the problem shows up, and a close function.

The connect produces a valid handle but the send always says the handle is
invalid. It may be that there is more to it than that but that is the only
message I get. The com port is com6. I have the sample code from MSDN and
that is the source of the original code. It works but it is in old style
windows with message maps etc. and I don't want to use that for the app.

Here is the code:

bool CComm485::CommOpenConnection()
{

HANDLE hCommWatchThread ;
DWORD dwThreadID ;
COMMTIMEOUTS CommTimeOuts ;
char szPort[30];
int iRetVal;

wsprintf( szPort, "%s%d", "COM", m_iCommPort ) ;

// open COMM device

m_hCommHandle =
CreateFile( szPort,
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // no security attrs
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL |
FILE_FLAG_OVERLAPPED, // overlapped I/O
NULL );
if(m_hCommHandle ==INVALID_HANDLE_VALUE)
return ( FALSE ) ;
else
{
// get any early notifications

SetCommMask( m_hCommHandle, EV_RXCHAR ) ;

// setup device buffers
DWORD dwError;
if(!SetupComm( m_hCommHandle, 4096, 4096 ) )
dwError = GetLastError();

// purge any information in the buffer

PurgeComm( m_hCommHandle, PURGE_TXABORT | PURGE_RXABORT |
PURGE_TXCLEAR | PURGE_RXCLEAR ) ;

// set up for overlapped I/O

CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF ;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
CommTimeOuts.ReadTotalTimeoutConstant = 1000 ;
// CBR_9600 is approximately 1byte/ms. For our purposes, allow
// double the expected time per character for a fudge factor.
CommTimeOuts.WriteTotalTimeoutMultiplier = 2*CBR_9600/9600 ;
CommTimeOuts.WriteTotalTimeoutConstant = 0 ;
SetCommTimeouts( m_hCommHandle, &CommTimeOuts ) ;
}

iRetVal = SetUpConnection() ;

if (!iRetVal)
{
m_bConnected = TRUE ;

// Create a secondary thread
// to watch for an event.

/* if ( NULL == (hCommWatchThread =
CreateThread( (LPSECURITY_ATTRIBUTES) NULL,
0,
(LPTHREAD_START_ROUTINE) CommWatchProc,
(LPVOID) this,
0, &dwThreadID )))
{
m_bConnected = FALSE ;
CloseHandle( m_hCommHandle ) ;
iRetVal = -1 ;
}
else
*/ {
m_dwThreadID = dwThreadID ;
m_hTermWnd = (HWND) hCommWatchThread ;

// assert DTR

EscapeCommFunction( m_hCommHandle, SETDTR ) ;

}
}
else
{
m_bConnected = FALSE ;
CloseHandle( m_hCommHandle ) ;
}

// restore cursor
// test it here
// char* szBuffer;
// szBuffer = (char*) malloc(100);
// memset(szBuffer, 'X', 100);
// WriteCommBlock( npTTYInfo, szBuffer, 100);
// free(szBuffer);

m_bConnected = true;
return m_bConnected ; //(bool) OpenConnection(pInfo);
}

bool CComm485::CommCloseConnection()
{
m_bConnected = false;

// disable event notification and wait for thread
// to halt

SetCommMask( m_hCommHandle, 0 ) ;

// block until thread has been halted

while(m_dwThreadID != 0);

// kill the focus

// KillTTYFocus( hWnd ) ;

// drop DTR

EscapeCommFunction( m_hCommHandle, CLRDTR ) ;

// purge any outstanding reads/writes and close device handle

PurgeComm( m_hCommHandle, PURGE_TXABORT | PURGE_RXABORT |
PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
CloseHandle( m_hCommHandle ) ;
//return (bool) CloseConnection((NPTTYINFO) m_pTTYInfo);
return true;
}

int CComm485::SendResponse(LPSTR szResponse, int iLength)
{
NPTTYINFO pInfo = (NPTTYINFO) m_pTTYInfo;

DWORD dwBytesWritten;

// WriteCommBlock( pInfo, szResponse , iLength);
int fWriteStat = WriteFile( m_hCommHandle, szResponse, iLength,
&dwBytesWritten, &m_osWrite ) ;

if (!fWriteStat)
{
DWORD dwLastError = GetLastError();
char szErrMsg[100];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,dwLa stError,NULL,szErrMsg,
100,NULL);
dwLastError = 0;
}
return 0;
}

int CComm485::SetUpConnection()
{
BOOL fRetVal ;
DCB dcb ;
;

dcb.DCBlength = sizeof( DCB ) ;

if(!GetCommState( m_hCommHandle, &dcb ) )
{
DWORD dwLastError = GetLastError();
char szErrMsg[100];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,dwLa stError,NULL,szErrMsg,
100,NULL);
dwLastError = 0;
}

dcb.BaudRate = CBR_9600 ;
dcb.ByteSize = 8 ;
dcb.Parity = NOPARITY ;
dcb.StopBits = ONESTOPBIT ;

// setup hardware flow control

dcb.fDtrControl = DTR_CONTROL_DISABLE ;
dcb.fRtsControl = RTS_CONTROL_DISABLE ;
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = FALSE;
dcb.fDsrSensitivity = FALSE;
dcb.fRtsControl = FALSE;

// setup software flow control
// bSet = 0; // no flow control
dcb.fInX = dcb.fOutX = FALSE ;
// dcb.XonChar = ASCII_XON ;
// dcb.XoffChar = ASCII_XOFF ;
// dcb.XonLim = 100 ;
// dcb.XoffLim = 100 ;

// other various settings
dcb.fAbortOnError = FALSE;

dcb.fBinary = TRUE ;
dcb.fParity = TRUE ;

fRetVal = SetCommState( m_hCommHandle, &dcb ) ;
DWORD dwError;
if(!fRetVal)
{
dwError = GetLastError();
char szErrMsg[100];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,dwEr ror,NULL,szErrMsg,
100,NULL);
dwError = 0;
return -1;
}

return 0;

}

Any help would be appreciated.

Frank Perry

"Severian" wrote:
On Fri, 1 Apr 2005 08:51:04 -0800, "Frank Perry"
<Fr********@discussions.microsoft.com> wrote:
Howdy,

I'm trying to write data out the com port. I have taken the code from the
sample on the MSDN Library CD and used the parts that seem relevant. I can
open the com port with CreateFile and get a valid file handle back. But
when I try to write to it, the WriteFile comes back and tells me the handle
is invalid. The program has control of the port because using Hyperterminal,
I can't connect when the program is connected.

There must be something simple I'm missing but I can't see it.


Whittle your routine down to the smallest compilable code that
reproduces the error and let us see it.

--
Sev

Nov 17 '05 #3
On Fri, 1 Apr 2005 10:05:05 -0800, "Frank Perry"
<Fr********@discussions.microsoft.com> wrote:
"Severian" wrote:
On Fri, 1 Apr 2005 08:51:04 -0800, "Frank Perry"
<Fr********@discussions.microsoft.com> wrote:
>Howdy,
>
>I'm trying to write data out the com port. I have taken the code from the
>sample on the MSDN Library CD and used the parts that seem relevant. I can
>open the com port with CreateFile and get a valid file handle back. But
>when I try to write to it, the WriteFile comes back and tells me the handle
>is invalid. The program has control of the port because using Hyperterminal,
>I can't connect when the program is connected.
>
>There must be something simple I'm missing but I can't see it.


Whittle your routine down to the smallest compilable code that
reproduces the error and let us see it.


Howdy,

Here is the code. It is a connect function that calls a config function, a
send function where the problem shows up, and a close function.

The connect produces a valid handle but the send always says the handle is
invalid. It may be that there is more to it than that but that is the only
message I get. The com port is com6. I have the sample code from MSDN and
that is the source of the original code. It works but it is in old style
windows with message maps etc. and I don't want to use that for the app.

Here is the code:


<snip>

That was not enough to compile and test, so all I can do is guess.

1) Have you checked in the debugger that the m_hCommHandle is the same
when you call WriteFile? (Not corrupted or changed by something.)

2) Is m_osWrite properly intialized, including the event handle?

--
Phillip Crews aka Severian
Micrisoft MVP, Windows SDK
Posting email address is real
Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: dim | last post by:
Copied directly from exaple book but not working.... All i get is an empty 0 byte file Call to GetLastError directly after the call to WriteFile returns 0 (NO_ERROR) but no data sees to be written...
1
by: Chuck Rittersdorf | last post by:
Hi There I am having a problem using the win32 API from VB6. I am trying to send a command string to a printer(zebra TLP 2742) on LPT1 using the folowing API functions CreateFile and...
0
by: Nitin Narang | last post by:
I have a piece of code which is moved to .NET VC7 recently from VC6 and there has been an apparent change in behavior using CreateFile/Writefile functionality. I am creating a file on a shared...
1
by: sarath1111 | last post by:
hi all, I am using comm port for serial communication between 2 PC's using C language. Once I have initialized the COMM port, Is there any option of closing the port in C language. Thanks in...
1
by: Paul | last post by:
Hi, I am extending an existing MFC app to use Unicode (for a Japanese version of the interface elements). The app's purpose is to control a peripheral device through the serial port, and the...
7
by: Michael Chong | last post by:
I wrote a program that communicate with SerialComm. In every 300 milliseconds, my program continuously send & receive data via the serial port once the program starts. My program is once in a...
0
by: Michael Chong | last post by:
I am not very good in C++ problem and this is my codes below. I do not know whether I got handshaking involve in my code. Could you guys let me know? HANDLE OpenComm(char *lpszPort, int nBaud,...
4
by: Iceman.Aragorn | last post by:
I'm having an odd problem where im reading input from a comm port (the maker of the software that exports the data TO the comm port is unhelpful). What im reading is fixed length (13 character)...
2
by: Hank | last post by:
Hello, I would like to get some opinions on using the Comm Port with Access 2000. We have a few jobs coming in that require us to interface with a PLC via the Comm Port. My partner feels we...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.