A vc serial port written by Indians and an Indian vc serial port

Source: Internet
Author: User

A vc serial port written by Indians and an Indian vc serial port

Software Introduction

A project written by IndiansVC serial port(AlsoVC serial control), And he also writes it in combination with this class.VC Serial CommunicationSome basic knowledge, such as how to useVC opens the serial port, How to configure the serial port, read the serial port, write the serial port, and so on.

This class is a bit special, it does not use the event-driven principle, it works as a query.

Introduction:

It is very difficult for VC programmers who have never been familiar with serial communication. I searched for serial communication information on codeguru.com a long time ago and got a lot of help, since then, it has been my dream to write a simple and easy-to-use VC serial class.

After seven months of practical experience in serial communication programming, I wrote a simple Serial Interface Class Based on API implementation, before introducing this serial port category, I would like to introduce the basic knowledge of VC serial port communication.

Serial Communication basics:

The transmission of each byte in serial communication is carried out in serial mode. When the transmission is low, it is sent first. A "packet" starts from "Start bit" + "Data bit" + "parity bit" (not required) + "Stop bit.

The parity bit is optional. It is used for error detection. You can set whether to enable the parity check in the software, and you can also choose which verification method to enable, such as "ODD" verification (ODD) or EVEN verification (EVEN ).

The procedure for a PC to send and receive data through a serial port is as follows:

  1,

Open serial port

  2, Configure serial communication parameters, such as baud rate, verification method, and number of data digits.
  3, Set communication timeout
  4, Write Data
  5, Read data
  6, Close serial port

 

Use VC to open the serial port:

Open the serial port can be achieved by using the API function CreateFile (), there are two methods to open the serial port, overlapping I/O (OVERLAPPED) and non-overlapping (NON-OVERLAPPED) method (in fact, the two methods correspond to the asynchronous and synchronous communication methods of the serial port respectively-VC serial port communication technology network note ). The CSerialCom class works in non-overlapping (NON-OVERLAPPED) mode (I .e. synchronous communication mode) and supports querying MSDN for more messages about OVERLAPPED and NON-OVERLAPPED.

Serial Port Configuration:

The most important topic in VC serial communication programming is how to use the DCB structure to configure the serial port. It is a common mistake for most people to fill the DCB structure incorrectly, generally, this problem occurs after the serial communication program is compiled because the structure is not properly filled. When using the CreateFile () function to open the serial port, we need to configure the baud rate, verification method, data bit, and stop bit of the serial port.

Set the timeout time:

You must use the COMMTIMEOUTS structure to set the timeout time each time you open the serial port. If this structure is not set, the communication will be subject to the timeout time set by default or the last time you open the serial port.

Serial Port writing:

The WriteFile () function can implement this function. Before executing this action, you must enable and configure the serial port.

Read Serial Port:

This function can be implemented using ReadFile (). Similarly, you must enable and configure the serial port before executing this action.

Close the serial port:

If you no longer use an opened serial port, you must close it to release this serial port resource so that other programs can use this serial port resource again, outside of non-overlapping I/O (NON-OVERLAPPED) in this mode, the serial port cannot be accessed by other programs or other threads in the same program. You can use the CloseHandle () function to disable the serial port. The CloseHandle () function has only one parameter, which is the set handle returned when CreateFile () opens the serial port.

 

CSerialCom serial port

The CSerialCom class uses six functions to implement the functions mentioned above. They are:

BOOL CSerialCom::OpenPort(CString portname)  {  portname= "//./" + portname;   hComm = CreateFile(portname,                        GENERIC_READ | GENERIC_WRITE,                        0,                        0,                        OPEN_EXISTING,                        0,                        0);  if(hComm==INVALID_HANDLE_VALUE){      return false;}      else     return true;   }  

 

The OpenPort () member function is used to open the serial port. Only one parameter is required, that is, the serial port name, such as "COM1" and "COM2 ".

 

BOOL CSerialCom::ConfigurePort(DWORD BaudRate, BYTE ByteSize,                                  DWORD fParity, BYTE Parity, BYTE StopBits)  {      if((m_bPortReady = GetCommState(hComm, &m_dcb))==0)      {          MessageBox("GetCommState Error","Error",MB_OK+MB_ICONERROR);          CloseHandle(hComm);          return false;      }            m_dcb.BaudRate =BaudRate;      m_dcb.ByteSize = ByteSize;      m_dcb.Parity =Parity ;      m_dcb.StopBits =StopBits;      m_dcb.fBinary=TRUE;      m_dcb.fDsrSensitivity=false;      m_dcb.fParity=fParity;      m_dcb.fOutX=false;      m_dcb.fInX=false;      m_dcb.fNull=false;      m_dcb.fAbortOnError=TRUE;      m_dcb.fOutxCtsFlow=FALSE;      m_dcb.fOutxDsrFlow=false;      m_dcb.fDtrControl=DTR_CONTROL_DISABLE;      m_dcb.fDsrSensitivity=false;      m_dcb.fRtsControl=RTS_CONTROL_DISABLE;      m_dcb.fOutxCtsFlow=false;      m_dcb.fOutxCtsFlow=false;       m_bPortReady = SetCommState(hComm, &m_dcb);      if(m_bPortReady ==0)      {          MessageBox("SetCommState Error","Error",MB_OK+MB_ICONERROR);          CloseHandle(hComm);          return false;      }      return true;  }  

 

The ConfigurePort () function configures the serial port. The required parameters are as follows:

DWORD BaudRate

DWORD BaudRate is used to describe the baud rate used for serial communication. When the parameter is CBR_9600, the baud rate is 9600bps. The standard baud rates supported by the PC are CBR_110, CBR_300, CBR_600, CBR_1200, CBR, CBR_9600, CBR_14400, CBR_19200, CBR_38400, CBR_56000, CBR_57600, CBR_115200, CBR_128000, CBR_256000

BYTE ByteSize

This parameter describes the number of bits. The standard value is 8 or 4.

DWORD fParity

Parity switch. If this parameter is TRUE, parity is enabled. If this parameter is FALSE, parity is disabled.

BYTE Parity

Verification Method. Optional methods:

 

EVENPARITY

  MARKPARITY
  NOPARITY
  ODDPARITY
  SPACEPARITY

 

BYTE StopBits

The number of Stop bits. The optional values are as follows:

 

ONESTOPBIT

  ONE5STOPBITS
  TWOSTOPBITS

 

Note: The ConfigurePort () function assumes that the serial port Throttling is completed by hardware, and the software does not detect the CTS/RTS and Xon/Xoff statuses during data sending and receiving, you can modify the DCB structure to enable software flow control.

 

BOOL CSerialCom::SetCommunicationTimeouts(DWORD ReadIntervalTimeout,                                             DWORD ReadTotalTimeoutMultiplier,                                             DWORD ReadTotalTimeoutConstant,                                             DWORD WriteTotalTimeoutMultiplier,                                             DWORD WriteTotalTimeoutConstant)  {      if((m_bPortReady = GetCommTimeouts (hComm, &m_CommTimeouts))==0)          return false;      m_CommTimeouts.ReadIntervalTimeout =ReadIntervalTimeout;      m_CommTimeouts.ReadTotalTimeoutConstant =ReadTotalTimeoutConstant;      m_CommTimeouts.ReadTotalTimeoutMultiplier =ReadTotalTimeoutMultiplier;      m_CommTimeouts.WriteTotalTimeoutConstant = WriteTotalTimeoutConstant;      m_CommTimeouts.WriteTotalTimeoutMultiplier =WriteTotalTimeoutMultiplier;      m_bPortReady = SetCommTimeouts (hComm, &m_CommTimeouts);            if(m_bPortReady ==0)      {          MessageBox("StCommTimeouts function failed",                     "Com Port Error",MB_OK+MB_ICONERROR);          CloseHandle(hComm);          return false;      }      return true;  } 

The SetCommunicationTimeouts () member function is used to set the read/write timeout. The required parameters are as follows:

DWORD ReadIntervalTimeout

Set the maximum interval between two characters received when reading the serial port, in milliseconds. When ReadFile () is executed, ReadFile () returns immediately if the interval between two characters exceeds this value. If this parameter is set to zero, it indicates that this feature is not enabled.

ReadTotalTimeoutConstant

Constant used to calculate the total read operation timeout. This parameter is added to ReadTotalTimeoutMultiplier during each read operation. If the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant parameters are both zero, the total timeout calculation function is not enabled.

ReadTotalTimeoutMultiplier

Used to save the total read operation timeout

WriteTotalTimeoutConstant

Constant used to calculate the total write operation timeout. Similar to ReadTotalTimeoutConstant.

WriteTotalTimeoutMultiplier

Used to save the total write operation timeout. If the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant parameters are both zero, the total write operation timeout feature is disabled.

For example, if you want to transmit a data packet and set the write operation timeout to 500 ms (the maximum sending interval between each character), you can use the set timeout member function to set the content as follows: setCommunicationTimeouts (0,500, 0, 0); if the setting is successful, the function returns true; otherwise, false is returned.

BOOL CSerialCom::WriteByte(BYTE bybyte)  {      iBytesWritten=0;      if(WriteFile(hComm,&bybyte,1,&iBytesWritten,NULL)==0)          return false;      else           return true;  } 

 

The WriteByte () member function is used to write data to the serial port.

 

BOOL CSerialCom: ReadByte (BYTE & resp) {BYTE rx; resp = 0; DWORD dwBytesTransferred = 0; if (ReadFile (hComm, & rx, 1, & dwBytesTransferred, 0 )) {if (dwBytesTransferred = 1) {resp = rx; return true ;}} return false ;}View Code

 

The ReadByte () member function implements the read serial port function. If you know that data is sent, you may use ReadByte () to read data. If you do not know when data is sent, you can call this function cyclically. When no data is received beyond the time-out period, ReadByte () will return automatically. In actual application, the communication parties may use a certain protocol. At this time, there is generally a sign indicating the end of the Communication packet. For example, the 3964 Protocol end is 'etx ', you may use it to determine whether the transmission is complete.

void CSerialCom::ClosePort()  {  CloseHandle(hComm);  return;  }  

 

The ClosePort () member function is used to close an opened serial port.

How to Use the CSerialCom class

Preparations before using the CSerialCom class:

  1,

Copy the files SerialCom. h and SerialCom. cpp to the project directory.

  2, Import these two files in the VC Project
  3, Add the # include "SerialCom. h" sentence code to the proper position of the program.
  4, Create an instance of the CSerialCom class

Now you can call the CSerialCom class member function for serial communication. The procedure is as follows:

  1. 1 // open the serial port. You need to check the function return value to determine whether the serial port is correctly opened 2 port. OpenPort (); 3 4 // configure the serial port. You need to check the function return value to determine whether the 5 port. ConfigurePort (); 6 7 // set the timeout value. You need to check the function return value to determine whether the 8 port is correctly configured. setCommunicationTimeouts (); 9 10 // write the serial port. Since only one byte can be written at a time, you need to call this function multiple times to send the string to the end of the 11 port. writeByte (); 12 13 // read the serial port. Since only one byte can be read at a time, it is generally necessary to call this function multiple times to read the string 14 port. readByte (); 15 16 // close the serial port 17 port. closePort ();

    : Http://pan.baidu.com/s/1mghzhvq (a VC ++ serial class _ serialport + CSerialCom_demo compiled by Indians)

  2. Reference: http://cs.nju.edu.cn/yangxc/dcc2003.files/jszc-sub/comif-35.htm
  3. Http://www.codeguru.com/cpp/i-n/network/serialcommunications/article.php/c2483/A-communication-class-for-serial-port.htm
  4. Http://www.vc-rs232.com/html/VC_SSCOM_Control/2011/0117/34.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.