Design implementation of RS-232-C port real-time monitoring software

zhaozj2021-02-16  110

Article title: Design implementation of RS-232-C port real-time monitoring software

Original author: Lang Rui

Original: Tianji Net

Putter: loose_went

Publish type: reprint

Summary:

This article describes the solution to the RS-232-C serial port in the Microsoft Visual C 6.0 environment, as well as solutions for problems such as unblocked background operation, real-time reception, and processing of data in the background monitoring process.

I. Introduction

In the laboratory and industrial applications, the credit cost is limited, and the serial port is often used as the preferred data transmission channel between the computer and the external serial device, and many devices and computers can be performed through serial ports due to serial communication convenient, many devices and computers Control, detection, and serial communication are increasingly a computer and peripheral for communication, gain a very important means of monitoring data collected by peripherals. The program instance described herein is running under the Windows 9x operating system, can be run in the background, real-time reception, processing data from the port, and can control the action by sending a command to the serial port. To avoid trigger the program blocking when real-time monitoring data, techniques such as thread and port interrupt responses are introduced.

Second, the program design ideas

Since this program is to monitor the serial port, it is required to be a background program that can be unrelated to the reception while monitoring. Therefore, it is necessary to avoid a polling method that is low in the process of repeated reading ports, and cannot be lost due to whether or not, it will be lost due to whether or later. Only the asynchronous way to take the port interruption can achieve efficient and secure monitoring procedures. As long as a data arrives at the port, the interrupt request will be thrown, and the interrupt processing function will start to process the data, thus avoiding the polling gap. Possible data. In most of the time without data arrival, there will be no interruption, the interrupt processing function will not be executed, ie only work in an instant there in data, this efficiency is not high.

In summary, to implement the above requirements, it is to be used to solve the problem problems encountered: First, use multithreading to avoid occurrence of occlusion in the operation of file operation. At the same time, in order to prevent multiple threads from operating the same variable while operating an error in timing, in order to maintain the synchronization of the thread, the technique of the critical area plus lock is also taken; the second is the interrupt response mode for the port data reading mode, specifically The cause is clear, and details are not described herein; third, the timer is used to meet the real-time display of the real-time monitoring program, in order to timely reflect the received dynamic data to the screen.

Curtain.

Third, RS-232-C serial port monitoring software program implementation

(1) Interface style

Since it is a real-time monitoring software, it is necessary to monitor the real-time data from the peripheral, but also send some specific instructions to the peripheral to control the peripheral to complete the preset action. To facilitate send commands to the serial port, you can add a dialogue similar to the Internet Explorer browser style to specify the "Internet Explorer Rebars" style when you first start construction, or you can add Microsoft Visual C 6.0. The "Dialog Bar" component belt is implemented. To display data read from the outside to the administrator and leave a fairly record to be reviewed, you can select a list view.

(2) The parameter setting and opening of the serial port

The parameter configuration for the RS-232-C serial port is the necessary condition for communicating using the serial port. And due to the different intervals, the use, the different configurations of the function is also different, in order to make this program more flexible, the adaptation surface is wider, and all possible parameters are preset in several combo boxes, can be in the program Change the settings at any time after running. Customize a data structure seting serial parameters: typedef struct tagcom_config

{

Int nport; file: // port number, from COM1 to COM4

Int nbaud; file: // baud rate, from 1200bps to 57600bps (corresponding macro to CBR_1200 to CBR_57600)

Int nData; file: // data bit, 7 bits or 8 digits

INT NSTOP; file: / / stop bit, can be 1, 1.5 bit, 2 digits.

INT nParity; // Take the check method, there is no check (noparity),

File: // oddparity and eVarity, etc.

COM_CONFIG;

When the appropriate parameters are selected, you can open the communication port according to the setting port configuration. Unlike previous DOS skewers, the Windows operation platform does not advocate the application directly control hardware (including port), nor does it make the use of interrupts (unless you want to enter the Ring0 system level), but through the Windows operating system. The device driver is delivered to data. During the Windows operating system, the serial port and other communication ports are processed as a file, not the ports to operate directly. For serial communication, Win 32 provides the corresponding file I / O function and communication function, through Understand the use of these functions, you can comply with the communication programs that meet different needs. There are 7 Communication Devices related to CommConfig, CommProp, CommTimeouts, Comst, DCB, ModemDevcaps, ModemSettings, 26 with communication-related Windows API functions, and specific instructions can be referred to the MSDN Help file. Here is some key code to open the serial port:

// Open the file in the form of a creation file and save the returned port handle in the handle IDcomdev.

IDCOMDEV = CREATEFILE (g_szcom_port [g_com_config.nport],

Generic_read | generic_write,

0,

NULL,

Open_EXISTING,

FILE_ATTRIBUTE_NORMAL,

NULL);

......

File: // CFG is an instance object of the CommConfig structure to obtain the status of the current communication port.

cfg.dcb.dcblength = sizeof (dcb);

GetcommState (IDCOMDEV, & CFG.DCB));

File: // Set the send, receive the cache size

Setupcomm (IDCOMDEV, 4096, 4096);

// purgecomm () is a clear function that can be used to suspend any unreasonable background or write, and can rush away I / O

File: // Buffer. Where: purge_txabort is used to abort the background write operation; prumpge_rxabort is used to abort the background

File: // Read the operation; prurance_txclear is used to clear the send buffer; prumpge_rxclear is used to clear the receiving buffer

PurgeComm (IDCOMDEV, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);

File: // Fill the DCB structure object DCB DCB.dcBLENGTH = SIZEOF (DCB) according to the set parameters;

GetcommState (IDCOMDEV, & DCB);

File: // Set port communication parameters

DCB.BAUDRATE = g_com_baud [g_com_config.nbaud];

DCB.BYTESIZE = g_com_bytesize [g_com_config.ndata];

DCB.PARITY = g_com_parity [g_com_config.nparity];

DCB.Stopbits = g_com_stopbits [g_com_config.nstop];

File: // Hardware Flow Control

DCB.FDTRCONTROL = DTR_CONTROL_DISABLE;

Dcb.foutxctsflow = false;

Dcb.frtscontrol = RTS_Control_Disable;

FILE: / / Software Flow Control

Dcb.finx = dcb.foutx = false;

Dcb.xonchar = (char) 0xFF;

DCB.XOFFCHAR = (char) 0xFF;

Dcb.xonlim = 100;

Dcb.xofflim = 100;

Dcb.evtchar = 0x0d;

Dcb.fbinary = true;

Dcb.fparity = true;

File: // Timeout control settings. There are two types: interval timeout: (only to read data from the port) It specifies the time to experience between two characters; total time: Total time required to read or write a specific number of bytes When a threshold is exceeded, the timeout triggers. Calculate the timeout according to the formula:

File: // readtotaltimeout = (ReadtotalTimeoutMultiplier * Bytes_to_read)

// readtotalTimeoutConstant

File: // WriteTotalTimeout = (WriteTotalTimeoutmuliplier * Bytes_to_write)

// WriteTototalTimeoutConstant

File: // If the parameter is 0 in setting the timeout, it is unlimited, ie no timeout.

CommTIMEOUTS.Readintervaltimeout = Maxdword;

CommTIMEOUTS.ReadtotalTimeoutMultiplier = 0;

CommTIMEOUTS.ReadtotalTimeoutConstant = 0;

CommTIMEOUTS.WRITETOTALTIMEOUTMULTIPLIER = 2 * 9600 / dcb.baudrate;

CommTIMEOUTS.WRITETOTALTIMEOUTCONSTANT = 25;

Setcommtimeouts (IDCOMDEV, & COMMTIMEOUTS);

File: // Set the status of the communication port according to the set DCB structure, and turn on the number of listening ports to monitor the number from the peripheral

File: // The thread comreadThreadProc.

IF (setcommstate (IDcomdev, & dcb))

{

m_bcomportopen = true;

G_HCOM = IDCOMDEV;

AfxBeginthread (ComreadThreadProc, Null, Thread_Priority_NORMAL);

Return;

}

Bool ccomreadbuf :: getonebyte (byte * cb)

{

m_lock.lock ();

IF (m_nhead == m_ntail)

{

m_lock.unlock ();

Return false; // empty

}

* CB = m_readbuf [m_ntail];

IF (m_ntail

m_ntail ;

Else

m_ntail = 0;

m_lock.unlock ();

Return True; //

}

Void ccomreadbuf :: add (byte buf [], int nbytes)

{

INT NT, I;

m_lock.lock ();

For (i = 0; ibr> {

NT = (m_nhead-m_ntail);

IF (NT <0)

NT = m_nbufsize;

IF (NT 1 == m_nbufsize)

Break; // buffer full

m_readbuf [m_nhead] = BUF [i];

IF (M_NHead

m_nhead ;

Else

m_nhead = 0;

}

m_lock.unlock ();

}

(4) Controlling command transmission

The control command can be obtained from the edit box on the dialogue, and then you can send it from the port by writing the file, which is simpler, and the thread is not involved. The main code mainly:

......

File: // Get the command line from the dialogue

NREAD = m_wnddlgbar.getdlgitemtext (IDC_EDit_send, BUF, 500);

File: / / Send commands to port

IF (NREAD> 0)

{

BUF [NREAD] = 0x0D;

BUF [Nread 1] = 0x00;

:: Writefile (G_HCOM, BUF, NREAD 1, & DWACTWRITE, NULL);

}

......

(5) Display of monitoring information

This program selects a list view as a display path to the data. In order to timely feed back the received data to the monitor, the function of the timing refresh can be completed by the timer in the view class, and the setTimer (...) function can be opened when the program starts in the program. Timer, with the killtimer (...) function in ONDESTROY () to turn off the timer before the program exits. Complete the latest received information to the list control in the response function of the timer message WM_TIMER. The main statement is:

......

File: // Get list of handles of lists related list space

Clistctrl & lisTctrl = getListCtrl ();

File: // There are two columns: the time and corresponding information received by the character

CTIME T = CTIME :: getcurrenttime ();

CSTRING SZTEMP;

SzTemp.Format ("% 02D:% 02D:% 02D", T.Gethour (), T.GETMINUTE (), T.GetSecond ());

FILE: / / Add information to the list

Int nindex = listctrl.insertitem (0, sztemp);

IF (-1! = nindex)

{

M_buf [m_ncurpoint] = 0;

ListCtrl.SetItemtemtext (NINDEX, 1, LPTSTSTR (M_BUF));

}

......

Fourth, debugging and detection

Now the program has been written, you can compile the run. It is best to check if the machine serial port can work properly and can be checked with the COMDEBUG program under DOS. After confirming that the serial port is working properly, if the conditions allow it to be connected to another computer or peripheral, the detection, such as the author uses a high-band digital transmission station. If there is only one computer to make a simple test: short of the second feet and the third foot of the computer serial port, that is, send itself, receive data. If there is a peripheral, when there is a collected data to the port, the time and information content will be recorded in the list, or the command can be entered in the dialogue to control the working status of the peripheral, which fully has real-time monitoring software. The required functions. summary:

Serial Communications is widely used in communication, and standard RS-232-C interface has become a standard interface for computer, peripherals, switches, and many communication devices. Computers, computers, computers, and peripherals can be easily connected via the RS-232-C interface to achieve monitoring, control peripheral, and transfer data. The methods described in other types of serial port communications are also worth reference. This program is

Microsoft Visual C 6.0 compiles to run in Windows 98.

转载请注明原文地址:https://www.9cbs.com/read-10405.html

New Post(0)