Visual Basic Expert SolutionsChapter 17Communications BasicsBy Steve Potts |
Communication between computers is a fundamental requirement of modern systems. Often this subject is treated with an undue amount of respect. Communications between computers is a complex arrangement of simple ideas and functionality.
Many end users are content to purchase a modem and run the applications that they purchase right out of the box. This chapter is written for programmers who are not willing to operate at such a global level. To create communication applications in Visual Basic, you can simply use the MSComm custom control, memorize what properties to set, and include it in your code. This approach creates the following two real problems, however:
To be really good, you must understand what is happening while communication between two computers is taking place. This chapter will attempt to give you an understanding of data communications in general, not just a primer on the MSComm custom control.
Data communications emerged as a field in the 19th century. Samuel F.B. Morse, of Morse code fame, learned of an experiment where an electrical signal was sent over a wire more than 25 miles long. He immediately commented that if that is possible, then intelligence can be transmitted instantaneously over long distances. That remark marks the birth of communications. He next went to work creating the infrastructure necessary to make this concept a reality. Shortly thereafter, he demonstrated how a sender can transmit information to a receiver using the Morse code. The dots and dashes were the protocol of the telegraph for the century that it was the preferred means of communications.
Modern data communications still centers around that idea. In this chapter, you will learn the following:
The simplest form of personal computer communications is called serial communications, because it transmits data signals in series, or one-at-a-time over one line. There are often other wires involved in supporting the data line, however. The following is a list of personal computer communication components:
This is in contrast to parallel communications where multiple signals are sent over multiple lines at the same time. If you have nine data wires in a cable, you could—in theory—send nine bits of information simultaneously. Parallel communications operates on this theory. Figure 17.1 shows a theoretical view of serial communications.
Fig. 17.1 Serial communication theory states that all communication takes place over one wire.
In practice, while there is only data wire in serial communications, there are a number of other wires that are needed to support the data wire.
These other wires manage the starting and stopping of the transmission of data, as well as other tasks. The Electronics Industries Association (EIA) wrote a "Recommended Standard Number 232, Revision C," which gives the specifications for the pin and voltage assignments for an operational serial communication standard. This standard is better known as the RS-232 standard. This standard defines 25 wires and their uses in serial communications. Table 17.1 lists these lines.
Table 17.1
Table 17.1 The 25 pin RS-232 Standard
Pin |
Abbreviation |
Name |
1 |
AA |
Protective Ground |
2 |
BA |
Transmitted Data |
3 |
BB |
Received Data |
4 |
CA |
Request to Send |
5 |
CB |
Clear to Send |
6 |
CC |
Data Set Ready |
7 |
AB |
Signal Common |
8 |
CF |
Received Line Signal Detect |
9 |
(none) |
Reserved for Testing |
10 |
(none) |
Reserved for Testing |
11 |
(none) |
Unassigned |
12 |
SCF |
Secondary Received Line Signal Detect |
13 |
SCB |
Secondary Clear to Send |
14 |
SCA |
Secondary Transmitted Data |
15 |
DB |
Transmission Signal Element Timing |
16 |
SBB |
Secondary Received Data |
17 |
DD |
Receiver Signal Element Timing |
18 |
(none) |
Unassigned |
19 |
SCA |
Secondary Request to Send |
20 |
CD |
Data Terminal Ready |
21 |
CG |
Signal Quality Detector |
22 |
CE |
Ring Indicator |
23 |
CH/CI |
Data Signal Rate Detector |
24 |
DA |
Transmit Signal Element Timing |
25 |
(none) |
Unassigned |
The total comprehension of the reasons behind the specifying of each pin would be fascinating reading on a stormy night. For the purposes of our discussion, however, there are only a few that we need to understand. Lines 2 and 3 actually send and receive data. If you hook two RS-232 ports together with a cable, it must have these two lines reversed from one end to the other. This is because one port's transmission is the other's reception. Pins 6, 8, 20, 22, and 23 communicate the various status from one device to another. Pins 4 and 5 (Request to Send and Clear to Send) are used to coordinate the timing of the transmissions between the devices. Figure 17.2 shows a female version of this device. The female version accepts the pins of the male version to make the connection.
Fig. 17.2 The RS-232 standard specifies the arrangement an use of a 25 pin serial connector.
It is not common on a personal computer to find all 25 pins actually present in a cable. This is because the EIA committee built in a lot of redundant capability to its standard. The budget-minded personal computer marketplace doesn't use these backups in their devices, so they dropped the pins while keeping the plug shape.
Table 17.2
Table 17.2 The Pin Assignments for the 9-Pin Plug in a 25-Pin Shell
Pin |
Abbreviation |
Name |
1 |
- |
Protective Ground |
2 |
TD |
Transmitted Data |
3 |
RD |
Received Data |
4 |
RTS |
Request to Send |
5 |
CTS |
Clear to Send |
6 |
DSR |
Data Set Ready |
7 |
- |
Signal Common |
8 |
DCD |
Received Line Signal Detect |
20 |
DTR |
Data Terminal Ready |
22 |
RI |
Ring Indicator |
23 |
DSRD |
Data Signal Rate Detector |
If you examine the back of the computer at your desk, you will probably discover another plug that is described as a serial port. A smaller plug with nine pins is most likely located right beside the printer port on your machine. This is a 9-pin "D" shell plug. It was created by IBM in the early personal computer days because it was small enough to fit with a parallel port on the same card, and because so many of the pins on a standard RS-232 plug are not commonly used by devices. They chose the nine pins that had to be present, and placed them in a pin arrangement on their computers. This decision was popular with the clone vendors, who copied the IBM arrangement. Table 17.3 shows the pin assignment for the 9-pin plug.
Table 17.3
Table 17.3 The Common 9-Pin Plug
Pin |
Abbreviation |
Name |
1 |
DCD |
Data Carrier Detect |
2 |
RD |
Received Data |
3 |
TD |
Transmit Data |
4 |
DTR |
Data Terminal Ready |
5 |
(none) |
Signal Common |
6 |
DSR |
Data Set Ready |
7 |
RTS |
Request to Send |
8 |
CTS |
Clear to Send |
9 |
RI |
Ring Indicator |
It is common to find both kinds of connectors on the same computer. Often, one is set up as COM1, and the other is called COM2. There is no official standard for the 9-pin plug and pin arrangement, except in the heads of 30 million computer lovers who would beat the tar out of any vendor who wanted to deviate one bit without good reason.
Each pin has a definite purpose in the 9-pin arrangement. These assignments depend on the connection between a computer (called Data Terminal Equipment or DTE) and a peripheral device (called Data Communication Equipment or DCE). These are as follows:
Data Carrier Detect (DCD) This line carries a positive voltage whenever a device (DCE) is ready to receive data. This is how a modem communicates to a computer that it is ready to accept data.
Received Data (RD) When data flows from the device (DCE) to the computer (DTE), it uses this line.
Transmit Data (TD) When data flows from the device (DTE) to the computer (DCE), it uses this line.
Data Terminal Ready (DTR) When a computer (DTE) is ready to talk to a device (DCE), it places a positive voltage on this line.
Signal Common (–) This is defined as 0 volts. Electrical engineers tell us that all voltage is relative, not absolute. This line defines what it is compared against.
Data Set Ready (DSR) The device (DCE) places a positive voltage on this wire when it is ready to communicate with the computer (DTE).
Request to Send (RTS) This line is given a positive voltage by the computer (DTE) when it wants to transmit data to the device (DCE).
Clear to Send (CTS) This line is given a positive voltage by the device (DCE) when it is ready to receive data from the computer (DTE).
Ring Indicator (RI) When a device (DCE)—normally a modem—detects a ring, it places a positive voltage on this wire.
You can see from the description of the pins that each is a wire with one specific purpose. Whenever a device wants to send data to a computer, it follows a procedure of placing a positive voltage on the appropriate lines, then checking the lines that the computer controls for its "answer". If it receives the correct responses, it starts transmitting data. As long as the computer leaves the lines that it controls in the same state, the device continues to pump data. If its buffers become full, or another problem occurs, the computer tells the device to wait a minute through these same wires.
Now that we have a physical connection between the two devices, we need to agree on the data that we plan to send across these wires. The first decision to make is the rate of data transfer. Different devices can accept data at different rates. For example, if you have a modem that accepts data at 14,400 baud, then it can accept 14,400 bits per second (bps). At times, one device is capable of faster data transfer than the other. In this case, the lower of the two rates must be used or the communication will fail. For example, if my laptop has a 14,400/28,800 baud modem, and I dial-up my office, which can only accept 14,400 bits per second, the "handshake" between modems will agree on 14,400 bits per second.
Another decision that must be made concerns the extra bits that are sent—but are not part of the data. There are three of these bits:
The Start bit—When a device wants to start transmitting, it wants to be sure that the computer will correctly receive the very first bit. The "protocol" that they use is as follows:
The Stop bit—Just as the Start bit signifies the start of a character, the stop bit signifies the end of a character. The transmitting device always sends a logical 1 for the stop bit. This is done by placing a positive voltage on the TD line.
The Parity bit—Reliability has always been a concern in serial communications. In the early days of data communications, someone invented a crude form of error detection, call parity checking, that is still being used today. Parity checking is done by sending an extra bit that indicates whether there was an even or odd number of logical 1 bits in the character just sent. Even parity places a logical 1 in the last bit sent if an odd number of logical 1 bits were in the character. If an even number of logical 1 bits were sent, then the parity bit is set to logical 0. This means that an even number of bits will always be sent. If an odd number of bits is sent, then that indicates an error condition.
The shortcomings of this scheme are obvious. If two errors occur in the same string, the failure can go undetected. While the odds of this happening are very small in a single character's transmission, the probability increases drastically when multiplied by the 100,000,000 characters that are commonly sent over the Internet to download one file.
You may be wondering how all of this bit-sending takes place in your computer. The setting of the lines at just the right voltages, sending the bits, and checking the parity of the response is the job of i/o card in your computer. This card contains a number of chips that handle these tasks for you. It plugs into the motherboard of your computer and provides one or more serial plugs to the back of the case.
By plugging into the motherboard, the serial card can receive instructions from a program running on the CPU. Unfortunately, your serial card cannot understand Visual Basic commands. This problem is overcome by the authors of both your operating system and Visual Basic.
The serial card contains a chip called a Universal Asynchronous Receiver Transmitter (UART). This UART has a number of registers that are addressable as memory locations. This means that a program running under Windows 95 can write to one of the addresses in Table 17.4, and the data will be placed in the buffer of the UART.
Table 17.4
Table 17.4 Serial Port Base Register Addresses
Serial Port |
Base Register Port Address |
COM1 |
3F8H |
COM2 |
2F8H |
COM3 |
3E8H |
COM4 |
2E8H |
By sending one of a series of instructions that the UART understands to these registers, your program can control the string of characters that gets sent out of the serial port
At this point, you should have a feel for what goes on under the covers when you are using a modem. The authors of Visual Basic have provided a custom control for you to use when you need to communicate with devices connected to the serial port on your computer. This custom control interacts with the operating system and, in turn, the operating system interacts with the device—hiding much technical detail from you, the programmer. The use of this custom control is the subject of the next section.
The communication custom control (MSComm) ships with Visual Basic 4.0, Professional Edition. It is called MSCOMM16.OCX or MSCOMM32.OCX—depending on whether you are running the 16- or 32-bit version of Visual Basic. In order to use the MSComm custom control, choose Custom Controls from the Tools menu. The Custom Controls dialog box appears, as shown in figure 17.3.
After you have indicated via the Custom Controls dialog box that you want to add the MSComm custom control to your project, the MSComm icon is added to your Toolbox, as shown in figure 17.4.
Fig. 17.4 The MSComm custom control icon looks like an old-fashioned telephone.
This first step in using the MSComm custom control is to place it on a form, as is shown in figure 17.5. This icon on the form will be invisible at runtime. It only appears on the form at designtime to preserve the visual programming paradigm.
The MSComm custom control works like the standard edition controls using properties, events, and methods. Before delving into the deeper details of how this control operates, run this simple example. The purpose of this experiment is to give you a global feel for the MSComm control. We will discuss this example's details following the code. This example assumes that your modem is properly configured and connected to COM2. If you have used the Windows 95 modem setup, then you should have no problem. If you are using Windows 3.1, follow the instructions that came with your modem to install it. If you are using COM1, COM3, or COM4, substitute that comm port for COM2.
This example sets up the MSComm custom control for use with a modem.
Listing 17.1 testcom1.bas A Simple Communication Program
1. Enter a phone number in your home or office (instead of 514-9688). Substitute your own phone number for this example one.
2. Run the program by single-stepping through your code.
3. Click on the form.
4. Step through the code until you get to the line that reads:
1. 10. Listen to your modem and watch its indicator lights (if it is so equipped). If the settings are correct, you will hear a dial tone, the tones for the number that you placed on this line, and the phone ring. If you pick up that phone and say something, you will likely hear your voice on the modem's speaker.
Briefly, the example opens the COM2 port with the following statement:
Opening the port means that the driver associated with the hardware port is connected to this program. On many modems, an indicator light will illuminate. The Output property takes string data and places it in the output buffer. The modem is looking in this buffer for commands. The commands that it understands are called AT commands, because they begin with AT. The command ATT tells the modem to dial using tones instead of pulses. You will learn more AT commands in the section "Programming a Modem" later in this chapter.
The command ATD514-9688 tells the modem to dial this number.
The Chr$(13) appends a carriage return to the end of the command, telling the modem to execute the command.
Having finished with the program, we now close COM2 so that it can be used by another application.
Only about half of the properties of the MSComm custom control are available to you at designtime. The rest expect to be set at runtime. As with other Visual Basic controls, not all of the properties need a static value at program initialization. Figure 17.6 shows the properties in the Properties window at designtime.
Fig. 17.6 These properties of the MSComm custom control are available at designtime.
The most frequently used of these properties are as follows:
Fig. 17.7 The Custom dialog box allows the designer to specify the values of several properties.
To display this setting, you use this syntax:
Table 17.5
Table 17.5 The Settings for the Handshaking Property
Setting |
Description |
None |
(Default) No handshaking |
XOnXOff |
XON/XOFF handshaking |
RTS |
RTS/CTS handshaking |
RTSXOnXOff |
Both RTS and XON/XOFF handshaking are used |
To display this setting, you use this syntax:
To display this setting, you use this syntax:
Note: The implementation of the MSComm custom control uses two properties to perform tasks normally associated with methods. The Output property places data in the output buffer. The Input property moves data from the buffer into a variable.
Text1.Text = MSComm2.InputLen
To display this setting, you use this syntax:
OutBufferSize—Sets and returns the size of the output buffer. In code, you set the OutBufferSize property like this:
To display this setting, you use this syntax:
To display this setting, you use the following syntax:
To display this setting, you use the following syntax:
To display this setting, you use the following syntax:
This means that the baud rate is 9600, no parity checking is desired, there are 8 Data bits, and there is 1 Stop bit in each packet. If the string doesn't contain a valid set of values when the PortOpen property is set to True, then an Error 380 is generated. The valid settings for the MSComm custom control are shown in Table 17.6.
Table 17.6
Table 17.6 The Valid Settings for the MSComm Custom Control
Baud Rates
110,300,600,1200
2400,9600 (default)
14400,19200
Parity Settings
Setting |
Description |
E |
Even |
M |
Mark |
N(default) |
None |
O |
Odd |
S |
Space |
Data Bits
4,5,6,7,8 (8 is the default)
Stop Bits
1 (default), 1.5, and 2
It is more important to match the settings that the other device is expecting than it is to use any particular set. Luckily, the more efficient settings have been gaining in popularity in recent years, improving the performance of communications overall. The default settings are the most common.
As the name implies, the runtime properties only have meaning while the program is running. They tell you the status of your program, serial port, or peripheral device. Earlier, you saw how the PortOpen property was used to open the port for communications. This property can also be used to query the system for the status of a port. Listing 17.2 shows this.
Listing 17.2 Portopn1.bas Checking a Port’s Status
When you run this program, single-step and watch what happens to the value of the PortOpen property as it is displayed in the Text1 Text Box control. The value will be True for a time, then after the port is closed (PortOpen = False), you can see the value change. While the port is open, you will see the window as it is displayed in figure 17.8.
Fig. 17.8 The status of a port can easily be queried using the PortOpen property
This property allows you to keep up with the status of the port during the course of your program's execution.
It is also useful to query the Settings property and the ComPort property during the course of the program's execution. An example of this would be during a user session where she is changing the settings to those required by the service that she wants to connect with. It is useful to display the current values. Listing 17.3 shows how this is done.
Listing 17.3 Whatset1.bas Checking Modem Settings
Run this program and observe that a form that looks like the one shown in figure 17.9.
Fig. 17.9 The Settings and CommPort properties can be queried at runtime.
The real power of a communications control is in its ability to communicate with a device. The MSComm custom control uses properties, curiously, to perform these tasks. Just as we saw how the Output property can be used to send the dial command to the modem, the same property can be used to send data to the modem also. The following code shows how this is done by sending a string to the modem when a command button is clicked:
In a similar fashion, the Input property can be used to retrieve data from the input buffer. Listing 17.4 shows how this is done. Getting a little ahead of ourselves, we will send an AT command (ATI0) to the modem, instructing the modem to identify itself by model number and also to perform a checksum. In both cases, we will use the Input property to pick up the string out of the buffer and display it on the form.
Listing 17.4 Whatmod1.bas Examining the Modem Model Number
The result of this code is a self-test. The result of this exercise is displayed in figure 17.10.
Fig. 17.10 The modem can be instructed to do self-tests.
By way of these commands, your programs can do some automatic detection of models and do the setup for the users. This is the mentality behind the Plug-and-Play concept. Instead of asking the user to configure a modem, which can be a difficult task even for battle veterans, your software would query the modem and use a database of modem characteristics to configure the port to work correctly.
Note: As a precaution, make sure to flush out the buffer after writing to it and before reading from it.
In figure 17.11, the buffer was read using the Input property right after the dialing command was sent to it. You can see that the same information that was just sent using the Output property was retrieved using the Input property.
After this has been read, the buffer is now empty and awaiting data.
A query to an external service is far more interesting than data generated by a query to the modem. Listing 17.5 dials-up a local bulletin board and receives a connect message from it.
Listing 17.5 Connect1.bas Displaying the Connection Success
The result is the standard CONNECT 9600 message means that the connection has been established. The verbose message allows you to easily display to the user that the connection was successful. Figure 17.12 shows the result of this program.
Fig. 17.12 The carrier sends back a connect message that can be displayed to the user.
The status can also be captured and a different message of your own composition can be displayed, such as You are now connected to the XYZ Online Service.
Previously in this chapter, in the section "The Communications Control," we used a modem and the AT command set to demonstrate the features of the MSComm custom control without defining what they were. The word modem is a contraction, of the concatenation of the words modulator and demodulator. It comes from the fact that data communications first used tones sent over telephone lines to transfer data. Modulation, the translation of bits into sounds, occurred at the sending end; demodulation, the translation of sounds into bits, occurred at the receiving end. Thus the pair of modems could move bits from one location to another without a magnetic media.
This remote communication at first involved dialing-up a remote site, telling the person at the other end to put their handset inside a couple of rubber donut-like things called acoustical couplers, and doing the same with your handset. The signals moved at a blistering 300 signals per second (300 baud). The result was that the remote computer could cause characters to be printed on a huge roll of paper that fed through a massive terminal.
Over the years, the roll of paper was replaced by the CRT screen, and the mechanical print head was replaced by video cards. The terminal itself has been replaced by attaching a modem to a PC. Not only do short answers pass back and forth, entire books are downloaded. Speeds now reach upwards of 28,800 bits per second and beyond.
Early modems responded to a set of commands that were unique to it. Each vendor created a way of communicating between modems. Hayes Microcomputer Products created a command set for its wildly popular modems in the mid-1980s. This command set started every command with an AT (meaning "ATtention"), followed by a string of characters that told the modem what the program wanted it to do next. Hayes sold so many of these modems that independent software vendors were willing to write programs that ran over these modems. Other modem vendors, anxious to cash-in on the sales generated by these independent software houses, designed their modems to accept the same command set. The result was a defacto standard for the industry. Now, in the mid 1990s, you can hardly buy a modem that doesn't support the AT commands.
While all of these modems support the basic AT commands, many of them—especially the high-speed modems—have considerable extensions to the basic commands. The use of these commands for a specific modem can produce performance that is far superior to the standard AT set.
Whenever a modem is turned on, it is in one of two states: the command mode or the online mode. The online mode is when the modem is connected with another modem. In online mode, the pair of modems is simply a pipeline connecting two programs at opposite ends of a wire. An example of online mode is when you are accessing an online service like CompuServe. You are normally running CIS, a program written for your PC, and connecting to a main CompuServe host over the phone line. Your modem is in command mode when the dialing and handshaking are going on, but when the logo comes up, that means that you are now in online mode.
Command mode is designed for accepting characters from the AT command set. The following code shows how this works. If you want to use pulse (or rotary) dialing instead of touch-tone, you would run the program in Listing 17.6.
Listing 17.6 Pulse1.bas Setting a Modem to Send Pulse Tones
In this example, the command ATP was sent to your modem. If you have the speaker turned on, you will hear a series of irregular tapping sounds instead of the familiar tones. Pulse-type switching equipment counts the number of pulses sent over the line instead of the frequency of the tone.
Another popular use for the AT command set is to test the modem. Listing 17.7 sends a command AT&T6 to the modem, asking it to perform a remote loopback test.
Listing 17.7 Loop1.bas Performing a Loopback Test
Because the test is being run without a connection first being made, we expect it to fail. Figure 17.13 shows what the message looks like.
Fig. 17.13 A loopback test will fail if no carrier is connected.
The phrase NO CARRIER means that it couldn't find a connection, or carrier, to perform the test.
Another use of the AT command set is to query and set the register values in the modem. In Listing 17.8, a query is made regarding the current setting of register S0. This register controls the number of rings that the modem will wait before auto answering.
Listing 17.8 Setreg.bas Setting Register Values
The answer that comes back is displayed in the text box in figure 17.14.
Fig. 17.14 The S registers control the behavior of the modem.
The answer that comes back is 000. This means that the modem is currently not in auto-answer mode.
In this chapter you were introduced to the details of communications programming using the MSComm custom control. You learned about how serial ports work and how Visual Basic interfaces with them.
You also learned how to program a modem using the AT command set, which was created by Hayes Microcomputer Products. You learned how to send data to a modem, and how to read data that was sent by a modem.
| Previous Chapter | Next Chapter | Search | Table of Contents | Book Home Page |
| Buy This Book | Que Home Page | Digital Bookshelf | Disclaimer |
To order books from QUE, call us at 800-716-0044 or 317-361-5400.
For comments or technical support for our books and software, select Talk to Us.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.