VC + + programming Simple serial host computer program

Source: Internet
Author: User

Reprint: http://blog.sina.com.cn/s/articlelist_1809084904_0_1.html

VC + + programming Simple serial host computer program

Serial communication, MCU and PC communication is often used in a way of communication, do interface, write the programming language of the computer program, compiling environment, and so on, VB, C #, LabVIEW and so on, I will be very few languages, C language used more, but has not found how to use C language to write serial communication computer program information, In the book management found the use of VC + + to write the serial host computer data, reference books, with their own rather crappy C + + write a simple serial host computer program, share, experience a single-chip computer and PC communication fun.


Compilation Environment: vc++6.0
Operating system: VMware virtual out of Windows XP


Program Implementation Features:
1, the PC initializes the COM1 port, uses the N81 method, the baud rate 57600 communicates with the monolithic microcomputer. The COM port number of the PC can be modified as follows:

Of course, can also be written by the PC software, through the button to select the COM port number, but this is simply a simple routine, it is not so complicated. COM1 port can be used, will prompt the serial port initialization is complete. Otherwise it will prompt the serial port has opened port already open, indicating that the serial port has been opened, is occupied.

2, click to start the conversion, the serial port will be sent to the microcontroller 0xaa, single-chip computer serial interrupt received 0XAA after the conversion of the ADC, and the conversion results ADCL, adch A total of two bytes of the results sent to PC,PC after the value conversion in the window display. (See figure at the end of the article)

3, in order to prevent the serial port is a occupy, click to close the serial port can be closed COM1, for other programs to use, click on the button to open the serial port, click to reopen COM1.

The program is written:
1. Open vc++6.0 to build the MFC Application based on dialog box test

2. Insert the MSComm control in the project: Engineering---add to Project->components and controls-> double-click registered ActiveX controls-> Select Microsoft Communications control, version 6.0->insert, added by default, you will find a more phone icon, which is added after the serial communication control.

4. Right-click Edit box to select Properties, set in style, tick multiple lines, scroll vertically, others can be by default.

    • Right-click the static text Selection property, and in the general settings, modify the caption.
    • Right-click the button pushbutton select Properties, in the general settings, modify the title.

After the modified interface is as follows, the "phone" flag will automatically disappear when the program writes out to run.

5, view and build the Class Wizard MFC Classwizard->member viariable, select classname for Ctestdlg class, control ID is MSCOMM1, double-click it, add control variable m_comm1 for it.
Similarly, select Idc_button2 to add the control variable m_serial.
(The Build Class Wizard can also right-click and select the Create Class Wizard in the popup shortcut menu)


At this point, the basic framework has come out, after compiling the run can see the interface as shown below. (Build all components, then build and execute)

6, click on the left side of the view window, you can switch in three modes, the third is to open our Source code window, the first is the class, the second is a form of resource view.

Select File View, expand Test files->header files, open testDlg.h, add the following code under global variables, and then save:
int gllen;//defines an integer scalar gllen that records the number of received data
CProgressCtrl * PBAR; A pointer to the progress bar to manipulate the progress bar
CString Strrxddata; edit box to display the text, record the previous conversion values

7, click Recourse View, expand TEST recourses->dialog, double-click Idd_test_dialog, Edit our main interface dialog box.
Double click on "Phone", pop Up the following dialog box, press the Confirm key:

VC will enter the source Code editing window, this function is used to handle the serial port event, when the PC serial port received data, will produce a data buffer has data message event, and then call to execute this function. Add the following code, for Data processing, window updates and other operations:

VARIANT Variant1;//Define variant variables to hold the received dataCOleSafeArray SafeArray;//Defining SAFEARRAY VariablesLONG len,k;//define long integer variables Len,kBYTE rxdata[2048];//Defining a byte-type arrayCString STREMP1,STREMP2;//define two stringsif(M_COMM1. Getcommevent () = =2)//determine the cause of oncomm time{//if a specific number of bytes are received, the received data is readVariant1 = m_comm1. GetInput ();//store the received data in a Variant variableSAFEARRAY = Variant1;//Variant variable to type COleSafeArrayLen =SAFEARRAY.   Getonedimsize ();  for(k=0; k<len;k++) {safearray. GetElement (&AMP;K,RXDATA+K);//get the received data into the byte array rxdata   }    for(k=0; k<len;k++) {BYTE bt= (* (unsignedChar*) (rxdata+k));//read high byte of ad conversion       if((k%2)==0)      if((k +1) <Len) {Gllen++;//A global variable that calculates the number of converted results receivedStremp2. Format ("The result of the first%d conversions:", Gllen);//show the first few conversions          inttemp = bt*4+ ((* (* (unsignedChar*) (rxdata+k+1)) >>6);//High and low bytes merged into actual conversion results, note that the conversion result is left justifiedSTREMP1. Format ("%2.2f",(2.56*temp/1024x768));//calculate the actual voltage valueSetdlgitemtext (Idc_static, ("the current voltage value is:"+stremp1+"V"));//updating a static text controlPbar-SetPos (temp);//Update the current position of the progress barStrrxddata + = STREMP2;//Put the new data in a global stringStrrxddata + =STREMP1; Strrxddata+="v\r\n";//string plus unit v line break      }}}setdlgitemtext (Idc_edit1,strrxddata);//Update the display of text controls

at this time recompile, see if there will be any errors, the following prompt, you can select all the build to clear.
LINK:LNK4073:cannot Create map for. ILK file; Linkingnonincrementally
The following error occurred, please close the running test.exe and try again.
link:fatal Error Lnk1104:cannot Open file "Debug/test.exe"
The following error is caused by the space number problem, when we add an edit box or "phone" and then add, its number automatically add one, the control will appear to be undefined.
z:\vc++ Serial host computer \test\testdlg.cpp (+): Error C2065: ' IDC_MSCOMM1 ': undeclared identifier
z:\vc++ Serial host computer \test\testdlg.cpp (139): Error C2065: ' idc_edit1 ': undeclared identifier
The solution is, in the Recourseview, open the form Idd_test_dialog, right click on "Phone" or other error control, such as edit box, right click on the selection of properties, in the general change the ID, the program here, except Button 1, 22, the others are 1

Compile all build, see if there are errors, no errors can be run, you can see the interface is the same as the original. There are mistakes to modify, save more, wrong in where do not know, check up trouble.


8, in the Source code Editor, open the TestDlg.cpp file, the window initialization function to write.
Find the bool Ctestdlg::oninitdialog () function,
In SetIcon (M_hicon, FALSE);

//Set Small Icon//Todo:add Extra Initialization hereafter that, add the following initialization code: Gllen=0;//record the number of conversions global variables clear 0if(! m_comm1. Getportopen ())//determine if the serial port is already open{m_comm1. Setcommport (1);//Select the serial number 1M_comm1. Setportopen (TRUE);//Open the serial portM_comm1. Setrthreshold (2);//received two bytes raised OnComm eventM_comm1. Setinputmode (1);//Input mode selected as binaryM_comm1. Setsettings ("57600,n,8,1");//set serial port parameters, baud rate 57600, no parity, 1 bit stop bit, 8 bit data bitMessageBox ("Serial port Initialization complete","Tips");//prompt for successful initialization of serial port}ElseMessageBox ("The serial port is occupied","Tips");//If the serial port is already open, a message box alertPbar = (cprogressctrl*) GetDlgItem (IDC_PROGRESS1);//get pointers to Idc_progress1Pbar-SetRange (0,1023);//set the range of the progress bar 0~1023Pbar-SetPos (0);//current position is 0M_serial. SetWindowText ("Close the serial port");//button Display status change

can see, the parameters of the serial port and so on are initialized here, can be modified according to their own needs, specific can see VC + + in the detailed introduction, See what parameters are available for us to modify.
After you add and compile, you can see a message window with a serial port initialization after running.
So far, we have completed the main serial port operation and interface, the remaining is two button operation.


9, Back to the Idd_test_dialog window of the Resource view, double-click the Start Conversion button, add an event to it, Click after the PC through the serial port to send 0xaa out, to the microcontroller to receive.
Add the following code:

// Defining byte Arrays // byte array empty m_array.setsize (1// Set Dimension 1m_array.setat (0,0xaa/ / give m_array[0] a value of 0m_comm1. Setoutput (COleVariant (M_array)); // since the parameter of the Setoutput function is variant, it must be cast before it can be sent

Similarly, double-click another button to add code to the serial Operation button to close or open the serial port. Add the following code:

if(! m_comm1. Getportopen ())//determine if the serial port is already open{m_comm1. Setportopen (TRUE); //If the serial port is off, open the serial portM_serial. SetWindowText ("Close the serial port");//button Display status change}Else{m_comm1. Setportopen (FALSE); //If the serial port is already open, turn off the serial portM_serial. SetWindowText ("Open the serial port");//button Display status change}

At this point, a simple serial port PC software is completed, can be used to test, through the single-chip computer to send data to the serial port, you can see the main window of the conversion results, the progress bar shows the voltage value changes. To take out this program, just put ... \vc++ serial port pc \test\release Test.exe copy out with the line. Release can select Win32 release in the Compile window and recompile it.

Finish.

VC + + programming Simple serial host computer program

Related Article

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.