An Indian compiled by the VC serial port class

Source: Internet
Author: User

Http://www.cnblogs.com/lwngreat/p/4098374.html

Software Introduction

An Indian compiled by the VC serial port Class (also a VC serial control ), he also cooperated with this class to write a VC serial communication of some basic knowledge, such as how to open the serial port with VC , how to configure the serial port, Read the serial port, write serial port and so on.

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

Introduction:

No contact with the serial communication of the VC programmer seems very difficult, a long time ago I searched the codeguru.com on the serial communication related information has been very big help, since then can write a simple and easy to use VC serial port class is my dream.

After seven months of practical experience in serial communication programming, I have written a simple API based on the implementation of the serial port class, before introducing this serial port class first introduced the VC serial communication basic knowledge.

Serial Communication Basics:

Serial communication Each byte of the transmission in a serial manner, the transmission of low-level first sent, a "packet" by "Start bit" + "data bit" + "parity bit" (not required) + "stop bit" composition.

The parity bit is optional, it is used for error detection, you can set whether parity is enabled in the software, and you can choose which check mode to enable, such as "odd" check (ODD) or "even" check (even).

The process by which a PC transmits and receives data via a serial port is as follows:

1.

Open the serial port

2. Configuration of serial communication parameters, such as: Baud rate, check mode, data bits, etc.
3. Setting the communication time-out period
4. Write Data
5. Read data
6. Close the serial port

Open the serial port with VC:

Open the serial port can be implemented with API function CreateFile (), open the serial port there are two ways, respectively, overlapping I/O (OVERLAPPED) and non-overlapping ( non-overlapped) Way (in fact, these two methods correspond to the serial port asynchronous and synchronous communication mode-VC serial Communication Technology network note). The cserialcom class works in non-overlapping (non-overlapped) mode (that is, synchronous communication mode), and more OVERLAPPED and non-overlapped messages can be queried for MSDN.

Serial configuration:

VC Serial Communication Program writing the most important topic is how to use the DCB structure to configure the serial port, the DCB structure is not properly filled is the majority of people often anti-crime, usually the serial communication program after the emergence of such a problem is because the structure is not properly populated. When using the CreateFile () function to open the serial port, we need to configure the serial port baud rate, check mode, data bit, stop bit and so on.

To set the timeout period:

Each time you open the serial port, you must use the commtimeouts structure to set the time-out period, if this structure is not set, the communication will be the default or last opened this serial port when the time-out is set.

Write Serial:

The WriteFile () function implements this function by first opening and configuring the serial port before performing this action.

Read Serial:

this can be achieved with ReadFile (), and the serial port must be opened and configured before performing this action.

Close the serial port:

No longer use the already opened serial port must be shut down to release this serial port resources, so that other programs may use this serial resources, outside the non-overlapping I/O (non-overlapped) mode of the serial port in the open period can not be accessed by other programs or other threads within the same program. Use the CloseHandle () function to turn off the serial port, the CloseHandle () function has only one parameter, which is the set handle returned when the serial port is opened by CreateFile ().

Cserialcom Serial Port Class

The Cserialcom class uses six functions to implement the above mentioned functions, respectively:

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

Openport () member function is used to open the serial port, it needs only one parameter, is the serial name, such as "COM1", "COM2".

BOOL Cserialcom::configureport (DWORD baudrate, Byte ByteSize, DWORD fparity, Byte Parity, BYTE stopbits) {if (M_bportready = Getcommstate (Hcomm, &M_DCB)) ==0) {MessageBox ("Getcommstate E          Rror "," 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, and the required parameters are as follows:

DWORD baudrate

The DWORD baudrate is used to describe the baud rate used by the serial communication, and when this parameter is cbr_9600, the baud rate for the 9600BPS,PC machine supports the standard baud rate:cbr_110, cbr_300, cbr_600, cbr_1200, cbr_2400,cbr_4800,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 data bits, with a standard value of 8 or 4.

DWORD fparity

Parity switch, if this parameter is True (true) turns on parity, False (false) turns off parity.

BYTE Parity

Check mode, the following options are available:

Evenparity

Markparity
Noparity
Oddparity
Spaceparity

BYTE StopBits

The number of stop bits is as follows:

Onestopbit

One5stopbits
Twostopbits

Note: theconfigureport () function assumes that the flow control of the serial port is done by the hardware, and the software does not detect the Cts/rts and Xon/xoff states during the sending and receiving of data, and you can modify the DCB structure to enable software flow control.

123456789101112131415161718192021222324 BOOLCSerialCom::SetCommunicationTimeouts(DWORD ReadIntervalTimeout,                                            DWORDReadTotalTimeoutMultiplier,                                            DWORDReadTotalTimeoutConstant,                                            DWORDWriteTotalTimeoutMultiplier,                                            DWORDWriteTotalTimeoutConstant)     if((m_bPortReady = GetCommTimeouts (hComm, &m_CommTimeouts))==0)         returnfalse    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        returntrue}

  The setcommunicationtimeouts () member function is used to set the read/write timeout time, which requires the following parameters:

DWORD ReadIntervalTimeout

When setting up a read serial port, the maximum time interval of two characters is received, in milliseconds. During the execution of ReadFile (), a time interval of two characters is exceeded, andReadFile () returns immediately. If this parameter is set to zero, it indicates that this attribute is not enabled.

ReadTotalTimeoutConstant

Constant that calculates the total time-out for the read operation. During each read operation, this parameter is added to readtotaltimeoutmultiplier. If both ReadTotalTimeoutMultiplier and readtotaltimeoutconstant two parameters are zero, the total timeout calculation function is not enabled.

ReadTotalTimeoutMultiplier

That is used to save the total time-out of the read operation

WriteTotalTimeoutConstant

Constant that is used to calculate the total write operation time-out. similar to ReadTotalTimeoutConstant.

WriteTotalTimeoutMultiplier

The total write operation time-out is used, if both the WriteTotalTimeoutMultiplier and writetotaltimeoutconstant two parameters are zero, indicating that the total write time timeout attribute is not enabled.

For example, you need to send a packet, set the write operation time-out to 500ms (the maximum interval of time between each character), you can set the timeout member function, the content is:setcommunicationtimeouts (0, 0,0, 0); If the setting succeeds, the function returns True, otherwise false.

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.

View Code

ReadByte () member function to implement the Read serial function, if you know that there is data sent, you may use readbyte () to read the data, if you do not know when the data sent over, you can periodically call this function, when the data is not received after the timeout period, ReadByte () automatically returns. In the actual application, the communication parties may be in some kind of protocol, at this time there is usually a sign that the end of the communication packet, such as the 3964 protocol Terminator is ' ETX ', you may use it to determine whether the transmission is over.

void Cserialcom::closeport ()  {  CloseHandle (hcomm);  return;  }  

The Closeport () member function is used to close an already open serial port.

How to use the Cserialcom class

Preparation before using the Cserialcom class:

1.

Copy SerialCom.h and SerialCom.cpp two files to the directory where the project is located

2. Import these two files in VC project
3. Add # include "SerialCom.h" sentence code to the appropriate location of the program
4. Create an instance of the Cserialcom class

It is now possible to call the Cserialcom class member function for serial communication, and the operation flow is as follows:

    1. 1//Open the serial port. You need to check the function return value to determine if the serial port is open   2 port correctly. Openport ();    3   4//Configure the serial port. The function return value needs to be checked to determine whether the 5 port is configured correctly   . Configureport ();     6   7//Set timeout time. The function return value needs to be checked to determine whether the 8 port is configured correctly   . Setcommunicationtimeouts ();    9        10//serial port, because only one byte can be written at a time, it is generally necessary to call this function more than once to send a string that needs to be sent out of  port. WriteByte ();       13//Read the serial port, because one byte can be read at a time, it is generally necessary to call this function multiple times to read the string that need to read the  port. ReadByte ();  16//Close serial port  . Closeport ();

      : http://pan.baidu.com/s/1mgzH428

  1. (An Indian-compiled VC + + serial class _serialport+cserialcom_demo)

  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

An Indian compiled by the VC serial port class

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.