Serial port communication in VC++

This program which you have displayed....it will allow you to sent commands to Com1 on your computer??

My problem is that I have hooked up a simple machine to my computer and after having written a program in C++, I am not sure how to send the program commands to port. If you have any suggestions or can help in any way, please do.

Sincerely
Neha Khera
 
N

nasser siddiqui

hi,
i am doing my project on Mutiple serial port I/O communication where i have to send file from one PC to other connected in lan through
serial port.please help me if u have code related to this subject

thanks
nasser siddiqui
[email protected]
MCA final year
Osmania university
 
Hi Madur Sharma,
I had used the code below to get started with serial port communication..Right now I do not have a test set up or something..All I want to do is see if I can test the serial comm with a single PC. Sounds wierd eh?!

I am trying to write on say "COM2" and want to read it from the same port "COM2". Is it possible..? I tired doing "PortWrite()" from within "PortReadThread()" itself as well as from "PortInitialize()" still no success..

Pls find attached my modifications to the code.
An early reply would be of real help...

Thank you
Indu.S

Pls reply to [email protected]
/***********************************************************************
Module Name:
serial.c

***********************************************************************/

#include <windows.h>
#include <iostream.h>
#include "tty.h"


/***********************************************************************

PortInitialize (LPTSTR lpszPortName)

***********************************************************************/
BOOL PortInitialize (LPTSTR lpszPortName)
{
DWORD dwError,dwThreadID, dwBytesTransferred;
DCB PortDCB;
COMMTIMEOUTS CommTimeouts;
BYTE Byte = (BYTE) "G";
BYTE Byte1;

// Open the serial port.
hPort = CreateFile (lpszPortName, // Pointer to the name of the port
GENERIC_READ | GENERIC_WRITE, // Access (read/write) mode
0, // Share mode
NULL, // Pointer to the security
attribute
OPEN_EXISTING, // How to open the serial port
0, // Port attributes
NULL); // Handle to port with attribute
to copy

// If it fails to open the port, return FALSE.
if ( hPort == INVALID_HANDLE_VALUE )
{
// Could not open the port.
MessageBox (hMainWnd, TEXT("Unable to open the port"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}

PortDCB.DCBlength = sizeof (DCB);

// Get the default port setting information.
GetCommState (hPort, &PortDCB);

// Change the DCB structure settings.
PortDCB.BaudRate = 9600; // Current baud
PortDCB.fBinary = TRUE; // Binary mode; no EOF check
PortDCB.fParity = TRUE; // Enable parity checking.
PortDCB.fOutxCtsFlow = FALSE; // No CTS output flow control
PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control
PortDCB.fDtrControl = DTR_CONTROL_ENABLE;
// DTR flow control type
PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity
PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx
PortDCB.fOutX = FALSE; // No XON/XOFF out flow control
PortDCB.fInX = FALSE; // No XON/XOFF in flow control
PortDCB.fErrorChar = FALSE; // Disable error replacement.
PortDCB.fNull = FALSE; // Disable null stripping.
PortDCB.fRtsControl = RTS_CONTROL_ENABLE; // RTS flow control
PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes on error.
PortDCB.ByteSize = 8; // Number of bits/bytes, 4-8
PortDCB.Parity = NOPARITY; // 0-4=no,odd,even,mark,space
PortDCB.StopBits = ONESTOPBIT; // 0,1,2 = 1, 1.5, 2

// Configure the port according to the specifications of the DCB
// structure.
if (!SetCommState (hPort, &PortDCB))
{
// Could not create the read thread.
MessageBox (hMainWnd, TEXT("Unable to configure the serial port"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}

// Retrieve the time-out parameters for all read and write operations
// on the port.
GetCommTimeouts (hPort, &CommTimeouts);

// Change the COMMTIMEOUTS structure settings.
CommTimeouts.ReadIntervalTimeout = MAXDWORD;
CommTimeouts.ReadTotalTimeoutMultiplier = 10;
CommTimeouts.ReadTotalTimeoutConstant = 1000;
CommTimeouts.WriteTotalTimeoutMultiplier = 10;
CommTimeouts.WriteTotalTimeoutConstant = 1000;

// Set the time-out parameters for all read and write operations
// on the port.
if (!SetCommTimeouts (hPort, &CommTimeouts))
{
// Could not create the read thread.
MessageBox (hMainWnd, TEXT("Unable to set the time-out parameters"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}

// Direct the port to perform extended functions SETDTR and SETRTS.
// SETDTR: Sends the DTR (data-terminal-ready) signal.
// SETRTS: Sends the RTS (request-to-send) signal.
EscapeCommFunction (hPort, SETDTR);
EscapeCommFunction (hPort, SETRTS);

PortWrite(Byte);
ReadFile (hPort, &Byte1, 1, &dwBytesTransferred, NULL);

// Create a read thread for reading data from the communication port.


/*if (hReadThread = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)PortReadThread,
0, 0,
&dwThreadID))
{
CloseHandle (hReadThread);
}

else
{
// Could not create the read thread.
MessageBox (hMainWnd, TEXT("Unable to create the read thread"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}*/

PortClose(hPort);
return TRUE;
}


/***********************************************************************

PortWrite (BYTE Byte)

***********************************************************************/
void PortWrite (BYTE Byte)
{
DWORD dwError,
dwNumBytesWritten;

if (!WriteFile (hPort, // Port handle
&Byte, // Pointer to the data to write
1, // Number of bytes to write
&dwNumBytesWritten, // Pointer to the number of bytes
// written
NULL)) // Must be NULL for Windows CE
{
// WriteFile failed. Report error.
dwError = GetLastError ();
}
}



/***********************************************************************

PortReadThread (LPVOID lpvoid)

***********************************************************************/
DWORD PortReadThread (LPVOID lpvoid)
{
BYTE Byte;
DWORD dwCommModemStatus,
dwBytesTransferred,
dwError;

// Specify a set of events to be monitored for the port.
SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING);

while (hPort != INVALID_HANDLE_VALUE)
{
// Wait for an event to occur for the port.
WaitCommEvent (hPort, &dwCommModemStatus, 0);

// Re-specify the set of events to be monitored for the port.
SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RING);

if (dwCommModemStatus & EV_RXCHAR)
{
// Loop for waiting for the data.
do
{
// Read the data from the serial port.
ReadFile (hPort, &Byte, 1, &dwBytesTransferred, 0);

// Display the data read.
if (dwBytesTransferred == 1)
/* ProcessChar(Byte);*/
cout << " " << Byte;

} while (dwBytesTransferred == 1);
}

// Retrieve modem control-register values.
GetCommModemStatus (hPort, &dwCommModemStatus);

// Set the indicator lights.
/*SetLightIndicators (dwCommModemStatus);*/
}

return 0;
}


/***********************************************************************

PortClose (HANDLE hCommPort)

***********************************************************************/
BOOL PortClose (HANDLE hCommPort)
{
DWORD dwError;

if (hCommPort != INVALID_HANDLE_VALUE)
{
// Close the communication port.
if (!CloseHandle (hCommPort))
{
dwError = GetLastError ();
return FALSE;
}
else
{
hCommPort = INVALID_HANDLE_VALUE;
return TRUE;
}
}

return FALSE;
}


void main()
{
LPTSTR lpszPortName = "COM2";
PortInitialize(lpszPortName);
}
 
Hi Madhur Sharma,
I have tried your code below but i still have compiling error. It's about 'ProcessChar' and 'SetLightIndicators' which are consider as
"undeclared identifier" by the compilator. What should I do please?
Another problem is that I am not using a modem; I have a direct connection by cable between my computer and our PBX through serial ports. I
need to read data from the serial port of my computer which are call detail records provided by the PBX.
Please do you think that this your code could help me to perform that task?
Thanks for your help.
RODRIGUE from LOME TOGO (WEST AFRICA)
[email protected]
 
hi mathur sharma

can u ( or anyone) help me to build an ocx which
contains mscomm also. i wish to create reusable components for every devices.

Pls advise.

Thanks
 
I wrote the following program for logging into my ISP, but for some reason the ReadFile does not returns. However, if I use HyperTerminal for doing the same this, and then disconnect and run my program, it works. Similarly, if I once get the connection using Dial-up service that comes with Windows, and then disconnect and try to connect again with my program, then it works (that is, the ReadFile returns).

Please advise.
Thanks.


#include <stdio.h>
#include <windows.h>

int
main(int argc, char *argv[])
{
HANDLE hCom;
COMMPROP commProp = {0};
COMMCONFIG commConfig = {0};
DCB dcb = {0};
BOOL fSuccess;
DWORD bytesRW;
char *pcCommPort[] = {"COM1","COM2","COM3","COM4"};
char mdmData[512];
char tempData[20];
int i;

while(1)
{
//////////////////////////
// Find and open modem //
//////////////////////////
for(i=1; i<=4; i++)
{
// Open a COM port
hCom = CreateFile(
pcCommPort[i-1],
GENERIC_READ | GENERIC_WRITE,
0, // comm devices must be opened w/exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
0, // Non-overlapped I/O
NULL // hTemplate must be NULL for comm devices
);

if (hCom == INVALID_HANDLE_VALUE)
{
// Handle the error.
printf ("\n\nCreateFile failed at %s with error %d.", pcCommPort[i-1], GetLastError());
continue;
}
printf ("\n\nCreateFile succeeded at %s!.", pcCommPort[i-1]);

// Get modem capabilities
fSuccess = GetCommProperties(
hCom, // handle to comm device
&commProp // communications properties
);

if (!fSuccess)
{
// Handle the error.
printf ("\nGetCommProperties failed at %s with error %d.", pcCommPort[i-1], GetLastError());
return (0);
}
printf ("\nGetCommProperties succeeded at %s!.", pcCommPort[i-1]);

if(commProp.dwProvSubType != PST_MODEM)
{
printf("\nNo modem found at %s!", pcCommPort[i-1]);
if(i==4)
{
printf("\nNo modem found in this computer!");
return(0);
}
CloseHandle(hCom);
continue;
}
else
{
printf("\nModem found at %s!", pcCommPort[i-1]);
break;
}
}
/////////////////////
// Configure modem //
/////////////////////

// Get current configuration of the modem
fSuccess = GetCommState(
hCom, // handle to comm device
&dcb // device-control block
);

if (!fSuccess)
{
printf ("\nGetCommState failed at %s with error %d.", pcCommPort[i-1], GetLastError());
break;
}
printf ("\nGetCommState succeeded at %s!.", pcCommPort[i-1]);

dcb.BaudRate = 57600; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit

fSuccess = SetCommState(
hCom, // handle to comm device
&dcb // device-control block
);

if (!fSuccess)
{
printf ("\nSetCommState failed with error %d.", GetLastError());
break;
}
printf ("\nSetCommState succeeded at %s!.", pcCommPort[i-1]);


//////////////////////
// Write/Read Modem //
//////////////////////

strcpy(mdmData, "ATDT3891004\r\n");

fSuccess = WriteFile(
hCom,
mdmData,
(DWORD)strlen(mdmData),
&bytesRW,
0
);

if (!fSuccess)
{
// Handle the error.
printf ("\nWriteFile failed with error %d.", GetLastError());
break;
}
printf ("\nWriteFile succeeded at %s.", pcCommPort[i-1]);
printf("\nDialing...");
Sleep(20000);

while(1)
{
memset(mdmData, '\0', sizeof(mdmData));
fSuccess = ReadFile(
hCom,
mdmData,
sizeof(mdmData),
&bytesRW,
0
);

if (!fSuccess)
{
// Handle the error.
printf ("\nReadFile failed with error %d.", GetLastError());
}
else
{
printf ("\nReadFile succeeded at %s.", pcCommPort[i-1]);
printf("%s", mdmData);
strupr(mdmData);

if(strstr(mdmData, "ENTER USERNAME"))
{
memset(mdmData, '\0', sizeof(mdmData));
scanf("%s",mdmData);
strcat(mdmData, "\r\n");
fSuccess = WriteFile(
hCom,
mdmData,
(DWORD)strlen(mdmData),
&bytesRW,
0
);

}
else if(strstr(mdmData, "ENTER YOUR PASSWORD"))
{
memset(mdmData, '\0', sizeof(mdmData));
scanf("%s",mdmData);
strcat(mdmData, "\r\n");
fSuccess = WriteFile(
hCom,
mdmData,
(DWORD)strlen(mdmData),
&bytesRW,
0
);
}
}
}
}

if (hCom != INVALID_HANDLE_VALUE)
{
CloseHandle(hCom);
}

return(0);
}
 
hi
you can do this simply.
you must run hyper terminal and set :
baud rate=9600
stop bit=1
parity =none
data bit=8
then select your com port and then select:
transfer--> capture text
from menu bar

your pbx must connect to your serialport at pc with rs232 cable
if you have problem email to me:
[email protected]
bye!
 
G

Ganesh Okade

Hello Manish,
You need to write a filter driver (assuming Win 2K+ or Win 98+) in which you attach a device object to the existing serial device. This new driver will be a layer above the serial driver and hence above your modem and so all data gets passed through this filter driver.

Regards,
Ganesh
 
i want to write on the port and read from that port. when i complete my write operation on port then only event of read should start using vc++
and mfc event
pleaze guide me
 
Hi Madhur,
I am facing the problem with serial communation.
I Open the Port with CreateFile and store the
return value in HANDLE. Program wait for the event using WaitCommEvent.It reads the data properly without any problem.In the window destroy event closing Port using CloseHandle(retOfCreateFile). It still waiting to read the data.I could not figure out the problem.

Could I get some guidance from you.

Thanks in Advance.
Dev
 
this is referred to the person who had asked a question regarding serial port commn. in vc++. sorry i cannot help u as i am facing a similar problem. i am still in step one of writing a serial port communication program in vc++. i wanted to know how exactly do i start off. i have familiar with MFC.
 
<p>Hi Madur Sharma,

<p>I had used the code below to get started with serial port communication..Right now I do not have a test set up or something..All I want to do is see if I can test the serial comm with a single PC. Sounds wierd eh?!

<p>I am trying to write on say "COM2" and want to read it from the same port "COM2". Is it possible..? I tired doing "PortWrite()" from within "PortReadThread()" itself as well as from "PortInitialize()" still no success..

<p>Pls find attached my modifications to the code. An early reply would be of real help...

<p>Thank you<br>
Indu.S

<p>Pls reply to [email protected]

<pre>
/***********************************************************************
Module Name:
serial.c
***********************************************************************/

#include <windows.h>
#include <iostream.h>
#include "tty.h"


/***********************************************************************

PortInitialize (LPTSTR lpszPortName)

***********************************************************************/
BOOL PortInitialize (LPTSTR lpszPortName)
{
DWORD dwError,dwThreadID, dwBytesTransferred;
DCB PortDCB;
COMMTIMEOUTS CommTimeouts;
BYTE Byte = (BYTE) "G";
BYTE Byte1;

// Open the serial port.
hPort = CreateFile (lpszPortName, // Pointer to the name of the port
GENERIC_READ | GENERIC_WRITE, // Access (read/write) mode
0, // Share mode
NULL, // Pointer to the security
attribute
OPEN_EXISTING, // How to open the serial port
0, // Port attributes
NULL); // Handle to port with attribute
to copy

// If it fails to open the port, return FALSE.
if ( hPort == INVALID_HANDLE_VALUE )
{
// Could not open the port.
MessageBox (hMainWnd, TEXT("Unable to open the port"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}

PortDCB.DCBlength = sizeof (DCB);

// Get the default port setting information.
GetCommState (hPort, &PortDCB);

// Change the DCB structure settings.
PortDCB.BaudRate = 9600; // Current baud
PortDCB.fBinary = TRUE; // Binary mode; no EOF check
PortDCB.fParity = TRUE; // Enable parity checking.
PortDCB.fOutxCtsFlow = FALSE; // No CTS output flow control
PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control
PortDCB.fDtrControl = DTR_CONTROL_ENABLE;
// DTR flow control type
PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity
PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx
PortDCB.fOutX = FALSE; // No XON/XOFF out flow control
PortDCB.fInX = FALSE; // No XON/XOFF in flow control
PortDCB.fErrorChar = FALSE; // Disable error replacement.
PortDCB.fNull = FALSE; // Disable null stripping.
PortDCB.fRtsControl = RTS_CONTROL_ENABLE; // RTS flow control
PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes on error.
PortDCB.ByteSize = 8; // Number of bits/bytes, 4-8
PortDCB.Parity = NOPARITY; // 0-4=no,odd,even,mark,space
PortDCB.StopBits = ONESTOPBIT; // 0,1,2 = 1, 1.5, 2

// Configure the port according to the specifications of the DCB
// structure.
if (!SetCommState (hPort, &PortDCB))
{
// Could not create the read thread.
MessageBox (hMainWnd, TEXT("Unable to configure the serial port"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}

// Retrieve the time-out parameters for all read and write operations
// on the port.
GetCommTimeouts (hPort, &CommTimeouts);

// Change the COMMTIMEOUTS structure settings.
CommTimeouts.ReadIntervalTimeout = MAXDWORD;
CommTimeouts.ReadTotalTimeoutMultiplier = 10;
CommTimeouts.ReadTotalTimeoutConstant = 1000;
CommTimeouts.WriteTotalTimeoutMultiplier = 10;
CommTimeouts.WriteTotalTimeoutConstant = 1000;

// Set the time-out parameters for all read and write operations
// on the port.
if (!SetCommTimeouts (hPort, &CommTimeouts))
{
// Could not create the read thread.
MessageBox (hMainWnd, TEXT("Unable to set the time-out parameters"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}

// Direct the port to perform extended functions SETDTR and SETRTS.
// SETDTR: Sends the DTR (data-terminal-ready) signal.
// SETRTS: Sends the RTS (request-to-send) signal.
EscapeCommFunction (hPort, SETDTR);
EscapeCommFunction (hPort, SETRTS);

PortWrite(Byte);
ReadFile (hPort, &Byte1, 1, &dwBytesTransferred, NULL);

// Create a read thread for reading data from the communication port.


/*if (hReadThread = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)PortReadThread,
0, 0,
&dwThreadID))
{
CloseHandle (hReadThread);
}

else
{
// Could not create the read thread.
MessageBox (hMainWnd, TEXT("Unable to create the read thread"),
TEXT("Error"), MB_OK);
dwError = GetLastError ();
return FALSE;
}*/

PortClose(hPort);
return TRUE;
}


/***********************************************************************

PortWrite (BYTE Byte)

***********************************************************************/
void PortWrite (BYTE Byte)
{
DWORD dwError,
dwNumBytesWritten;

if (!WriteFile (hPort, // Port handle
&Byte, // Pointer to the data to write
1, // Number of bytes to write
&dwNumBytesWritten, // Pointer to the number of bytes
// written
NULL)) // Must be NULL for Windows CE
{
// WriteFile failed. Report error.
dwError = GetLastError ();
}
}



/***********************************************************************

PortReadThread (LPVOID lpvoid)

***********************************************************************/
DWORD PortReadThread (LPVOID lpvoid)
{
BYTE Byte;
DWORD dwCommModemStatus,
dwBytesTransferred,
dwError;

// Specify a set of events to be monitored for the port.
SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING);

while (hPort != INVALID_HANDLE_VALUE)
{
// Wait for an event to occur for the port.
WaitCommEvent (hPort, &dwCommModemStatus, 0);

// Re-specify the set of events to be monitored for the port.
SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RING);

if (dwCommModemStatus & EV_RXCHAR)
{
// Loop for waiting for the data.
do
{
// Read the data from the serial port.
ReadFile (hPort, &Byte, 1, &dwBytesTransferred, 0);

// Display the data read.
if (dwBytesTransferred == 1)
/* ProcessChar(Byte);*/
cout << " " << Byte;

} while (dwBytesTransferred == 1);
}

// Retrieve modem control-register values.
GetCommModemStatus (hPort, &dwCommModemStatus);

// Set the indicator lights.
/*SetLightIndicators (dwCommModemStatus);*/
}

return 0;
}


/***********************************************************************

PortClose (HANDLE hCommPort)

***********************************************************************/
BOOL PortClose (HANDLE hCommPort)
{
DWORD dwError;

if (hCommPort != INVALID_HANDLE_VALUE)
{
// Close the communication port.
if (!CloseHandle (hCommPort))
{
dwError = GetLastError ();
return FALSE;
}
else
{
hCommPort = INVALID_HANDLE_VALUE;
return TRUE;
}
}

return FALSE;
}


void main()
{
LPTSTR lpszPortName = "COM2";
PortInitialize(lpszPortName);
}
</pre>
 
Top