Serial programming of MFC under "Turn" VS2010

Source: Internet
Author: User

Introduction to Serial communication

In general, computers have one or more serial ports that provide a channel for data transmission and communication between the external device and the PC, acting as an interpreter between the CPU and the peripheral. When character data is sent from the CPU to the peripheral, these character data are converted to serial bitstream data, and when the data is received, the bitstream data is converted to the character data passed to the CPU, further speaking, in terms of the operating system, Windows uses the communication driver (COMM. DRV) calls API functions to send and receive data, and when API functions are invoked with communication controls or declarations, they are interpreted by comm.drv and passed to the device driver. As a programmer, to write a communication program, you just need to know the interface of the Windows API communication function provided by the communication control, in other words, just set and monitor the properties and events of the communication control.

The serial port communication method generally has the following several kinds:

    1. Using the Windows API communication functions;
    2. Using Visual C + + standard communication functions _INP, _INPW, _INPD, _OUTP, _OUTPW, _outpd and so on directly to the serial port operation;
    3. Through Microsoft's serial communication control MSComm, it is an ActiveX control;
    4. The use of 3rd party-written communication classes, such as Mumega Technologies Company provided by the Cserail class;

I used the third method in the project development process--using the MSComm control to manipulate the serial port, the following is the note that I use this control.

Introduction to MSComm Controls

MSComm is an ActiveX control provided by Microsoft Corporation for simplifying serial port programming in Windows, and it provides a range of interfaces for the use of standard communication commands. The MSComm control transmits and receives data through the serial port (serial port), providing serial communication functionality to the application. In the popularity of visual programming today, we can easily in visual Basic (VB), Visual C + + (VC), Delphi and other languages and development platform application. There are two ways of handling data: event-driven (event-driver) and query (Inquire).

  Event-driven method : When designing a program using event-driven, the MSComm control triggers the OnComm event whenever a new character arrives, a port state changes, or an error occurs, and after the application captures the event, the You can take action by checking the CommEvent property of the MSComm control to learn about the event or error that occurred. The advantage of this method is that the program responds in time and has high reliability.

  Query Method : This method is suitable for smaller applications. In this case, each time the application finishes executing a serial port operation, the CommEvent property of the MSComm control is constantly checked to check the execution results or to check whether an event occurs. For example, when a program sends a command to a serial device, it may just wait for a specific response string to be received, instead of Nonalphanumeric immediately responding to and processing every word it receives.

Each MSComm control that is used corresponds to a serial port. If you need to access multiple serial ports in your application, you must use multiple MSComm controls, and you can modify the interrupt address of the serial address in the Windows Control Panel.

Common Properties for MSComm controls

    • Commport Property: Sets or returns the communication port number, which can be set to any value from 1 to 16;
    • Settings property: Sets or returns the baud rate, parity, data bit, and stop bit as a string;
    • PortOpen Property: Sets or returns the status of the communication port and the opening and closing of the port, either by setting the property to True or false to open or close the port;
    • Inbuffersize and Outbuffersize properties: Sets the amount of memory allocated for the receive and send buffers, in bytes, with default values of 1024byte and 512byte, respectively;
    • Inputlen property: Determines the number of characters you want to move out of the receive buffer, and when inputlen=0, removes all characters from the receive buffer at once;
    • Input property: Reads the data from the receive buffer and then removes the data from the buffer.
    • Output property: Passes the data to be sent to the send buffer.
    • inbuffercount and outbuffercount properties : Determine the number of characters that currently reside in the receive buffer waiting to be fetched and send buffers ready to be sent, both of which are set to 0, and the contents of the receive and send buffers are cleared;
    • Inputmode property: Sets the format to receive incoming data, set to 0 in text form, set to 1 in binary format;
    • Sthreshold Property : Save a OnComm event to generate the threshold value, the system set this property is 0, send data without generating OnComm event;
    • RThreshold Property : Sets the OnComm event that is triggered when a few characters are received, this system sets the property to 1, and each time a character is received, a OnComm event is generated;

MSComm Events for controls

The MSComm control uses only one event OnComm, using the 17 values of the property commevent to distinguish between different trigger times, mainly the following:

    • Commevent=1: The number of characters in the transmit buffer is less than sthreshold (the property value can be set);
    • commevent=2 : The receive buffer receives a rthreshold(set property value) character, which can be used to write the process of receiving data;
    • Commevent=3: CTS line is changed;
    • COMMEVENT=4: The DSR line is changed;
    • COMMEVENT=5: the CD line changes;
    • Commevent=6: The ringing signal is detected;

There are 10 other situations where communication errors occur, which is the error code.

Implementation of MSComm serial program based on MFC in VS2010

1. Registering MSComm controls

After I downloaded the MSComm control online, I placed it under the project directory and built a . bat batch file in the current directory with the following contents:

Copy. \\MSCOMM\\MSCOMM. SRG%windir%\system32copy. \\MSCOMM\\MSCOMM32. DEP%windir%\system32copy. \\MSCOMM\\MSCOMM32.oca%windir%\system32copy. \\MSCOMM\\mscomm32.ocx%windir%\ System32regsvr32 Mscomm32.ocx

Double-click the file to register the MSComm control.

2. Adding MSComm controls

First add the MSComm control to the VS2010 Toolbox, add the MFC-based ATL class for the project to that ActiveX control, and finally drag the MSComm control (phone icon) from the Toolbox to the dialog box. When you add a MSComm control to a dialog box, it will have white on the side, right-click the control, and select Edit Control to remove the white.

3. Adding control variables

Adds a control variable (member object) associated with the MSComm control in the main dialog box, which allows you to manipulate the serial port.

4, serial port information configuration and open the serial port

You can set MSComm control properties by right-clicking the MSComm Control on the dialog box template and selecting the Property menu item. In the modem communication program, set the "Control" property page handshaking item as "2-comrts", or the domestic part of the manufacturer modem can not communicate normally, other accept the default settings. You can also set the properties of a control by modifying the OnInitDialog () function of the dialog class. Refer to the detailed instructions on Comm Control in MSDN for details.

My program's serial port Setup code is as follows:

    Serial Port Settings **************************//m_ctrlcomm.put_commport (port);//select COM port m_ctrlcomm.pu T_inputmode (1);//input mode is binary mode m_ctrlcomm.put_inbuffersize (1024);//input buffer size is 1024byte m_ctrlcomm.put_outbuffersize (    512);//output buffer size is 512byte CString strbaudrate;    Strbaudrate.format (_t ("%ld"), baudrate); M_ctrlcomm.put_settings (strbaudrate+_t ("n,8,1"));//Set serial port parameters: 9600 baud rate, no parity check, 8 data bits, 1 stop bit if (!m_ctrlcomm.get_                PortOpen ()) {/* HANDLE m_hcom;          CString strcom;          Strcom.format (_t ("\\\\.\\com%d"), (int) (M_ctrlcomm.get__commport ())); The CreateFile function here can be used to create a system device file,//If the device does not exist or is occupied, an error is returned, that is, the following invalid_handle_value,//To determine usability.          See the introduction to MSDN in more detail.          m_hcom = CreateFile (strcom, 0, 0, 0, open_existing, file_attribute_normal, 0);              if (m_hcom = = INVALID_HANDLE_VALUE)//If the device is not available, or is used by another application in {int errornum=getlasterror (); if (errornum==2) StrcoM.format (_t ("Port%d does not exist"), (int) (M_ctrlcomm.get__commport ()));              else if (errornum==5) Strcom.format (_t ("Port%d is occupied"), (int) (M_ctrlcomm.get__commport ()));              AfxMessageBox (strcom); CloseHandle (m_hcom);          Close the file handle, followed by the control, not the API return,//This is because the serial port initialization encapsulated in another function inside the OnInitDialog call. } closehandle (m_hcom); Close the file handle, followed by the control, without API */try {M_ctrlcomm.put_portopen (true);//Open serial Port} C            Atch (COleDispatchException *e) {CString strerror; Strerror.format (_t ("Open serial port failed!            \n\nerror Number:%d \nerror Message:%s "), e->m_wcode,e->m_strdescription);            MessageBoxW (strerror,_t ("error hint"), mb_iconerror);        Return    }} else {//messagebox (_t ("Cannot open serial port!")); } m_ctrlcomm.put_rthreshold (1);//The OnComm event that receives data is raised whenever the serial receive buffer has extra or equal to 1 characters m_ctrlcomm.put_inputlen (0);// Sets the current receive area data length to 0 M_ctrlcomm.get_input ();//read-ahead buffer to empty residual data 

5. Serial data reading and writing

The reading and writing functions of the MSComm class are relatively simple:get_input () and put_output (). The function prototypes are Variant get_input () and void Put_output (const variant newvalue), all using variant types. But the PC is accustomed to string form when sending and receiving data. The variant type is consulted in MSDN, and a BSTR can be used to represent a string, but all of the BSTR contains wide characters, and only Windows NT supports wide characters, which Windows 9X does not support. So to complete a platform to adapt to the serial port application must solve this problem, here to use CByteArray solution.

To add the receive data function, double-click Comm Control in the dialog box, and accept the default function, the member function of the dialog class is Oncommmscomm (), and its approximate code is as follows:

Cdatatypeconverter DTC;    The phone icon may be half the white side to go, right click on the phone icon Click Edit Control can be removed    if (m_ctrlcomm.get_commevent () ==2)//event value of 2 means receive event    {        BYTE rxdata[255]={0};//set byte array        VARIANT variant_inp=m_ctrlcomm.get_input ();//Read buffer        COleSafeArray SAFEARRAY_INP = Variant_inp;//variant variable is converted to COleSafeArray variable        long len=safearray_inp. Getonedimsize ();//Get valid data length for        (long k=0;k<len;k++)            SAFEARRAY_INP. GetElement (&k,rxdata+k);//Convert to byte array        m_ctrlcomm.put_outbuffercount (0);//clear Send buffer        m_ctrlcomm.put_ InBufferCount (0);//Slide the receive buffer        SAFEARRAY_INP. Clear ();                    for (long k=0;k<len;k++)        {            BYTE bt = * (char*) (rxdata+k);//character-type short            int intdec= (int) bt;            CString STRTEMP=DTC. Dec2hex (INTDEC);            m_strdatarxtemp+=strtemp;//add to receive edit box corresponding string        }        m_strdatarx=m_strdatarxtemp;        M_strdatarxtemp= "";
}

Where the code for the Dec2hex () function is as follows:

CString cdatatypeconverter::D ec2hex (unsigned int intdec) {    CString strhex;    Char charhex[255];    sprintf (Charhex, "%x", Intdec);    Strhex=charhex;    if (Strhex.getlength () ==1)        strhex=_t ("0") +strhex;    return strhex;}

The code that sends the data is roughly as follows:

UpdateData (TRUE);//reads the contents of the edit box m_strdatatx//the surface of the sent string is in hexadecimal format CString m_strctrllightbl;m_strctrllightbl= " 55aa0aaa6b4310100000 ";//" 55aa0aaa6b4310100000 "    cdatatypeconverter DTC; COleVariant M_OLEVARIANT=DTC. Hexm2olevariant (M_STRCTRLLIGHTBL); M_ctrlcomm.put_output (m_olevariant);//Send data

where the Hexm2olevariant () function is defined as follows:

COleVariant cdatatypeconverter::hexm2olevariant (CString strhexm) {    BYTE bt[255];    Short int len=strhexm.getlength ();    short int length=0;    short int intdec;    for (int n=0,i=0;n<len-1;n+=2,i++)    {                Intdec=hex2dec (Strhexm.mid (n,2));        Bt[i]=char (INTDEC);        length=i+1;    }    CByteArray M_array;    M_array.removeall ();    M_array.setsize (length);    for (int i=0;i<length;i++)        m_array.setat (I,bt[i]);    Return COleVariant (M_array);}

Note: When receiving data, the RThreshold property is important because it affects the trigger condition of the OnComm event, and the RThreshold property can be set through the put_rthreshold () function in the program.

RELATED links:

VC + + Serial Programming (v) based on third-party class library: http://blog.csdn.net/nash635/article/details/5339704

Serial programming of MFC under "Turn" VS2010

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.