Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write to and read from Com ports using MS Visual C++ 1

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I have been asked to write a piece of software as a starting block for a communications device emulator.
I was told to use Microsoft Visual C++ to write an application that took in text in and edit box and "on the click of a button" wrote the text to com port 1 and read it back in from com port 2 (ports connected on PC by a serial cable) and displayed the read in text in a second edit box.
Sounds easy but I am at breaking point with it.
Having spent hours in the MSDN pages I now have a code that compiles but does nothing.
I have just moved from working in a UNIX very non-visual environment and am very much at sea with this environment.
I have documentation on CreatFile, WriteFile and ReadFile up to my eyes...can anybody please show me how to perform this task simply ?????!!! *(before I fall out of love with C++ ???!!!)
 
Unfortunately simple doesn't come into it where comms in VC are concerned.

To open a port:

hCommHandle = CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

To set the Baud rate and stuff:

DCB sDCB ;

GetCommState(hCommHandle, &sDCB);
sDCB.BaudRate = 19200 ;
sDCB.fBinary = FALSE ; // Since you are sending text.
sDCB.fParity = FALSE ; // Usually 8,N,2
sDCB.fNULL = FALSE ;
sDCB.ByteSize = 8 ;
sDCB.Parity = 0 ; // 'None'.
sDCB.StopBits = 2 ;
sDCB.fOutxCtsFlow = FALSE ;
sDCB.fRtsControl = RTS_CONTROL_DISABLE ;
sDCB.fTXContinueOnXoff = TRUE ;
sDCB.fOutX = FALSE ;
sDCB.fInX = FALSE ;
sDCB.fErrorChar = FALSE ;
sDCB.EofChar = 0 ;

SetCommState(hCommHandle, &sDCB);

To write to the port:

CString strText = _T("Hello!");
DWORD dwBytesWritten ;

WriteFile(hCommHandle,(LPCTSTR)strText, strText.GetLength(), &dwBytesWritten, NULL);


To check how many characters are waiting at a port to read:

COMSTAT sStatus ;
DWORD dwDummy ;

ClearCommError(hCommHandle, &dwDummy, &sStatus);

The number of bytes waiting is in sStatus.cbInQue.


To read a port:

TCHAR cBuffer[100];
ReadFile(hCommHandle, cBuffer, sStatus.cbInQue, &dwBytesRead, NULL);

Note: this will block (with timeout) if there are not as many in the queue as you ask to read.


To close the port:

CloseHandle(hCommHandle);

 
try to fing on internet (because I lost the web page _sorry_) the Class CRS232...all the functions are inside for writing and raed from this port.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top