⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rs232_sub.cpp

📁 《Windows CE .NET嵌入式工业用控制器及自动控制系统设计》的源代码
💻 CPP
字号:
/*****************************************************************************/
/* Subroutine: RS232C common subroutine                                      */
/*                                                                           */
/* COPYRIGHT 2003 BY HUNG-TSAIR YEH                                          */
/*     Date :   2003 -04 - 15   designed  V1.0                               */
/*                                                                           */
/*                                           Desgined by Yeh Hung-Tsair      */
/*****************************************************************************/
#include "stdafx.h"
#include  <stdio.h>
#include  <string.h>
#include  <ctype.h>

#define DTRDSR       0x01
#define RTSCTS       0x02
#define XONXOFF      0x04
#define BEL       0x07
#define BS        0x08
#define LF        0x0A
#define CR        0x0D
#define XON       0x11
#define XOFF      0x13
#define STX       0x02
#define ETX       0x03
#define MAX_PORT     8

static  HANDLE  PORT_HD[MAX_PORT];
/*...........................................................................*/
/* Open COM port                                                            */
/*...........................................................................*/
BOOL seropen( int nPort, int nBaud, char parity, int data_bit, int stop_bit, int flow)
{

//  DWORD dwError;
  DCB PortDCB;
  COMMTIMEOUTS CommTimeouts;
  HANDLE  m_hPort;
  CString  PortName, error;

  // Open the serial port.
  PortName.Format(_T("COM%d:"), nPort);
  m_hPort = CreateFile (PortName, // 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 ( m_hPort == INVALID_HANDLE_VALUE  )
  {
    // Could not open the port.
    error.Format(_T("Unable to open port "));
	error= error + PortName;
    MessageBox (NULL, error, _T("RS232C SUB."), MB_OK);
//    dwError = GetLastError ();
    return false;
  }

  PortDCB.DCBlength = sizeof (DCB);

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

  // Change the DCB structure settings.
  PortDCB.BaudRate = nBaud;              // Current baud
  PortDCB.fBinary = TRUE;               // Binary mode; no EOF check
  if(flow==TRUE)
  {
  PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control
  PortDCB.fDtrControl = DTR_CONTROL_ENABLE;
  }
  else
  {
  PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control
  PortDCB.fDtrControl = DTR_CONTROL_DISABLE;
  }

// SW On for Modem set
  if(flow==TRUE)
  {
  PortDCB.fOutX = TRUE;                // No XON/XOFF out flow control
  PortDCB.fInX = TRUE;                 // No XON/XOFF in flow control
  }
  else
  {
  PortDCB.fOutX = FALSE;                // No XON/XOFF out flow control
  PortDCB.fInX = FALSE;                 // No XON/XOFF in flow control
  }
                                        // DTR flow control type
  PortDCB.fDsrSensitivity = FALSE;      // DSR sensitivity
  PortDCB.fTXContinueOnXoff = TRUE;     // XOFF continues Tx
  PortDCB.fErrorChar = FALSE;           // Disable error replacement
  PortDCB.fNull = FALSE;                // Disable null stripping

// NoneRTSON
//  PortDCB.fOutxCtsFlow = FALSE;         // No CTS output flow control
//  PortDCB.fRtsControl = RTS_CONTROL_ENABLE;
// Modem set RTSCTS
  if(flow==TRUE)
  {
  PortDCB.fOutxCtsFlow = TRUE;         // No CTS output flow control
  PortDCB.fRtsControl = RTS_CONTROL_HANDSHAKE;
  }
  else
  {
  PortDCB.fOutxCtsFlow = FALSE;         // No CTS output flow control
  PortDCB.fRtsControl = RTS_CONTROL_DISABLE;
  }
                                        // RTS flow control
  PortDCB.fAbortOnError = FALSE;        // Do not abort reads/writes on
                                        // error
  PortDCB.ByteSize = data_bit;                 // Number of bits/byte, 4-8

  PortDCB.fParity = TRUE;               // Enable parity checking
  if(parity=='N')
	PortDCB.Parity = NOPARITY;            // 0-4=no,odd,even,mark,space
  else if(parity=='O')
	PortDCB.Parity = ODDPARITY;            // 0-4=no,odd,even,mark,space
  else if(parity=='E')
	PortDCB.Parity = EVENPARITY;            // 0-4=no,odd,even,mark,space
  else
	PortDCB.Parity = NOPARITY;            // 0-4=no,odd,even,mark,space

  if(stop_bit==1)
	PortDCB.StopBits = ONESTOPBIT;        // 0,1,2 = 1, 1.5, 2
  else if(stop_bit==2)
	PortDCB.StopBits = TWOSTOPBITS;        // 0,1,2 = 1, 1.5, 2
  else
	PortDCB.StopBits = ONESTOPBIT;        // 0,1,2 = 1, 1.5, 2

  // Configure the port according to the specifications of the DCB
  // structure.
  if (!SetCommState (m_hPort, &PortDCB))
  {
    // Could not create the read thread.
    error.Format(_T("Unable to configure the serial port "));
	error= error + PortName;
    MessageBox (NULL, error, _T("RS232C SUB."), MB_OK);
//    dwError = GetLastError ();
    return FALSE;
  }

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

  // Change the COMMTIMEOUTS structure settings.
//  CommTimeouts.ReadIntervalTimeout = (DWORD)(( 3.5 * 10.0 * 1000) / nBaud );
  CommTimeouts.ReadIntervalTimeout = 2;   // 2 msec.
  CommTimeouts.ReadTotalTimeoutMultiplier = 1;
  CommTimeouts.ReadTotalTimeoutConstant = 2;
  CommTimeouts.WriteTotalTimeoutMultiplier = 1;
  CommTimeouts.WriteTotalTimeoutConstant = 2;

  // Set the time-out parameters for all read and write operations
  // on the port.
  if (!SetCommTimeouts (m_hPort, &CommTimeouts))
  {
    // Could not create the read thread.
    error.Format(_T("Unable to set the time-out parameters "));
	error= error + PortName;
    MessageBox (NULL, error, _T("Modem Comm."), 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 (m_hPort, SETDTR);
  EscapeCommFunction (m_hPort, SETRTS);

  PORT_HD[nPort-1]= m_hPort;
  return true;

}
/*...........................................................................*/
/* Close COM port                                                            */
/*...........................................................................*/
BOOL serclose(int nPort )
{
  HANDLE  m_hPort;

  m_hPort= PORT_HD[nPort-1];
  if (m_hPort != NULL)
  {
    // Close the communication port.
	EscapeCommFunction (m_hPort, CLRDTR);
	EscapeCommFunction (m_hPort, CLRRTS);
	Sleep(100);
	CloseHandle (m_hPort);
        PORT_HD[nPort-1] = NULL;
	return TRUE;
  }
  else
  {
	MessageBox(NULL, _T("Port is already close"), _T("RS232C SUB."), MB_OK);
	return FALSE;
  }

}
/*...........................................................................*/
/* Write n byte to COM port                                                  */
/*...........................................................................*/
int serwrite(int nPort, char *data, int len)
{
  DWORD dwBytesWritten;
  HANDLE  m_hPort;

  m_hPort= PORT_HD[nPort-1];

  dwBytesWritten= 0;
  if( !WriteFile( m_hPort, data, len, &dwBytesWritten, NULL))
    return(0);
  else
    return((int)dwBytesWritten);

}
/*...........................................................................*/
/* Write one byte to COM port                                                */
/*...........................................................................*/
BOOL sersend(int nPort, char Byte)
{
  DWORD dwBytesWritten, len;
  HANDLE  m_hPort;

  m_hPort= PORT_HD[nPort-1];
  char data[10];

  dwBytesWritten= 0;
  len= 1;
  data[0]= Byte;
  if( !WriteFile( m_hPort, data, len, &dwBytesWritten, NULL))
    return TRUE;
  else
    return FALSE;

}
/*...........................................................................*/
/* read one byte from COM port                                               */
/*...........................................................................*/
short serrecv(int nPort)
{
  DWORD	read = 0;
  WORD    data;
  BYTE input = NULL;
  HANDLE  m_hPort;

  m_hPort= PORT_HD[nPort-1];

  if(m_hPort == NULL ) return( -1);
  if( !ReadFile(m_hPort, &input, 1, &read, NULL) || (read != 1) )
     return -1;
  else
  {
     data= input;
     return(data);
  }

}
/*...........................................................................*/
/* read n byte from COM port                                               */
/*...........................................................................*/
int serread(int nPort, void *buffer, int limit )
{
  HANDLE  m_hPort;

  m_hPort= PORT_HD[nPort-1];

  if( m_hPort == NULL ) return( 0 );

  BOOL bReadStatus;
  DWORD dwBytesRead, dwErrorFlags;
  COMSTAT ComStat;

  ClearCommError( m_hPort, &dwErrorFlags, &ComStat );
  if( !ComStat.cbInQue ) return( 0 );

  dwBytesRead = (DWORD) ComStat.cbInQue;
  if( limit < (int) dwBytesRead ) dwBytesRead = (DWORD) limit;

  bReadStatus = ReadFile( m_hPort, buffer, dwBytesRead, &dwBytesRead, NULL);
  if( !bReadStatus )  return( 0 );
  else	return( (int) dwBytesRead );

}
/*...........................................................................*/
/* flush COM port buffer area                                               */
/*...........................................................................*/
void serflush(int nPort)
{
  HANDLE  m_hPort;

  m_hPort= PORT_HD[nPort-1];
  if(  m_hPort == NULL ) return;

  PurgeComm(m_hPort, PURGE_TXABORT | PURGE_RXABORT |
		               PURGE_TXCLEAR | PURGE_RXCLEAR );
  return;
}
/*...........................................................................*/
/* check lenght of received byte in input buffer                             */
/*...........................................................................*/
int serloc(int nPort)
{
  HANDLE  m_hPort;

  m_hPort= PORT_HD[nPort-1];
  if(  m_hPort == NULL ) return( 0 );

  DWORD dwErrorFlags;
  COMSTAT ComStat;

  ClearCommError( m_hPort, &dwErrorFlags, &ComStat );
  if( !ComStat.cbInQue ) return( 0 );
  else return(ComStat.cbInQue);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -