VC++ uses ActiveX controls to communicate with microcontrollers serially

Publisher:快乐行者Latest update time:2012-06-27 Source: 慧聪电子元器件商务网 Keywords:VC++ Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

In single-chip microcomputer application systems, it is often necessary to communicate with microcomputers through RS-232 serial ports. Among various operating systems, Microsoft's Windows is more common, and most of them are 32-bit platforms such as Windows 95/98. In the past, serial communication on the Windows platform was mostly implemented using the API functions provided by it. This method requires many low-level settings to use, so it is cumbersome and difficult to understand. The ActiveX technology launched by Microsoft provides another way to implement serial communication. This method is not only relatively simple, but also very practical. Especially in the visual object-oriented programming environment such as Visual C++, the serial port can be truly regarded as an object. Only simple settings are required when programming, and it is also easy to understand. The following discusses in detail how to use the serial communication ActiveX control provided by Microsoft. The corresponding file of this control is MSCOMM32.OCX, hereinafter referred to as the MSCOMM control. 1. MSCOMM control MSCOMM control, namely Microsoft Communication Control, is an ActiveX control provided by Microsoft to simplify serial communication programming under Windows. It provides a series of standard communication command interfaces, which can be used to establish a connection with the serial port, connect to other communication devices (such as modems) through the serial port, issue commands, exchange data, and monitor and respond to events and errors that occur in the serial connection. The MSCOMM control can be used to create telephone dialing programs, serial communication programs, and full-featured terminal programs. The MSCOMM control provides two ways to handle communication: (1) Event-driven method. When a communication event occurs, the MSCOMM control triggers the OnComm event. The caller can capture the event and check its CommEvent property to confirm what event or error occurred, so as to handle it accordingly. The advantages of this method are timely response and high reliability. (2) Query method. After each key function of the program, you can query events and errors by checking the value of the CommEvent property. If the application is small, this method may be more desirable. For example, if you write a simple telephone dialing program, there is no need to generate an event for each character received, because the only character waiting to be received is the "OK" response from the modem. When using the MSCOMM control, one MSCOMM control can only correspond to one serial port at a time. If the application needs to access and control multiple serial ports, multiple MSCOMM controls must be used. In VC++, the MSCOMM control corresponds to only one C++ class - CMSComm. Since the MSCOMM control itself does not provide methods, the CMSComm class, except for the Create() member function, has Get/Set function pairs to get or set the properties of the control. The MSCOMM control also has only one OnComm event to notify the caller that a communication event has occurred. The MSCOMM control has many important properties. Due to space limitations, only a few more important and commonly used properties are given, as listed in Table 1. Table 1 Important properties of the MSCOMM control: Property Description CommPort Communication port number Settings Baud rate, parity, data bit expressed in string form PortOpen The status of the communication port, open or close Input Receive data Output Send data InputMode Type of received data: 0 is text; 1 is binary 2. Programming implementation As can be seen from Table 1, MSCOMM can receive data in two different forms, namely in text form and in binary form. There are many documents and materials on using MSCOMM control to transmit character data. Such an example can be found in Microsoft's MSDN (Microsoft Developer Network), namely VCTERM. However, almost all raw data obtained by measurement systems with single-chip microcomputer as the core are in binary form, so transmitting data in binary form will be the most direct and concise way. In addition, since the MSCOMM control transmits characters in wide character format in text form, additional processing is required to obtain useful information. Therefore, this article mainly discusses the use method in binary form. In VC++6.0, three types of applications can be generated using APPWizard: single document (SDI), multiple documents (MDI) and dialog-based applications. In order to illustrate the problem and omit unnecessary details, the following takes a dialog-based application as an example. 1. Create a dialog-based application Open the VC++6.0 integrated development environment, select the menu item File/New, select MFC AppWizard (exe) in the Projects tab in the dialog box that appears, and then fill in MyCOMM (name it as needed) in the Project Name box, and then click the OK button. In the dialog box that appears next, select the Dialog Based item, and then click the NEXT button. The following dialog boxes are set by default, so that a dialog-based application can be generated. Its dialog box template will appear in the resource programmer. 2. Insert the MSCOMM control Select the menu item Project/Add to project/Components and Controls…, select Microsoft Communications Control, version 6.0 in the Registered ActiveX Controls folder in the pop-up dialog box, and then press the Insert button. Then a dialog box will pop up, prompting the generated class name and file name. Press the OK button to insert the control. At this time, a control icon that looks like a telephone will appear on the control toolbar of the dialog box, and a class CMSComm will also appear in the Classview of the Workspace. [page] At this time, you can add the MSCOMM control to the dialog box template, and the addition method is the same as other controls. Then you also need to add a member variable to the dialog class accordingly, and here we name it m_comm. To add it: First, in the dialog template, right-click the control, select ClassWizard, and in the Control Ids item of the Member Variables tab of the dialog box that appears, select IDC_MSCOMM1. Then, press the Add Variable… button, and enter m_comm in the Member Variable Name item of the dialog box that appears. Finally, press the OK button. 3. Set properties You can set the properties of the control in two places:















































(1) In the dialog resource editor. On the dialog template, right-click the MSCOMM control and select the Properties… menu item to set various properties. Only the following items are modified here, and the others are accepted by default: Rthershold: 1, InputLen: 1, DTREnable: Unchecked, InputMode: 1-Binary.

(2) In the OnInitDialog() function of the dialog class. : Below is the function implementation of the above settings:

BOOL CMyCOMMDlg::OnlnitDialog()
{
CDialog::OnlnitDialog();
//This is the code automatically generated by the application framework and is not listed
//TODO: Add extra initialization here
m_comm.SetCommPort(1); //Use serial port 1
m_comm.SetSettings("9600, N, 8, 1");
//The baud rate is 9600, no parity, 8 data bits, 1 stop bit
m_comm.SetRThreshold(10); //Trigger a receive event every 10 characters received
m_comm.SetSThreshold(0); //Do not trigger a send event
m_comm.SetInputLen(10); //Each read operation takes 10 characters from the buffer
m_comm.SetInputMode(1); //Binary data transmission form
m_comm.SetPortOpen(TRUE); //Open the serial port
return TRUE; //return TRUE unless you set the focus to a control
}

4. Send binary data

If you need to send binary data, you can process the data as follows. The specific code is as follows:

CByteArray bytOutArr;
bytOutArr.Add(0x0); //Assign values ​​to the array
bytOutArr.Add(0x1);
bytOutArr.Add(0x2);
bytOutArr.Add(0x3);
bytOutArr.Add(0x4);
COleVariant varOut;
varOut=COleVariant(bytOutArr); //Convert the data to the variant data type
m_comm.SetOutput (varOut); //Send data

5. Receive binary data

When you need to receive a large amount of data, it is best to use event-driven programming. The specific steps are as follows:

(1) Respond to the OnComm event. In the dialog resource programmer, double-click the MSCOMM control on the dialog template and fill in the event response function name you want in the pop-up dialog box. Here it is named OnCommMscomm1().

(2) Receive and process data in the event response function. The received data is variant data, so some processing is needed. The specific code is as follows:

void CMyCOMMDlg::OnCommMscomm1()
{
COleVariant varRcv;
CByteArray byt;
int i;
long num;
switch (m_comm.GetCommEvent())
{
cass 1://data sending event
break;
case 2://data receiving event
varRcv=m_comm.GetInput();
varRcv.ChangeType (VT_ARRAY |VT_UI1);
BYTE HUGEP *pbstr;
HRESULT hr;
hr=SafeArrayAccessData (varRcv.parray,(void HUGEP*FAR*)&pbstr);//Get the safe array pointer

if (FAILED (hr)){
AfxMessageBox("Failed to get the array pointer!");
break;}
num=0;
hr=SafeArrayGetUBound (varRcv.parray,1,&num);//Get the upper bound of the arrayif
(FAILED (hr)){
AfxMessageBox("Failed to get the upper bound of the array!");
break;}
for(i=0;i
byt.Add(pbstr [i]);
SafeArrayUnaccessData (varRcv.parray);
//At this point, the data has been saved in the binary array byt, and related processing can be performed as neededbreak
;
default:
break;
}
}

The processing part in the above code can be made into a separate function and called here. After the processing of the above code, the received data has been stored in the binary array byt, and it can be processed according to your needs, such as saving and displaying.

3. Hardware interface

The hardware interface between the microcontroller and the microcomputer can be realized with a MAX232 or ICL232 and a few capacitors. There are many literatures discussing this, so I will not go into details here.

The above method has been applied by the author in practice and feels very simple and convenient, and has strong practical significance.

Keywords:VC++ Reference address:VC++ uses ActiveX controls to communicate with microcontrollers serially

Previous article:Using MSP430F149 single chip microcomputer to realize universal controller of stepper motor
Next article:Hardware design trivia 1: Low power design

Recommended ReadingLatest update time:2024-11-16 19:51

Implementation of serial communication between multiple MCUs and PC based on VC6.0
introduction   In computer control systems, it is inevitable to use a multi-machine system for communication. In a distributed control system consisting of a PC (host) and multiple single-chip microcomputers (slave), it is most convenient to communicate with multiple single-chip microcomputers through the serial por
[Microcontroller]
Interface Design Technology between TMS320VC5402DSP and 51 Single Chip Microcomputer
TMS320VC5402 (VC5402) is a fixed-point digital signal processor with high cost performance launched by Texas Instruments. The enhanced peripherals of VC5402 are composed of software wait state generator, phase-locked loop clock generator, 6-channel direct memory access (DMA) controller, enhanced 8-bit parallel host
[Microcontroller]
Interface Design Technology between TMS320VC5402DSP and 51 Single Chip Microcomputer
Design and implementation of low-power encrypted voice hardware platform based on TMS320VC5510
   High-quality, low-rate speech coding algorithms are becoming more and more important in modern communication systems and are widely used in fields such as IP phones, voice mailboxes, and military wireless communications. Especially in some special application fields, the channel bandwidth is very narrow and the bit
[Embedded]
PCI2040 bridges TMS320VC5420 to PCI bus
  PCI2040 is a bridge chip produced by TI specifically for use between DSP and PCI bus. The internal schematic diagram is shown in Figure 1. For a detailed introduction to PCI2040, please refer to the relevant information from TI (see Reference 1). The PCI local bus standard was proposed by Intel Corporation and formu
[Embedded]
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号