Open the "project->; Add to project-> Components and controls->; Registered Activex control ",and then select the control: Microsoft Communication Control, version 6.0 to insert into the current project. In this way, CMSComm's related documents mscomm.cpp and mscomm.h are added to the project. When programming, just drag the MSComm control in the control dialog box to your application dialog box.
The MSComm control provides two ways to handle communication:
1. Event-driven communication is a powerful method to deal with serial activities. For example, when a character reaches or changes a CD (carrier detection) line or RTS (request to send) line, in this case, you can use the OnComm event of the MSComm control to capture and handle these communication events. OnComm can also capture and handle errors in communication.
2. You can check the value of the CommEvent property after each important program function to detect events and communication errors.
Each MSComm control used corresponds to a serial port. If you need to access multiple serial ports in an application, you must use multiple MSComm controls, and you can modify the interrupt address of the serial port address in the Windows control panel.
MSComm controls have many important properties,
CommPort property: Sets and returns the communication port number.
Syntax: object. Component [value] (value is an integer value indicating the port number. )
Note: At design time, this value can be set to any number between 1 and 16 (the default value is 1). However, if a nonexistent port is opened by using the PortOpen property, the MSComm control will generate an error 68 (invalid device).
RThreshold property: the number of characters to be received that are set and returned before the MSComm control sets the CommEvent property to comEReceive and generates OnComm.
Syntax: object. Rthreshold [= value] (value integer expression indicating the number of characters to receive before generating the OnComm event. )
Note: After receiving characters, if the Rthreshold property is set to 0 (the default value), the OnComm event will not be generated. For example, if Rthreshold is set to 1, every character received by the receive buffer will cause the MSComm control to generate an OnComm event.
CTSHolding attribute: determines whether data can be sent by querying the status of CTS lines. "Permission to send" is a signal sent by the modem to the relevant computer, indicating that transmission can be made. This property is invalid at design time and read-only at run time.
Syntax: object. CTSHolding (boolean type)
Setting value of CTSHolding property of Mscomm control:
65438 +0. It's clear that the delivery line is high.
2.false clear the transmission line voltage is too low.
Description: If the clear send line is low (CTSHolding = False) and times out, the MSComm control sets the CommEvent property to ComeventCTSTO and generates the OnComm event. .
The clear transmission line is used for RTS/CTS (request transmission/clear transmission) hardware handshake. If it is necessary to determine the status of clearing the sending line, the CTSHolding property provides a manual query method.
SThreshold property: Sets and returns the minimum number of characters allowed in the transmission buffer before the MSComm control sets the CommEvent property to comEvSend and generates the OnComm event.
Syntax: object. SThreshold [= value] plastic expression representing the minimum number of characters in the transmission buffer before generating the OnComm event.
Description: If the Sthreshold property is set to 0 (the default value), the data transmission event will not generate the OnComm event. If the Sthreshold property is set to 1, the MSComm control will generate an OnComm event when the transmission buffer is completely empty. If the number of characters in the transmission buffer is less than the value, the CommEvent property is set to comEvSend and an OnComm event is generated. When the number of characters exceeds the threshold, the comEvSend event is activated only once. For example, if Sthreshold is equal to 5, comEvSend will only occur when the number of characters in the output queue is reduced from 5 to 4. If the number of characters in the output queue never exceeds Sthreshold, the comEvSend event will never occur.
ComInputModeText 0 (default) retrieves data as text through the Input property.
ComInputModeBinary 1 Retrieves data in binary form by inputting attributes.
CDHolding property: determine whether there is transmission at present by querying the status of the carrier detection (CD) line. Carrier detection is a signal sent from the modem to the relevant computer, indicating that the modem is online. This property is invalid at design time and read-only at run time.
Grammar object. CDHolding
Setting value: the setting value of the CDHolding property is:
Setup description
True carrier detection line height.
The error carrier detection line is low.
Note: When the carrier detection line is high (CDHolding = True) and times out, the MSComm control sets the CommEvent property to comEventCDTO (carrier detection timeout error) and generates an OnComm event.
Capturing a lost transmission in a host application, such as a bulletin board, is particularly important because callers can hang up (abandon transmission) at any time.
Carrier detection is also called received line signal detection (RLSD). Boolean data type
DSRHolding property: Determines the state of the data set ready (DSR) line. The data ready signal is sent by the modem to the connected computer, indicating that it is ready to run. This property is invalid at design time and read-only at run time.
Syntax: object. DSRHolding
The position of the object represents an object expression whose value is the object in the Applies to list.
The DSRHolding property returns the following values:
Value description
Real data set ready line height
Error data set ready line low.
Description: When the dataset ready line is high (DSRHolding = True) and times out, the MSComm control sets the CommEvent property to comEventDSRTO and generates an OnComm event.
This property is useful when writing a DataSet Ready/Data Terminal Ready handshake routine for a DTE machine.
Data type: Boolean
Settings property: Sets and returns parameters of baud rate, parity, data bit and stop bit.
Syntax: object. Set [= value]
Description: When the port is open, the MSComm control will generate an error 380 (illegal property value) if the value is illegal.
The value consists of four setting values in the following format:
BBBB, doctor, master
BBBB is baud rate, P is parity, D is the number of data bits, and S is the number of stop bits. The default value of value is: "9600, n, 8, 1".
InputLen property: Sets and returns the number of characters that the Input property reads from the receive buffer.
Syntax: object. The syntax of Inputlen [= value] input attribute includes the following parts: value integer expression, which indicates the number of characters that the input attribute reads from the receive buffer.
Description: The default value of the InputLen property is 0. When InputLen is set to 0, using Input will make MSComm control read everything in the receive buffer.
The CommEvent property returns one of the following values for a communication event or error. These constants can also be found in the object library of the control.
Constant value description
Comeventbreak1001received a disconnect signal.
1002 clears the sending timeout. When sending characters, the CTS line is low in the event 1 specified by the system.
ComEventDSRTO 1003 Dataset Ready Timeout. When a character is sent, the DSR line is low in the event specified by the system.
ComEventFrame 1004 data frame error. The hardware detected a data frame error.
ComEventOverrun 1006 port overflow. The character in the hardware is not read, and the next character arrives and is lost.
Total 1007 carrier detection time. When sending characters, the CD (carrier detection) line is low in the event specified by the system. laser record
Also known as RLSD (Receiving Line Signal Detection).
ComEventRxOver 1008 receive buffer overflow. There is no space in the receive buffer.
ComEventRxParity 1009 parity error. Hardware detected parity error 7
Comeventtxfull1010 send buffer is full. The send buffer is full when queuing the send characters.
Unexpected error occurred while retrieving port dcb (device control Blick) from comeventdcb101.
Communication events contain the following settings:
Constant value description
ComEvSend 1 The number of characters in the send buffer is lower than the value of Sthreshold.
ComEvReceive 2 received Rthreshold characters. This event will continue to be generated until the data in the receive buffer is deleted by using the Input property.
ComEvCTS 3 CTS (Clear Send) line change
ComEvDSR 4 DSR line change. This event occurs when the DSR changes from 1 to 0.
ComEvCD 5 CD (carrier detection) line change ComEvRing6 detected a ringing signal. Some urat (universal asynchronous receiver-
-The transmitter (universal asynchronous receiver) does not support this event.
ComEvEOF 7 received EOF character (ASCII character 26).
Error messages (MSComm controls) The following table lists the error messages that MSComm controls can capture:
Constant value description
ComInvalidPropertyValue 380 invalid property value.
The ComSetNotSupported 383 property is read-only
ComGetNotSupported 394 property is read-only.
When the ComPortOpen 8000 port is opened, the existence is invalid.
The 800 1 timeout setting must be greater than 0.
ComPortInvalid 8002 invalid port number.
The 8003 property is only valid at run time.
The 8004 property is read-only at run time.
The comportaleydopen8005 port is already open.
The 8006 device identifier is invalid or unsupported.
8007 does not support the baud rate of the device.
8008 The specified byte size is invalid.
8009 Default Parameter Error
80 10 hardware unavailable (locked by other devices)
The 80 1 1 function cannot allocate queues.
ComNoOpen 80 12 device is not turned on.
80 13 device is turned on.
80 14 communication notification cannot be used.
Comsetcommstatefailed 8015 failed to set the communication status.
80 16 failed to set the communication event mask.
Comprtnotopen80 18 This existence is only valid when the port is open.
80 19 equipment busy
ComReadError 8020 communication device reading error
ComDCBError 802 1 An internal error occurred while retrieving the port device control block.
After figuring out the above basic attributes, you can start writing communication permission programs. Create a new project file in VB5.0/6.0. Add Microsoft Comm Control 5.0 group
Add a command button to the simplified Form 1 and name it CmdTest. The MSComm control is named MSComm 1, and add the following program code.
Private Sub cmdTestClick ()' opens the serial port.
MSComml。 CommPort = 2' set Com2.
If MSComml. Then PortOpen = False
MSComm 1。 Settings = "9600, n, 8, 1"' 9600 baud rate, no check, 8 data bits, 1 stop bits.
MSComm 1。 PortOpen = True' Open serial port.
If ... it will be over.
MSComm 1。 OutBufferCount = 0' clears the send buffer.
MSComm 1。 InBufferCount = 0' Empty the receive buffer.
When sending character data, pay attention to ending with a carriage return (vbcr).
MSComm 1。 Output= "This is a good book!" & ampvbCr
Dial a phone number or send an AT command.
MSComm 1。 output = " ATDT 05778 19 1898; vbCr
Pay attention when sending character array data. ByteArray must have a predefined assignment.
Dim ByteArray as byte()
Define a dynamic array
ReDim ByteArray( 1)
Redefine the array size.
ByteArray ( 0 ) =0
ByteArray ( 1 ) = 1
MSComm 1。 Output = ByteArray
End joint
Private Sub MScommEvent ()
Select MSComm 1 case. CommEvent
Case acceptance
Dim buffer as variable
MSComm 1。 InputLen = 0
Receiving binary data
MSComm 1。 InputMode= ComInputModeBinary
Buffer =MSComm 1. invest
Receiving character data
MSComm 1。 InputMode=comInputModeText
Buffer = MSComml。 invest
Other cases
End selection
End joint
(Program 1)
Second, the communication problems and solutions under Chinese WIN 95/98
1. The received data is less than the sent data.
If more binary data is transmitted through MSComm control at one time, it is likely that the received data is insufficient. For example, in the case of setting the transmission rate to 24000 bps,
You can transmit 2048 characters of data at a time, so in most cases. Only about 1200 characters can be received at a time. This address can be found in the new version of MSComm32. OCX
A bug). This will affect the transmission of binary data. Note that this is not a feature.
The 32-bit Windows API function (hereinafter referred to as API) uses several time-limited variables represented by COMMTIMEOUTS structure, and WriteTotalTimeOutConstant is one of them.
One of them, Windows internal setting is 5000 (that is, 5 seconds). This constant determines the time it takes to send data in the buffer before the communication driver stops transmitting.
5 seconds means that only 600 characters can be sent at the communication speed of 1200bps, and only about 1200 characters can be sent at 2400 bps. In fact, in one place
It is possible to send more data in the buffer at a time. Even in the case of high-speed serial communication, this bug will cause problems even if the system is using flow control.
System, regardless of software flow (Xon/XofI) or hardware flow (CTS/RTS). If the data is in the send buffer, the flow control stops transmission, and if the stop time exceeds 5.
Seconds Then the data will be lost. In some cases, 5 seconds may be short. But don't worry, the MSComm control in VB 5.0/6.0 has an important new function.
This property is called CommID, and CommID refers to the serial port handle or flag called by API when the serial port is opened, which means that this can be modified by API interface function.
No change. Every time the serial port is closed, Windows will automatically revert to 5000. So you need to reset the following API statement every time you open the serial port. See the next program for the code.
Type COMMTIMEOUTS
ReadIntervalTimeout is Long.
ReadTotalTimeoutMultiplier is a Long type.
ReadTotalTimeoutConstant is the same length.
WriteTotalTimeoutMultiplier is a Long type.
WriteTotalTimeoutConstant as long.
End type
Declare the function SetCommTimeouts Lib "Kernel32 "
(BYVal hFile As Long,lpComm time out As comm time out)As Long
Declare the function getCommTimeoutLib "kernel32"
(ByVal hFile is Long, lpCommTimeouts is CommTimeouts) is Long.
Display timeout as a command
Dim Ret As Long
If Comm 1。 Then PortOpen = False
Comm 1。 PortOpen = True
If ... it will be over.
ret = GetCommTimeouts(comm 1。 CommID, timeout)
Set some default timeouts.
Time out. ReadIntervalTimeout = 1
Time out. ReadTotalTimeoutMultiplier = 1
Time out. ReadTotalTimeoutConstant = 1
Time out. WriteTotalTimeoutMultiplier = 1
Time out. WriteTotalTimeoutConstant=
(Comm 1。 OutBufferSize\Val(Comm 1。 Settings) * 10000+ 1000
ret = SetCommTimeouts(comm 1。 CommID, timeout)
(Procedure 2)
2. How to send character data greater than 128?
In the communication program, when sending data one by one in a single-character manner, each data range is 0-255 (that is, 00-FF in hexadecimal). In the single-character version of English Win95 or
In the DOS version of the BASIC program, it is only necessary to convert the corresponding data into corresponding characters and send them to the communication port. But not in Chinese Win95/98, assuming it is in Chinese.
Run the following programs under WIN 95/98:
Dim i
For i=0 to 255
MSComm 1。 Output =chr(i)
Next, I
I hope to get the expected data between 0 and 255 at the receiver, but it turns out that the first 129 data is received correctly, which is 0- 128, and the next 127 data is 126 zeros and a 255.
The reason for this result is that Chinese Windows uses the double-byte character set (DBCS) system. The DBCS system uses a number between 0- 128 to represent ASCII characters, which is greater than.
The number 128 is only used as the leading character, which only shows that it is a non-Latin character and does not represent the actual meaning. The above program is used when calling the CHR () function.
DBCS character set, which led to this error. Then, how to distribute the data of 128 people? The answer is to use a character array and change the above program to:
Cc(255) is displayed in bytes.
For i = 0 to 255
cc(i) = i
Next, I
MSComm 1。 Output = cc
do
Multiple activities
Loop until MSComm 1. OutBufferCount = 0
Receiving process MSComm 1 _ on com ()
Select MSComm 1 case. CommEvent
Case acceptance
Modified Dim buffer, b 1, i.
MSComm 1。 InputMode=comInputModeBinery
MSComm 1。 InputLen = 0
Buffer = MSComm 1. invest
For i=LBound (buffer) to UBound (buffer)
Debugging. Print buffer (1);
Next, I
Keith. . . . .
3. How to send 0 characters (00H, empty)
It's a bit troublesome to send 0 characters by using serial port control in Visuai C++, but in VB5.0/6.0, you only need to pay attention to the following two points:
(1) Set the property of MSComm control NullDiscard = False;; .
(2) Use binary reception, namely MSComm 1. InputMode = CominputModebinary can solve the problem;
4. How to send Chinese strings (DBcS characters)
Various reference books in VB5.0/6.0 indicate that MSComm communication controls cannot send or receive binary data of double-byte character set system (DBCS).
This is a great pity for countries that use DBCS character set. But in practice, I found that using MSComm control can also send Chinese characters. There are two specific methods:
(1) Send directly
Direct sending equates Chinese characters with English characters. For example: mscomm 1. Input = "This is a line of Chinese data!" , but the Chinese data sent by this method cannot be too
Long, the size of the sending buffer and the receiving buffer should be set to more than twice that of Chinese characters, and the operating system versions of the sending and receiving systems should be consistent, otherwise it is.
An error occurred, such as receiving or sending buffer overflow. This method is often used in situations where general requirements are not too high.
(2) Indirect transmission
At the sending end, Chinese characters or characters are converted into a data array of internal code or area code, and then the converted data is sent to the serial port. After receiving the data at the receiving end, according to.
Data obtained in reverse order are converted into corresponding Chinese characters or characters. In the process of conversion, it is necessary to perform bit operations, such as separating high-order bytes from low-order bytes after obtaining the internal code of Chinese characters.
VB5.0/6.0 does not provide this function. The following is the function to find the high byte and low byte of an integer.
Common function HiByte(a is an integer)
Dim b
B= a and & ampHFF00
b = b / 256
If b<0, then b = b+256.
High byte = b
End function
Common function LowByte(a is an integer)
Dim b
B = a and & ampHFF
Low byte = b
End function
5. How to use a single computer for communication test?
Usually, after writing the communication program, you need two PCs or a PC and a single chip microcomputer. After the communication port is connected, the test can be carried out, but in many cases, there is only one PC due to conditions.
The test item is very simple. Can it be tested? Of course, and the method is simple. For the nine-pin serial port, find an abandoned serial mouse, peel off the mouse cable and connect it.
Connect 2 or 3 stitches at the butt joint; For a 25-pin serial port, find a paper clip (preferably with a plastic sleeve) and pull it straight. After using the plastic at both ends, bend a circle at both ends.
The symplectic in the middle of the ring can be directly connected to the socket of serial port 2 and 3 pins. If Dan Xin is not safe enough, you can put five needles on the ground.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
About the usage of mscomm, improve the article [mgwmj]?
MSCOMM control is a good thing. If you can fully understand it, it will serve you sincerely.
In the afternoon, I read the topic about MSCOMM, and felt it necessary to speak my mind. I only do hardware at ordinary times, and I have never studied software systematically, but only in my spare time.
Learn to use it. I've mastered a little. I'll play it here. I don't know if there are any mistakes, but I think I did a good job.
This is a VB universal serial event-driven receiver. Receive one data packet at a time, and the data packet can be any byte, ensuring that there will be no data loss!
Private Submcomm _ oncomm ()
Display s () as bytes.
Dim SS( 1024) as bytes.
Static n times longer
Static testing as a variable
If (MSComm。 CommEvent = comEvReceive) and then
S = MSComm。 Input' as long as there is data, bring it in, even if there is only one.
if(Timer-T & gt; 0.0 1), the "interval" is greater than 10 millisecond, and it is considered as a new packet.
Text 1 = "'text 1 is used to collect and display reception (hexadecimal format).
N = 0
If ... it will be over.
T = timer
For i = 0 to UBound(S)', a packet may generate several oncomm events.
Text 1。 Text = Text 1。 Text & Right ("0" & hexadecimal (s (i))&; " H ",3) +"
SS(N+i)=S(i)' The received data packet is buffered in SS ().
N = N+ unbound
Next, I
If ... it will be over.
End joint