home *** CD-ROM | disk | FTP | other *** search
- //***************************************************************
- // From the book "Win32 System Services: The Heart of Windows NT"
- // by Marshall Brain
- // Published by Prentice Hall
- //
- // Copyright 1994, by Prentice Hall.
- //
- // This code demonstrates an extremely simple serial connection.
- //***************************************************************
-
- // commtest.cpp
-
- #include <windows.h>
- #include <iostream.h>
-
- void ErrorHandler(char *message, DWORD error)
- {
- cout << message << endl;
- cout << "Error number = " << error << endl;
- ExitProcess(1);
- }
-
- void main()
- {
- HANDLE comHandle;
- BOOL success;
- DCB dcb;
- char str[100];
- DWORD numWrite, numRead;
- COMMTIMEOUTS timeouts;
-
- // Open the comm port. Can open COM, LPT,
- // or \\\\.\\TELNET
- comHandle = CreateFile("COM2",
- GENERIC_READ|GENERIC_WRITE,
- 0, 0, OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL, 0);
- if (comHandle == INVALID_HANDLE_VALUE)
- ErrorHandler("In CreateFile",
- GetLastError());
-
- // Get the current settings of the COMM port
- success = GetCommState(comHandle, &dcb);
- if (!success)
- ErrorHandler("In GetCommState",
- GetLastError());
-
- // Modify the baud rate, etc.
- dcb.BaudRate = 2400;
- dcb.ByteSize = 8;
- dcb.Parity = NOPARITY;
- dcb.StopBits = ONESTOPBIT;
-
- // Apply the new comm port settings
- success = SetCommState(comHandle, &dcb);
- if (!success)
- ErrorHandler("In SetCommState",
- GetLastError());
-
- // Change the ReadIntervalTimeout so that
- // ReadFile will return immediately. See
- // help file
- timeouts.ReadIntervalTimeout = MAXDWORD;
- timeouts.ReadTotalTimeoutMultiplier = 0;
- timeouts.ReadTotalTimeoutConstant = 0;
- timeouts.WriteTotalTimeoutMultiplier = 0;
- timeouts.WriteTotalTimeoutConstant = 0;
- SetCommTimeouts( comHandle, &timeouts );
-
- // Set the Data Terminal Ready line
- EscapeCommFunction(comHandle, SETDTR);
-
- // Send an "at" command to the modem
- // Be sure to use \r rather than \n
- strcpy(str, "at\r");
- success = WriteFile(comHandle, str, strlen(str),
- &numWrite, 0);
- if (!success)
- ErrorHandler("In WriteFile", GetLastError());
-
- // Wait 2 seconds and then retrieve from the
- // modem
- Sleep(2000);
- success = ReadFile(comHandle, str,
- 100, &numRead, 0);
- if (!success)
- ErrorHandler("In ReadFile", GetLastError());
-
- // Print the string received
- cout << numRead << endl;
- str[numRead]='\0';
- cout << str << endl;
-
- // Clear the DTR line
- EscapeCommFunction(comHandle, CLRDTR);
-
- CloseHandle(comHandle);
- }
-