[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 264
  • Last Modified:

Need to open and read and write to a com port using win 2000 with Visual C++ 6.0

I am a begining  programmer using visual C++ 6.0.  I want to be able to read and write data bytes in  and out of my com1 port.  I am operating on a win 2000 OS.  I have read some solutions and read lots of links on how to create comunication to a com port.  I am not familar with MFC functions and dont mind working with no GUI.  I have compiled the following code and got no error but when trying to build it, i get the following error. (see below)  Is there an optinon that I must change in my project with the compiler..please try this code and see if you could help me out.

////////////////////////////////////////////////////////////////////////////////


#ifndef SERIAL_H


#define SERIAL_H

// Global Variables
static HANDLE hPort;            // Serial port handle
static HANDLE hReadThread;      // Handle to the read thread
static LPTSTR lpszDevName;      // Communication port name

//serialport.cpp

BOOL PortInitialize (LPTSTR);
BOOL PortClose (HANDLE);
void PortWrite (BYTE);
DWORD PortRead ();

#end


///////////////////////////////////////////////////////////////////////////

/*
*
*      serialreader.cpp
*  
*      Simple Serial Reader Demonstrator
*
*
*/

#include <windows.h>
#include "serialport.h"
#include <iomanip.h>
 
/***********************************************************************

  WINMAIN (      HINSTANCE hInstance,
                              HINSTANCE hPrevInstance,
                              LPTSTR    lpCmdLine,
                              int       nCmdShow)

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

int WINAPI WinMain(      HINSTANCE hInstance,
                              HINSTANCE hPrevInstance,
                              LPTSTR    lpCmdLine,
                              int       nCmdShow)
{

      DWORD dwError;

      hPort = INVALID_HANDLE_VALUE;            // Serial port handle
      
      lpszDevName = TEXT("COM1:");

      // Initialize the port.
  if (!PortInitialize (lpszDevName))
  {
    return 0 ;
  }

  cout<<"Reading from the Serial Port\n\n";

  if(PortRead())
  {
    // Could not create the read thread.
   
        cout<<"Unable to create the read thread";
        MessageBox (NULL, TEXT("Unable to create the read thread"),
                TEXT("Error"), MB_OK);
    dwError = GetLastError ();
    return 0;
  }
 
  if (PortClose(hPort))
  {
      MessageBox (NULL, TEXT("Comm Port already Closed"),
                TEXT("Error"), MB_OK);
}
 

  return 0 ;

}


////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////
/*
*
*      serialport.cpp
*  
*      Simple Serial Port Functions
*
*      
*/

#include <windows.h>
#include "serialport.h"
#include <iomanip.h>

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

  PortInitialize (LPTSTR lpszPortName)

***********************************************************************/
BOOL PortInitialize (LPTSTR lpszPortName)
{
  DWORD dwError;
  DCB PortDCB;                              // Port Control Settings Structure
  COMMTIMEOUTS CommTimeouts;      // Comm port timeout structure

  // 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.
      cout<<"Unable to open the port";
      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/byte, 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.
        cout<<"Unable to configure the serial port";
    MessageBox (NULL, 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 = 0;  
  CommTimeouts.ReadTotalTimeoutConstant = 0;    
  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 (NULL, 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);

  return TRUE;
}


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

  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;
}

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

  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 ();
  }
}


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

  PortRead()

  This function loops continously simple to demonstrate serial reading
  in a specific apllication of reading from the serial port a quit
  method should be implemented.

***********************************************************************/
DWORD PortRead ()
{
  BYTE Byte;
  DWORD dwCommModemStatus,
        dwBytesTransferred;
 
  // 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)
          cout<<"%c"<<Byte;

      } while (dwBytesTransferred == 1);
    }

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

  }

  return 0;
}

/////////////////////////////////////////////////////////////////////////////////////////////////


Error when building ->

Compiling...
serialport.cpp
Linking...
LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
Debug/serialreader.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.

serialreader.exe - 2 error(s), 0 warning(s)


0
tony_n
Asked:
tony_n
1 Solution
 
jkrCommented:
>>LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main

That's because your project is configured as a console application. Go to your project settings and pick the Link tab. There, in the text field at the bottom, locate '/subsystem:console' and change that to read '/subsystem:windows'. Be sure to do that for both the Debug and the Release configuration.
0
 
tony_nAuthor Commented:
I was able to change teh subsystem:console to windows.  Where are the Debug and Release configuration options?  I could not find those to change.  Please respond when available
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now