A Method for querying serial communication by calling Win95 API

Source: Internet
Author: User
Tags qtest

A Method for querying serial communication by calling Win95 API

Abstract: In Win95, the serial communication mechanism has been improved and standardized compared with Windows 3.x. This article describes how to use a simple serial port query method to implement serial communication from the perspective of calling an API.

Key words API, serial communication, Visual Basic, multithreading, Win95

Visual Basic is a popular application development platform in windows. Its convenient interface design allows programmers to save a lot of time and focus their most on writing the core code of the application. Vb4 has become one of the most efficient and flexible mainstream development tools in the Win95 system, and calling the API application interface is a powerful expansion of vb4 functions, it enables vb4 to directly control and process PC hardware resources without relying on MS-DOS system services. It can be said that with the help of APIS, VB can hide most of the difficulties of Windows programming, while providing flexibility to use Windows environments.

Therefore, calling APIs in serial communication is a simple and feasible solution to directly control serial port hardware in VB.

I. Description of Win95 multithreading and 32-bit APIs

The Windows 95 operating system launched by Microsoft in is a comprehensive enhancement to the performance of earlier Windows versions. It first proposed and implemented the multi-thread programming idea of the application, which is one of the most significant and important features of the Win95 system that distinguishes it from other systems. A process is an execution instance of an application, while a thread is the path for internal execution of the process. Basically, a thread is the simplest code unit that can be scheduled by the system, each thread has its own set of CPU registers and stacks. Win95 schedules CPU time for each independent thread. The operating system provides time slices to the thread in rotation mode, so that each thread is running at the same time in terms of appearance. A multi-threaded application actually implements multi-task extension within it, giving the code parallel execution features.

The main advantage of multi-threaded applications is that they can respond to user requirements at minimal time. Multithreading does not mean that the code runs faster. To be precise, it only means that the application can make better use of system resources (Scheduling Mechanisms, memory, and physical devices ). This allows you to create a flexible application that can receive user input at any time and achieve satisfactory results.

Therefore, to build faster, reliable, and robust code in a 32-bit Win95 system, multithreading is one of the key technologies that must be mastered.

APIS (application programming interfaces) are an extremely important component included in Win95. The 32-bit API of Win95 is mainly a collection of complex functions and messages. It can be seen as an open universal function enhancement interface provided by Win95 for various development systems running under it. It makes it easier for programmers to compile applications running on the Win95 system in different languages.

Compared with Windows 3. X's 16-bit API, the Win32 api included in Win95 is the most significant improvement in API quality. It is gradually becoming a target platform widely used. Win32 APIs include more than 1000 API calls, and hundreds of Windows constants, messages, and data types attached to the APIs, this gives you a series of complex and effective tools for Win95 programming.

APIs are the most important extension of VB functions. Almost all problems that cannot be solved using the standard functions of VB can be solved by calling the API functions. API call not only provides VB with a large number of scalable functions. More importantly, it provides a train of thought and method to expand the VB function most effectively. In some low-level operations that directly interact with hardware, Calling API functions is often the only feasible method.

In short, Calling API interfaces and combining multi-thread programming technology have become the most popular advanced technology in Win95. Most application code has to deal with this high-level topic.

Ii. Working Mechanism of Win95 Serial Communication

The common DOS system mainly works in the response interrupt mode. Most PC serial communication programs use the int14h interrupt of the BIOS block to query the serial port for asynchronous serial communication.

Unlike dos interrupt response, Windows is an event-driven, device-independent multi-user operating system. At the same time, Windows prohibits applications from directly interacting with hardware. programmers can only manage hardware through various drivers provided by windows. In this case, Windows acts as an intermediary between applications and hardware.

Windows functions include the communication support interrupt function. The Win95 system opens a user-defined input/output buffer (read/write buffer) for each communication device. Data access and communication ports are completed by the system background. The application only needs to complete the input and output buffer operations. The actual process is to generate a low-level hardware interrupt every time a character is received. The serial driver in the Win95 system gets control and puts the received characters in the input data buffer. Then return the control to the running application. If the input buffer data is full, the serial driver uses the currently defined flow control mechanism to notify the sender to stop sending data. Data in the queue is processed in the "first-in-first-out" order.

Windows 3. X provides comm. DRV drivers support serial communication, while Win95 has improved and standardized the standard functions of these serial communication, and integrated the support for serial ports with the basic input/output driver assembly. Win95 implements serial port operations like file operations. both use the same open, close, and read/write functions.

The following is a comparison of the corresponding serial communication functions in the 16-bit and 32-bit APIs:

The 16-bit API only provides 16 communication-related functions. Compared with these 16-bit communication functions, Win95 provides richer communication functions and more powerful functions.

In the Win95 system, the serial port and serial communication driver are configured through a data structure called Device Control Block (DCB. Win95 DCB is more complex than Windows 3. x DCB and has better data structure definition.

The following is the definition of the device control block data structure in Win95:

Type DCB 'is defined in detail in the Win95 API. You can obtain it from the API text viewer of vb4.
Dcblength as long
Baudrate as long
Fbinary as long
Fparity as long
......
Evtchar as byte
End type
Win95 provides an important getcommstate function for obtaining the communication port status. The function loads the port configuration information into a device control block DCB to obtain the port configuration.

Another important COMSTAT structure is usually used to describe the current status of the serial port. It is defined as follows:

Type COMSTAT 'is defined in detail in Win95 API, which can be obtained from the API text viewer of vb4.
Fctshold as long
Fdsrhold as long
......
Cbinque as long
Cboutque as long
End type
Generally, you can achieve serial communication in the following four steps:

(1) initialize and open the serial port according to the protocol settings. In this way, the serial port is required for the Windows application,
And block other applications so that they cannot use this serial port.
(2) configure this serial port.
(3) transmit data back and forth on the serial port and verify the data during transmission.
(4) Close the serial port when this serial port is not required. Release the serial port for other applications.
In these four steps, the main program code is concentrated in step (3.

Iii. Implementation of VB serial port Query

(1) Mechanism of serial port Query

The serial port query method of VB is mainly used in the query mode. When the communication program is working in the "query" mode, the Win95 process and thread issues can be ignored. You can read the Serial Buffer only when there is data in the serial port. In this way, it is important for programmers to determine the timing of serial port reading, handshaking protocol and software error correction.

The following is a flowchart for reading and receiving buffer data:

This method mainly works in the query mode. Programmers must complete a considerable part of the communication status detection work, and many details (even including conversion of character attributes in the communication process) must also be completed through program code. Therefore, compared with the communication control method, this query method is especially dependent on the protocols of both parties. The Agreement on communication between the two parties has a great impact on the difficulty of program implementation.

In the serial port query method, the general serial port initialization process is as follows:

It is worth noting that the agreement under this method must meet the following conditions: When Party A sends the message, Party B must enter the cyclic receiving status before Party A sends the action, after receiving the characters, the reader judges that the returned value of the readfile function is out of the loop state through the serial port reading function.

At the same time, in order not to make the system enter the "endless loop" status due to cyclic waiting for receiving, You can manually set the number of times to read the serial port, generally 1000 ~ You can perform this operation 10000 times.

Vb4 is an extremely flexible high-level language. In this way, you can easily introduce the idea of assembly language and use its goto to turn statements to easily control the program process. Flexible and convenient.

(2) Comparison with the communication thread method

The communication thread method creates a communication thread outside the main thread of the application to monitor the communication device. Its biggest advantage is that the program has the ability to detect the received data. Once the communication thread finds that the data has been sent to the serial port, the thread automatically sends a message to the application, which can be used by the application to read data from the communication device. The communication thread does not occupy the CPU time. In this way, the system can control multiple communication devices (such as modem) at the same time.

The communication thread method is widely used in C ++ development systems, which is closely related to the characteristics and advantages of C ++.

Due to the characteristics of VB, it is quite difficult to create a communication thread for VB. In addition, it is not economical to sacrifice the convenience of VB to accommodate the complexity of the program. The serial query method easily introduces some ideas about the Assembly Language and implements the most streamlined program code. It is not necessarily the most complete, but for general VB programmers, this method does achieve the purpose of simplifying the thinking and reducing the difficulty. Therefore, the implementation is simple.

Iv. program instance of serial port Query Method

It is agreed that Party A shall be a PC and Party B shall be a single-chip microcomputer system (such as a card reader of the Electric Meter System ). The communication format is set to 2400 baud rate, 8-Bit Data bit, 1-bit stop bit, no parity.

The following is an example of a program that defines a Communication Protocol. The Protocol is shown in the following flowchart:

The following are program instances of several sub-functions of Party A (PC.
Private function opentheport (cport as string, cbaud as string, cparity as string, CDATA as string, tstops as string) as Boolean
Dim lresult as long
Dim lhandle as long
Dim dcb_comm as DCB
Dim cdcbconfig as string
Lhandle = createfile (cport, generic_read or generic_write, 0 &, 0 &, open_existing, 0 &, 0 &)
If lhandle =-1 then' failed to open the serial port
Opentheport = false
Msgbox "serial ports may be occupied by other applications !"
Lresult = closehandle (lhandle) 'Close the serial port before enabling
If lresult = 0 then
Opentheport
Exit Function
End if
End if
Cdcbconfig. Band = 2400 'set DCB
Cdcbconfig. Parity = none
Cdcbconfig. Data = 8
Cdcbconfig. Stop = 1
Lresult = buildcommdcb (cdcbconfig, dcb_comm) 'configure a dcb structure according to user settings
If lresult = 0 then
Opentheport = false
Msgbox "unable to establish DCB Device Control Block"
Exit Function
End if
Lresult = setcommstate (lhandle, dcb_comm) 'specifies the DCB of a serial port.
If lresult = 0 then
Opentheport = false
Msgbox "unable to establish DCB Device Control Block"
Exit Function
End if
Opentheport = true
End Function

Private sub sendhand () 'subprocess for sending the handshake Signal
Dim nchars as long
Static readbuff as string * 1
Static writebuff as string * 1
Dim lpdcb as DCB
Dim LRET as long
Dim lhandle as long
Dim lpoverlapped as overlapped
Dim rnum as integer

Msgbox "Please plug the card reader in Serial Port 2 !", 48. "Prompt window"
Lhandle = opentheport (comm1, 2400, none, 8, 1)
LRET = purgecomm (lhandle, 1) 'clear output buffer
LRET = purgecomm (lhandle, 0) 'clear input buffer
LRET = getcommstate (lhandle, lpdcb) 'gets the status of the Communication Port
Shand:
Writebuff $ = CHR $ (& h8f)
LRET = writefile (lhandle, writebuff $, 1, nchars, lpoverlapped) 'send the handshake signal to the serial port Buffer
If LRET <= 0 then
Msgbox "sending operation error, electrical card handshake signal not sent successfully", 16
Goto shand' resend if it fails
Else
Goto qtest
End if
Goto Shand
Qtest:
Readbuff $ = "" 'clear the buffer is empty
Do While lhandle 'loop query serial port
Rnum = 0' set the number of times the serial port is read to 0
Readagain:
LRET = readfile (lhandle, readbuff $, 1, nchars, lpoverlapped)
If LRET <0 then
Msgbox "An error occurred while reading the response signal", 16
End if
If LRET = 0 then
If rnum> 1000 then' read-only 1000 serial ports to avoid endless Loops
Msgbox "Electrical card is not plugged in or the electrical card is not connected to the serial port! "
Goto closep
End if
Rnum = rnum + 1
Goto readagain
End if
If hex $ (ASC (readbuff) <> hex $ (& HFF) then
If the Goto shand' return code is incorrect, the system returns the handshake signal to continue sending.
Else
Label1.caption = "handshake signal:" + hex $ (ASC (readbuff $ ))
Msgbox "the handshake signal is correct and is online correctly"
Goto closep
End if
Loop
Closep: LRET = closehandle (lhandle)
If LRET = 0 then
Msgbox "serial communication port closed successfully", 48, "Prompt window"
End if
End sub

Note: When the PC communicates with the single-chip microcomputer system, the data in the single-chip microcomputer data storage zone (RAM) is in hexadecimal format, the signal line transmits the binary form of the hexadecimal ASCII code, while the ANSI code is used in Windows. The ANSI code is only the first 126 and the ASCII code is the same. That is, the string that receives the hexadecimal ASCII code in Win95 can be converted to the ANSI code first and then restored to the hexadecimal number in Win95.

Code $ = hex $ (ASC (readbuff $ ))

In addition, due to a change in the Data Type of 32-bit API function parameters, All Integer Parameters are converted to long to support 32-bit processing. This is especially true when setting the return value.

At the same time, these API functions, types, and constants must be declared before they can be used before being called.

V. Conclusion

It can be seen from the above that the VB serial port query method that calls the API interface has the outstanding advantages of simple implementation, low difficulty, and simplified code. It is suitable for common VB programmers when writing communication programs.

References
US $1 Darwin Boyle and other visual basic 4 developer's Guide
Beijing: Machinery Industry Publishing House 1997.1
2. Stefano maruzzi the Microsoft Windows 95 developer's Guide
Beijing: Machinery Industry Publishing House 1997.1

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.