Implementation of serial communication in Delphi: Ruan help autumn

zhaozj2021-02-11  202

Implementation of serial communication in Delphi: Ruan help autumn Published: 2001/04/19

Thesis:

This article describes the serial port communication method between the PC and the lower PLC controller based on Windows95 / NT operating system. Key words serial communication, Delphi, multi-threaded

text:

The implementation of serial communication in Delphi With the development of modern information technology and the wide use of computer networks, computer communication technology has been mature, but serial communication is a flexible and convenient communication method, and it is still not a valid communication means. Widely used in industrial control. In industrial production practice, use of a PC to implement real-time monitoring, usually requires PC functionality to have data acquisition, data processing, and control signals such as data acquisition, data processing, and control signals on the user interface. In this particular environment, the PC is responsible for linking the real-time signal controlled by the process, requiring the serial port directly to the PC. The Delphi, launched by Borland is a powerful advanced programming language, which is characterized by visual object-oriented properties, especially suitable for graphical interfaces and user programs in a Windows environment. Based on WIN95 / NT serial communication mechanism Windows operating system mechanism prohibits applications from accessing computer hardware, but it provides programmers with a series of standard API functions that make the application more convenient and except for hardware Commissioning trouble. In Windows95 / NT, the WM_COMMNOTIFY message originally Windows3.x has been canceled, the operating system opens up the user-definable size read / write buffer for each communication device, and the data entry communication port is completed by the operating system background. Simply operate on the read / write buffer. Several commonly used serial communication operation functions in Win95 / NT are as follows: CreatFile Open Serial Port CloseHandle Close Serial Port SetupComm Sets the size of the communication buffer ReadFile Readfile ReadCommState Settings Communication Parameters GetCommState Get Default Communication Parameters Clearcommorror Clear the serial port error and get the current state except for the above functions, it is often used to use an important record DCB (device control block). During the DCB, the definable serial port parameters are recorded. When setting the serial port parameter, you must first use the getcommstate function to fill the system default value into the DCB control block, and then set the user to change the custom value setting. Serial communication is made in Win95 / NT In addition to understanding basic communication operation functions, you must master multi-threaded programming. The thread is the path executed in the process, which is the basic entity of the operating system allocates the CPU time. Each process starts the execution of the application by single-thread. Serial communication needs to be implemented using multi-threading technology. Its main processing logic can be expressed as follows: The process starts to do some necessary initialization works by the main thread first, and then the main thread establishes a communication monitoring thread monitoring communication port as needed. When the specified serial port event occurs, send the WM_COMMNOTIFY message to the main thread (since Win95 cancels the WM_COMMNOTIFY message, it must be created itself), the main thread is processed. If a WM_COMMNOTIFY message is not required, the primary thread terminates the communication monitoring thread. Multithreading is executed simultaneously, will cause conflicts of shared resources. To avoid conflicts, you must use synchronous multi-threads to access shared resources. Win95 provides a number of ways to keep thread synchronization, and the author adopts the creation of event objects to keep thread synchronization. Create an event object via CRAETEEVENT (), set the event object to signal synchronization using the ETEVENT () or PULSEEVENT () function. In the application, use the waitsingleObject () function to wait for the synchronized trigger, wait until the specified event is set to have a signal, and then executes the program. Delphi's specific implementation method of Delphi and supports multi-threaded object-oriented programming technology, making serial communication very simple and convenient.

It is implemented by calling the external API function. The main steps are as follows: First, use the CreateFile function to open the serial port to determine the share of this serial port, and block other applications for this serial port; secondly The device control block DCB is populated by the getcommstate function, and then configure the baud rate, data bit, check bit, and stop bit of the serial port by calling the setcommstate function. Then, create a serial port monitoring thread monitoring serial port event. On this basis, the data can be operated on the corresponding serial port; Finally, the serial port is turned off with the CloseHandle function. The specific procedures are as follows, and this program is prepared in the Win95 environment with Delphi3.0, which is used in practical applications, and is available for the broader readers.

Program: unit comdemou; interfaceuses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; const Wm_commNotify = Wm_User 12; type TForm1 = class (TForm) procedure FormCreate (Sender: TObject); private Procedure comminitialize; Procedure MsgcommProcess (var Message: Tmessage); Message Wm_commnotify; {Private declarations} public {public declarations} end; // declare thread TComm = Class (TThread) protected procedure Execute; override; end; var Form1: TForm1; hcom, post_Event: Thandle; lpol: poverlapped; implementation {$ R * .DFM} procedure TComm.Execute; // thread execution vardwEvtMask: Dword; Wait: Boolean; Beginfillchar (lpol, sizeof (toverlapped), 0); While True do Begin dwEvtMask: = 0 Wait: = Waitcommevent (hcom, dwevtmask, lpol); // Waiting for the serial port event; if Wait The begin WaitForsingleObject (post_event, infinite); // Waiting for the synchronization event set; resetEvent (post_event); // Synchronization event reset PostMessage (Form1.Handle, WM_COMMNOTIFY, 0, 0); // Send message; end; end; end; procedure tform1.com initialized VarlPDCB: TDCB; BE ginhcom: = createfile ( 'com2', generic_read or generic_write, 0, nil, open_existing, file_attribute_normal or file_flag_overlapped, 0); // open the serial port if hcom = invalid_handle_value then else setupcomm (hcom, 4096,4096); // Set Input, output buffer is 4096 byte getcommstate (hcom, lpdcb); // Get serial port current default settings lpdcb.baudrate: = 2400; lpdcb.stopbits: = 1; lpdcb.bytesize: = 8; lpdcb.parity : = EVENPARITY; // Even ques setcommstate (hcommmmask; setcommmask; // Specifying a serial port event to receive characters; end; procedure tform1.msgcommProcess (var message: tMessage); varclear: Boolean; coms: tcomstat; cbnum, readnumber, lpperrors: integer; read_buffer: array [1..100] of char; becom: =

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

New Post(0)