Manu said:
i need to know how i can interface to RS232 with VC++.NET (MFC). In the
old VC++ 6.0 there is the MSCOMM32 component, i read i can use it but
there are some license problems. Is there some low level interface can i
use??
I don't know if MFC provides a class library that addresses serial
communication. The old version of Visual Studio provided a non-MFC sample.
You may still be able to download it at this link:
http://msdn.microsoft.com/library/d...erialsampleforcommunicationsdemonstration.asp
In case you don't know, on Win32 every device is accessed by means of a
handle. Reads of the device are done by passing the handle to ReadFile() and
writes by passing the handle to WriteFile().
You will find a little _hack_ below which presumes the existence of a modem
on COM3, gets a handle to a the serial port, posts a read, sends the Hayes
command "identify" and reads the response.
It should get you started.
Regards,
Will
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv)
{
char szBuffer[80];
DCB dcb = {0};
DWORD dwRead, dwWritten;
HANDLE hComm;
OVERLAPPED ovlr = {0}, ovlw = {0};
COMMTIMEOUTS cto;
// Create events for overlapped operation
ovlr.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
ovlw.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// Open the port
hComm = CreateFile("\\\\.\\COM3", GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
// Get the state of the device and modify it
dcb.DCBlength = sizeof(dcb);
GetCommState(hComm, &dcb);
dcb.BaudRate = CBR_9600;
SetCommState(hComm, &dcb);
// Set the timeout parameters (almost completely bogus here)
cto.ReadIntervalTimeout = 1000;
cto.ReadTotalTimeoutConstant = 1000;
cto.ReadTotalTimeoutMultiplier = 1000;
cto.WriteTotalTimeoutConstant = 1000;
cto.WriteTotalTimeoutMultiplier = 1000;
SetCommTimeouts(hComm, &cto);
// Send a command and receieve a response. Note that
// we post the receive in advance of sending the
// command in order not to miss anything
printf("\r\nSending: ATI1\r\n");
ReadFile (hComm, szBuffer, sizeof(szBuffer), &dwRead, &ovlr);
WriteFile(hComm, "ATI1\r", strlen("ATI1\r"), &dwWritten, &ovlw);
// Wait for the receive to complete and display the response
if ( GetOverlappedResult(hComm, &ovlr, &dwRead, TRUE) )
{
szBuffer[dwRead] = 0;
printf("Received: %s\r\n", szBuffer);
}
// Close the device
CloseHandle(hComm);
return 0;
}