Serial port com1. What is a COM port
Along with the parallel port, the COM port, or serial port, is one of the traditional computer input/output ports, used in the first PCs. Although in modern computers The COM port has limited use, however, information about it may be useful to many users.
The serial port, like the parallel port, appeared long before the advent of personal computers of the IBM PC architecture. In the first personal computers, the COM port was used to connect peripheral devices. However, the scope of its application was somewhat different from the scope of the parallel port. If the parallel port was used mainly to connect printers, then the COM port (by the way, the prefix COM is just an abbreviation for the word communication) was usually used to work with telecommunications devices, such as modems. However, you can connect to the port, for example, a mouse, as well as other peripheral devices.
COM port, main areas of application:
- Connecting terminals
- ~ external modems
- ~ printers and plotters
- ~ mice
- Direct connection between two computers
Currently, the scope of the COM port has been significantly reduced due to the introduction of a faster and more compact, and, by the way, also serial, USB interface. Almost out of use external modems, designed for connection to a port, as well as “COM” mice. And it’s rare that anyone now connects two computers using a null modem cable.
However, a number of specialized devices still use the serial port. You can find it on many motherboards. The fact is that, compared to USB, the COM port has one important advantage - according to the RS-232 serial data transmission standard, it can work with devices at a distance of several tens of meters, while the range USB cable, as a rule, limited to 5 meters.
The principle of operation of a serial port and its difference from a parallel one
Unlike a parallel (LPT) port, a serial port transmits data bit by bit on a single line, rather than on multiple lines at once. Sequences of bits are grouped into series of data, starting with a start bit and ending with a stop bit, as well as parity bits used for error checking. This is where another English name comes from, which has a serial port - Serial Port.
The serial port has two lines through which the actual data is transmitted - these are lines for transferring data from the terminal (PC) to the communication device and back. In addition, there are several more control lines. The Serial port is served by a special UART chip, which is capable of supporting a relatively high data transfer rate, reaching 115,000 baud (bytes/s). True, it is worth noting that real speed information exchange depends on both communication devices. In addition, the functions of the UART controller include converting parallel code into serial code and vice versa.
The port uses relatively high voltage electrical signals - up to +15 V and -15 V. The logical zero level of the serial port is +12 V, and the logical one level is -12 V. Such a large voltage drop allows us to guarantee a high degree of noise immunity of the transmitted data. On the other hand, used in Serial port high voltage require complex circuit solutions. This circumstance also contributed to the decline in the popularity of the port.
Serial interface RS-232
Serial port operation on a PC is based on the data transmission standard for serial devices RS-232. This standard describes the process of data exchange between a telecommunications device, such as a modem, and a computer terminal. The RS-232 standard defines electrical characteristics signals, their purpose, duration, as well as the sizes of connectors and pinout diagrams for them. At the same time, RS-232 describes only physical layer data transfer process and does not affect the data used in this case transport protocols, which may vary depending on the communications equipment and software used.
The RS-232 standard was created in 1969, and its latest version, TIA 232, published in 1997. RS-232 is now considered obsolete, but most operating systems still supports him.
In modern computers, the Serial port connector is a 9-pin DB-9 male connector, although the RS-232 standard also describes a 25-pin DB-25 connector, which was often used on older computers. The DB-9 connector is usually located on system board PC, although in older computers it could be on a special multicard inserted into the expansion slot.
9-pin DB-9 socket on motherboard
DB-9 connector on the cable of the device connected to the port
Unlike a parallel port, the connectors on both sides of a two-way serial cable are identical. In addition to the lines for transmitting the data itself, the port contains several service lines through which data can be transmitted between the terminal (computer) and the telecommunications device (modem). control information. Although theoretically only three channels are enough for a serial port to work - data reception, data transmission and ground, practice has shown that the presence of service lines makes communication more efficient, reliable and, as a result, faster.
Purpose of the Serial port DB-9 connector lines according to RS-232 and their correspondence to the contacts of the DB-25 connector:
Contact DB-9 | English name | Russian name | Contact DB-25 |
1 | Data Carrier Detect | Carrier detected | 8 |
2 | Transmit Data | Transmitted data | 2 |
3 | Receive Data | Received data | 3 |
4 | Data Terminal Ready | Terminal readiness | 20 |
5 | Ground | Earth | 7 |
6 | Data Set Ready | Transmitter readiness | 6 |
7 | Request To Send | Request to send data | 4 |
8 | Clear To Send | Data transfer allowed | 5 |
9 | Ring Indicator | Ring indicator | 22 |
Configuration and interrupts
Since a computer can have several serial ports (up to 4), the system allocates two hardware interrupts for them - IRQ 3 (COM 2 and 4) and IRQ 4 (COM 1 and 3) and several BIOS interrupts. Many communication programs, as well as built-in modems, use interrupts and the address space of COM ports for their work. In this case, not real ports are usually used, but so-called virtual ports, which are emulated by the operating system itself.
As with many other components motherboard, operating parameters of COM ports, in particular, the values of BIOS interrupts corresponding to hardware interrupts, can be configured via the interface BIOS Setup. For this purpose the following are used BIOS options, such as COM Port, Onboard Serial Port, Serial Port Address, etc.
Conclusion
The PC serial port is not currently a widely used means for I/O. However, since there is large number equipment, primarily for telecommunication purposes, designed to work with a serial port, and also due to some advantages of the RS-232 serial data transfer protocol, the serial interface should not yet be written off as a completely outdated rudiment of personal computer architecture.
Initially, when they appeared personal computers , with them came several not-God-knows-what sophisticated, but quite successfully working in conjunction with all the other filling, ports or circuit interfaces. The word port denotes the method of data transfer. It's like a memory cell. Only in RAM information is recorded and lies there as long as some program needs it, until the program processes it (or the program itself is still needed by someone on the computer).
Port and memory
That is, the program will read the data from memory into the processor, do something with it, maybe receive some new data from this information, which it will write to another location. Or the given itself will simply be rewritten to another place. In any case, in memory, information that has once been recorded can either be read or erased. The cell looks like a chest standing against the wall. And all memory consists of a cell, each cell has its own address. Just like the chests standing in a row against the wall in the basement of a stingy knight.
Well, you can also imagine a port as a cell. Only such a cell at the back there is a window leading somewhere behind the wall. You can write information into it, and the information will take it and fly out of the window, although for some time it will remain in the cell in the same way as in a regular cell RAM.
Or vice versa, information can “fly” into the port cell from the window. The processor will see this and read this new information that appears. And he will put it to work - he will rewrite it somewhere, recalculate it along with some other data. It can even write it to another cell. Or to another cell-port, then this information received via the first port can “fly away” into the window of the second port - well, that’s how the processor decides. More precisely, the program that at this moment commands the processor and processes the data recorded in memory and coming from the ports.
Simple and beautiful. These ports were immediately called - input-output ports. Through some of them, data is sent somewhere, through others, it is received from somewhere.
Well, then the movement begins in a circle. There is one device, and there is another. And now there is a chain of characters, each of which consists of individual binary bits, and this chain needs to be transmitted. How to transfer? You can immediately transmit a whole character along a line of 8 wires - one wire = one bit, then the code of another, then a third, and so on until you transmit the entire chain.
And it was possible to unfold each bit not in space (via wires), but in time: first transmit one bit of the symbol, then the second, and so on eight times. It is clear that in the second case some additional funds, so that the symbols unfold in time.
Parallel and serial
And the transmission speed will be different:
![](https://i1.wp.com/instrument.guru/wp-content/auploads/200175/220px-rs-232.jpg)
It turns out that each option has its advantages, but also its disadvantages.
- It’s faster to transmit eight bits at a time (that is, byte by byte), but you need eight times more wires
- Transmitting one bit at a time requires only one information transmission, but it will be 8 times slower.
So in the first case they called the transmission parallel, and in the second case - serial.
Port Interface
And the whole system of such transmission - in one case this way, in another - like that, called interface. One interface is parallel, the other is serial. Almost the same thing, ports, one parallel, the other serial.
How does the concept of port differ from the concept of “interface”? IN modern technology words not only appear, they grow and receive “education.” And just like with people, they can become narrow specialists, or they can become “amateurs.” This is a typical amateur word - “interface”. Because it is “a plug for every hole.” The interfaces are:
![](https://i1.wp.com/instrument.guru/wp-content/auploads/200176/parametry-svyazi-com.jpg)
And the meaning of the word is something between something. Inter - between, face - face. It turned out beautifully, that’s why it’s used everywhere. For example, user interface Windows systems is the on-screen face of the system, designed to communicate with a person.
And it consists of a picture drawn on the screen + rules for the operation of each element of the picture (for example, click on a button on the screen with the mouse - it will be pressed) + rules for the response of each element and the entire system as a whole + all hardware participating in the dialogue (mouse, keyboard, screen) + all programs that provide dialogue both from the side of the entire system and from outside individual devices(drivers).
They didn’t mention the person, but since he is also part of the interaction, he must have knowledge and skills to work in the system, and for this there are training programs, help systems... And out of all this a beautiful and capacious word arises: interface.
In our theme, interface means things a little more simple.
These are hardware + software transmission + transmission rules. Hardware - understandable. But the software on computers and in modern means connections are present always and everywhere. It even happens: first, something functional is created on some hardware base, which is not executed immediately, but using specially written programs. And the programs are all customizable.
And gradually, as you work new feature(or a functional block), the programs that “make it” - and they differ from hardware in that they can be easily configured - are brought to some state optimal settings. That there is no need to configure anymore. And then the program in new version The functional block can be replaced with a hardware-based substitute for the software part. For example, “sew up” an optimally working well-tuned program in permanent memory . Or come up with a special one logic circuit, which will do exactly the same thing that an optimally configured program did - without shying away and sometimes forgetting all its useful settings.
That's why the interface is often called this - software and hardware.
Transmission rules are needed to ensure that the same things are understood (and processed) in the same way at both ends of the interaction. Are we talking about impulse transmission? This means that the impulses must be strictly identical.
For example, so that 1 bit comes in the form of +12 or +15 volts of voltage drop from zero. And so that it would be in the form of a rectangle, or a sharp burst - the peak of which would definitely be no less than, well, + 5 volts, and it’s not really necessary to introduce an upper limit, for example. This is because when transmitting impulses over some distance, electrical signals tend to weaken and “smear.”
If strictly 12 volts are sent from one end, then 3 volts may reach the other, and this may be regarded by the receiving system simply as noise on the line, and the transmitted information will be lost.
The meaning of impulses should also be understood in the same way. And impulses can be informational, service, synchronizing. And in general, for example, not impulses, but simply constant voltage. Which can be used at the other end to power a small device.
And the wires themselves that were discussed at the very beginning should also be understood equally. Here it must be said right away that it never happens that there is only one wire. Even the telephone has two wires in the cable, but normally the cable is supposed to have four. And data interfaces always have several conductors. Some of them are informational, some are service. And this is what should be recognized equally on both ends of the interaction. And the wires are recognized as? By color, if in the cable and by location, if in the connection contacts.
Port is a simple word and also not entirely unambiguous. But the meaning is similar: that something is loaded onto something and sent somewhere. Or vice versa, something that accepts something and unloads something from it. The meaning is almost the same as the hardware-software interface, but somehow more concise. And stricter, like in the navy (“They will tell you - don’t argue... but we don’t argue...”). Only our signals travel not by sea, but by cable.
Pinout of COM port connectors
The pinout has no connection with crucification, although, like wires running freely in one cable sheath, they are taken apart and hard soldered to their pins, similar to crucification. Pin, in English “pin”, pin, therefore pinout, the word is already a computer-communications “pro-English” jargon. It means wiring the wires to the pins on the connector.
The shape of the connector, the order of the wiring (pins) in it, the purpose of each pin, as well as the voltage ratings and the meaning of the signals in each - this is part of the interface. Typically, all this information is compiled into a separate document called a port specification. Such a simple and clear one-page sign. In other types of interfaces, something like this might be called a “protocol.” And here they simply call it “pinout”.
Serial COM ports
COM ports of a computer are the connection of a computer complex " long range" Unlike parallel ports and cables that led to “heavy” devices - printers, scanners, Com ports connected “light” units to the computer - a mouse, a modem. The first computer-to-computer interfaces (via a “null modem”). In the future, when did they spread local networks , and mice began to be connected via the same connector as the keyboard - port ps/2 (pe-es-in half) - com port somehow it was forgotten.
Renaissance came with the advent serial interface USB. So it turned out to be a movement in a circle. Now on USB you can find, in addition to flash drives, USB mice and USB keyboards. Printers, scanners, modems - all peripherals are now on USB, I have already forgotten about thick and solid parallel LTP cables that were necessary in mandatory screw on each side with 2 bolts. And there are two signal wires in these USBs (actually, one channel, one direct signal, the other the same - inverse) and two - power supply and housing.
There were several previous serial COM ports. The smallest - and the most popular 9-pin port (D9), to which most devices were connected: mice, modems, null modem cables. The contacts were arranged in two rows, 5 and 4 in a row, creating a trapezoid. Hence the name D9. On the “mother” the numbering went from left to right and from top to bottom:
1 2 3 4 5
COM port wiring, port RS232, 9 pins.
№ | Designation | Type | Description |
---|---|---|---|
1 | DCD | Entrance | High level from the modem when it receives the carrier modem partner |
2 | RxD | Entrance | Incoming data pulses |
3 | TxD | Exit | Outgoing data pulses |
4 | DTR | Exit | A high level (+12V) indicates the computer is ready to receive data. The connected mouse used this pin as a power source |
5 | GND | General | Earth |
6 | DSR | Entrance | The device is ready to transmit data |
7 | RTS | Exit | Response readiness of the partner device |
8 | CTS | Entrance | Readiness to receive data from a partner |
9 | R.I. | Entrance | Signal informing the computer about incoming call, received by the modem from the communication line |
Sometimes you have to solve a communication problem electronic device with a computer, be it simply data exchange or remote control. This article describes how this can be implemented using a serial port. Its main advantage is that the standard software interface Windows (API) allows direct control of output lines, giving direct control over them, and has the function of waiting for some event associated with the COM port. Also, the RS-232 standard, according to which the COM ports are made, allows for connecting and disconnecting cables while the devices are operating (hot plug).
Description
COM port (serial port)– bidirectional interface that transmits data in serial form (bit by bit) via the RS-232 protocol. This is a fairly common protocol used to connect one device (for example, a computer) with others via wires up to 30m long. The logical signal levels here differ from the standard ones: the logical one level is from +5 to +15V, the logical zero level is from -5 to -15V, which requires additional circuit transformations, but provides good noise immunity.
Consider a 9-pin connector (DB-9M). Below is its pinout:
![](https://i1.wp.com/housecomputer.ru/technology/interface/com-port/Com_pins.gif)
Pin no. | Name | Character of the signal | Signal |
1 | DCD | Input | Data carrier detect |
2 | RxD | Day off | Transmit data |
3 | TxD | Input | Receive data |
4 | DTR | Day off | Data terminal ready |
5 | GND | - | Ground |
6 | DSR | Input | Data set ready |
7 | RTS | Day off | Request to send |
8 | CTS | Input | Clear to send |
9 | R.I. | Input | Ring indicator |
We will be most interested in pins 2 (data transmission), 3 (data reception) and 5 (ground). This is the minimum set for two-way communication between devices.
I will not dwell on the description of the protocol in detail. For this there are GOSTs, etc. Therefore, we will go further and talk about how to control this beast.
Application
As already mentioned, RS-232 LAN levels are different from standard TTL levels. Therefore, we need to somehow convert the voltage values. Those. make 5V from +15V and 0V from -15V (and vice versa). One way (and probably the simplest) is to use a special MAX232 chip. It is easy to understand and can simultaneously convert two logic signals.
Below is a diagram of its inclusion:
![](https://i0.wp.com/housecomputer.ru/technology/interface/com-port/RS232.png)
I think there shouldn't be any difficulties. This is one of the options for using this chip: transferring data from a microcontroller to a computer and vice versa. The transmitted signal goes to the T pins x IN on one side and on R x IN on the other. Input signals removed from T x OUT and R x OUT respectively.
Programming
First, let's talk about programming ports at a low level. This will be more correct. I spent a lot of nerves understanding this interface until I began to delve into the principle of its operation at a lower level than simple character transmission. If this becomes clear, it means the same with languages high level there won't be any problems.
Below are the addresses of the COM ports that we will have to work with:
Port name | Address | IRQ |
COM 1 | 3F8h | 4 |
COM 2 | 2F8h | 3 |
COM 3 | 3E8h | 4 |
COM 4 | 2E8h | 3 |
They may vary. You can set the values in the BIOS settings. These are the base addresses. The addresses of the registers responsible for the operation of the ports will depend on them:
Address | DLAB | Read/Write | Abbreviation | Register name |
+ 0 | =0 | Write | – | Transmitter Holding Buffer |
=0 | Read | – | Receiver Buffer | |
=1 | Read/Write | – | Divisor Latch Low Byte | |
+ 1 | =0 | Read/Write | IER | Interrupt Enable Register |
=1 | Read/Write | – | Divisor Latch High Byte | |
+ 2 | - | Read | IIR | Interrupt Identification Register |
- | Write | FCR | FIFO Control Register | |
+ 3 | - | Read/Write | LCR | Line Control Register |
+ 4 | - | Read/Write | MCR | Modem Control Register |
+ 5 | - | Read | LSR | Line Status Register |
+ 6 | - | Read | MSR | Modem Status Register |
+ 7 | - | Read/Write | – | Scratch Register |
The first column is the address of the register relative to the base one. For example, for COM1: the LCR register address will be 3F8h+3=3FB. The second column is DLAB (Divisor Latch Access Bit) bit, which defines different purposes for the same register.. I.e. it allows you to operate 12 registers using only 8 addresses. For example, if DLAB=1, then by accessing address 3F8h we will set the value of the low byte of the clock generator frequency divider. If DLAB = 0, then when accessing the same address, the transmitted or received byte will be written to this register.
“Zero” register
It corresponds to registers for receiving/transmitting data and setting the generator frequency divider coefficient. As mentioned above, if DLAB = 0, then the register is used to record received/transmitted data, but if it is equal to 1, then the value of the low byte of the clock generator frequency divider is set. The data transmission speed depends on the value of this frequency. The high byte of the divider is written to the next memory cell (i.e. for the COM1 port it will be 3F9h). Below is the dependence of the data transfer rate on the divisor coefficient:
Interrupt Enable Register (IER)
If DLAB=0, then it is used as a register for controlling interrupts from an asynchronous adapter; if DLAB=1, then the high byte of the clock generator frequency divider is set in it.
Interrupt Identification Register (IIR)
An interrupt is an event that stops the execution of the main program and begins the execution of the interrupt routine. This register determines the type of interrupt that occurred.
Line Control Register (LCR)
This is the control register.
Bit 7 | 1 | Divisor Latch Access Bit – setting the data exchange speed | ||
0 | Normal mode (interrupt control, data reception/transmission) | |||
Bit 6 | Simulate line break (sends a sequence of multiple zeros) | |||
Bits 3 – 5 | Bit 5 | Bit 4 | Bit 3 | Parity selection |
X | X | 0 | No Parity | |
0 | 0 | 1 | Odd Parity | |
0 | 1 | 1 | Even Parity | |
1 | 0 | 1 | High Parity (Sticky) | |
1 | 1 | 1 | Low Parity (Sticky) | |
Bit 2 | Number of stop bits | |||
0 | 1 stop bit | |||
1 | 2 stop bits for 6,7 or 8 data bits or 1.5 stop bits for 5 data bits. | |||
Bits 0 And 1 | Bit 1 | Bit 0 | Number of data bits | |
0 | 0 | 5 bits | ||
0 | 1 | 6 bit | ||
1 | 0 | 7 bit | ||
1 | 1 | 8 bit |
Parity checking involves the transmission of one more bit - the parity bit. Its value is set so that the total number of ones (or zeros) in a packet of bits is even or odd, depending on the setting of the port registers. This bit is used to detect errors that may occur during data transmission due to interference on the line. Receiver Recalculates the parity of the data and compares the result with the received parity bit. If the parity does not match, then it is considered that the data was transmitted with an error.
The stop bit indicates the end of data transmission.
Modem Control Register (MCR)
Modem control register.
Bit | Meaning |
---|---|
0 | DTR line |
1 | RTS line. |
2 | Line OUT1 (spare) |
3 | Line OUT2 (spare) |
4 | Running diagnostics when the input of an asynchronous adapter is shorted to its output. |
5-7 | Equal to 0 |
Line Status Register (LSR)
A register that determines the state of the line.
Bit | Meaning |
---|---|
0 | Data received and ready to be read, automatically reset when data is read. |
1 | Overflow error. A new byte of data was received, but the previous one had not yet been read by the program. The previous byte is lost. |
2 | Parity error, cleared after reading line status. |
3 | Synchronization error. |
4 | A request to interrupt transmission "BREAK" was detected - a long string of zeros. |
5 | The transmitter holding register is empty and a new byte can be written to it for transmission. |
6 | The transmitter shift register is empty. This register receives data from the holding register and serializes it for transmission. |
7 | Timeout (device is not connected to the computer). |
Modem Status Register (MSR)
Modem status register.
Well, that's all. By operating these registers, you can directly communicate with the COM port and control the transmission and reception of data. If you don’t want to tinker with memory, you can use ready-made components for various programming environments: C++, VB, Delphi, Pascal, etc. They are intuitive, so I think there is no need to focus on them here.
A serial port is an I/O device. As an I/O device, it is only a path for transferring data to and from the computer. There are also many other I/O devices such as serial ports, parallel ports, disk controllers, network cards, Universal Serial Bus devices, etc. Most computers have one or two serial ports. Each has a 9-pin connector (sometimes 25-pin) (Fig. 1) on the back wall of the computer system unit. Programs can send data (bytes) through a send data pin (output) and receive bytes through another data receive pin (input). All other contacts are used for control and ground.
) is somewhat more than just a connector. It converts data from parallel to serial and changes the electrical representation of the data. Inside a computer, data bits are transmitted in parallel (using multiple wires to transmit data simultaneously). A serial data stream is a sequence of bits over just one wire (such as the transmit and receive data wire on the serial port connector). This is what this device serves to create such a data stream from parallel to serial (inside the computer) and transmit it to the data transfer contact (and, accordingly, vice versa).
Majority electronic components serial port is concentrated in one computer chip (microcircuit) called UART.
Contacts and wires
Older computers use 25-pin connectors, but only 9 pins are actually used today. Each of the 9 contacts is usually connected to a wire. Except for two wires for transmitting and receiving data, the rest are used for control and ground. The voltage at each of the pins and wires is measured relative to the signal ground. Therefore, the minimum number of wires for bidirectional data transmission is 3. In rare cases, two wires (without signal ground) may be enough for operation, but this can lead to low performance and sometimes errors in data transmission.
There are still a few wires left that are intended only for control (monitoring) and are not used for data transmission. All these signals could be transmitted over one line, but instead, separate wires are allocated for them. Some (or all) of these signal lines are called "modem status lines." The status lines can be in one of two states: set (on) +12 volts or reset (off) -12 volts. One of these wires signals the computer to stop sending data through the serial port. Others in turn signal the device connected to the serial port to stop sending data to the computer. If the connected device is a modem, then the remaining lines may indicate to the modem that it needs to seize the telephone line or signal to the computer that a connection has been established or that there is a call on telephone line(means someone connects to the computer). See the Contacts and Signals section for more complete information.
RS-232 or EIA-232, etc.
Serial port) (not to be confused with USB) usually follows the standard RS-232-C, EIA-232-D, or EIA-232-E. These are three designations for the same thing. The main RS standard (Recommended Standard) received the prefix EIA (Electronics Industries Association) and later EIA/TIA after the EIA organization was merged with TIA (Telecommunications Industries Association). The EIA-232 specification also covers synchronous data transfer, but in most cases synchronous data transfer is not supported by the chips in computers. The RS designation is obsolete but is still widely used. EIA will be used more frequently later on this site. Some documents use full designation EIA/TIA.
Data Communication (Baud Rates)
Data (the bytes that make up letters, pictures, etc.) passes through the serial port. Data rates (such as 56k (56000) bps) are called (incorrectly) "speed". Most people incorrectly say "speed" instead of "speed factor".
It is important to know that the average data transfer speed is often less than the maximum declared. There are delays (or periods of waiting) and as a result the speed becomes slower. These delays may increase depending on the type of data transmission control. Even in best case scenario There are always delays between bytes, even small ones (a few microseconds). If a device connected to the computer via a serial port cannot work on full speed, then the average speed must be reduced.
Data transmission control
Data transmission control means the ability to limit the data flow through the serial port. For serial port this means you can stop and then resume data transfer without losing any bytes.
So we got to the COM port. But with it everything is not as simple as with LPT, and its full use will require much more effort. The main problem is also its main advantage - serial data transfer. If in LPT a byte of data is transmitted along 8 lines, a bit per line, and the state of each line could be easily viewed, then in the COM port a byte of data is transmitted bit by bit along one line (relative to ground, of course) and see what is transmitted there with LEDs alone won't do it. To do this, you need a special device - a converter of a serial data stream into a parallel one, the so-called. USART (Universal Synchronous/Asynchronous Receiver Transmitter). For example, it is included in the motherboard of a computer equipped with a COM port, or in any more serious microcontroller. |
I hope you are still discouraged in mastering the COM port. It's not all doom and gloom. Some results can be obtained without USART. Let us formulate a problem that we will implement on initial stage working with COM port:
"I would like an LED to be connected to the computer via the COM port. I launch the program. I perform some action in this program, the LED lights up, I do something else - the LED goes out."
The task is quite specific (taking into account the fact that USART is not used) and is a pure “do-it-yourself” task, but it is quite feasible and workable. Let's start implementing it.
1.COM port
We take it again system unit of your PC and look at the rear. We note there is a 9-pin connector - this is the COM port. In reality there may be several of them (up to 4). My PC has two COM ports (see photo).
2. COM port extension
3. Hardware
We will also have to “tinker” with the hardware, in the sense that it will be more complicated than with the first device for LPT port. The fact is that the RS-232 protocol, through which data is exchanged in the COM port, has a slightly different logical state-voltage relationship. If usually this is logical 0 0 V, logical 1 +5 V, then in RS-232 this relationship is as follows: logical 0 +12 V, logical 1 -12 V.
And for example, having received -12 V, it is not immediately clear what to do with this voltage. Typically, RS-232 levels are converted to TTL (0.5 V). The simplest option is zener diodes. But I propose to make this converter on a special chip. It's called MAX232.
Now let's see what signals from the COM port can we see on the LEDs? In fact, there are as many as 6 independent lines in the COM port, which are of interest to the developer of interface devices. Two of them are not yet available to us - serial data lines. But the remaining 4 are designed to control and indicate the data transfer process and we can “transfer” them to suit our needs. Two of them are designed for control from the side external device and we won’t touch them for now, but we’ll use the last two remaining lines now. They are called:
- RTS- Request for transfer. An interaction line that indicates that the computer is ready to receive data.
- DTR- The computer is ready. An interaction line that indicates that the computer is turned on and ready to communicate.
Now we transfer their purpose a little, and the LEDs connected to them will either go out or light up, depending on the actions in our own program.
So, let's put together a diagram that will allow us to carry out our intended actions.
And here is its practical implementation. I think you will forgive me that I made it in such a dumb breadboard version, because I don’t want to make a board for such a “highly productive” circuit.
4. Software part
Everything is simpler here. Let's create a Windows application in Microsoft Visual C++ 6.0 based on MFC to manage two lines of COM port communication. To do this, create a new MFC project and give it a name, for example, TestCOM. Next, select the option of constructing based on dialogue.
Give appearance dialog window of our program, as in Fig. below, namely add four buttons, two for each of the lines. One of them is respectively necessary to “extinguish” the line, the other to “set” it to one.
Class CTestCOMDlg: public CDialog ( // Construction public: CTestCOMDlg(CWnd* pParent = NULL); // standard constructor HANDLE hFile;
In order for our program to control the lines of a COM port, it must first be opened. Let's write the code responsible for opening the port when loading the program.
HFile = CreateFile("COM2", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0,NULL); if(hFile==INVALID_HANDLE_VALUE) ( MessageBox("The port could not be opened!", "Error", MB_ICONERROR); ) else ( MessageBox("The port was successfully opened", "Ok", MB_OK); )
Using the standard function Win API CreateFile() open the COM port COM2. Next, we check the success of the opening with the output information message. Here we need to make an important note: COM2 is on my computer, but on your computer you could connect it to another COM port. Accordingly, its name needs to be changed to whatever port you are using. You can see what port numbers are present on your computer like this: Start -> Settings -> Control Panel -> System -> Hardware -> Device Manager -> Ports (COM and LPT).
As a result, the function CTestCOMDlg::OnInitDialog(), located in the file TestCOMDlg.cpp, our dialogue class should take the form:
BOOL CTestCOMDlg::OnInitDialog() ( CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); ) ) // Set the icon for this dialog. The framework does this automatically // when the application"s main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here hFile = CreateFile("COM2", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0,NULL); if(hFile==INVALID_HANDLE_VALUE) ( MessageBox("Could not open port!", "Ostbk", MB_ICONERROR); ) else ( MessageBox("Port successfully opened", "Ok", MB_OK); ) return TRUE; // return TRUE unless you set the focus to a control )
Now let's add handlers for line control buttons. I gave them appropriate names: the function that sets one on the DTR line is OnDTR1(), 0 is OnDTR0(). For the RTS line, in the same way. Let me remind you that the handler is created when you double click on the button. As a result, these four functions should look like:
Void CTestCOMDlg::OnDTR1() ( // TODO: Add your control notification handler code here EscapeCommFunction(hFile, 6); ) void CTestCOMDlg::OnDTR0() ( // TODO: Add your control notification handler code here EscapeCommFunction(hFile, 5); ) void CTestCOMDlg::OnRTS1() ( // TODO: Add your control notification handler code here EscapeCommFunction(hFile, 4); ) void CTestCOMDlg::OnRTS0() ( // TODO: Add your control notification handler code here EscapeCommFunction(hFile, 3);
Let me explain a little how they work. As you can see, inside they contain a call to the same Win API function EscapeCommFunction() with two parameters. The first of them is a handle (HANDLE) to an open port, the second is a special action code corresponding to the required line state.
That's it, we compile and launch. If everything is fine, you should see a message about the successful opening of the port. Next, by pressing the corresponding buttons, we blink the LEDs connected to the COM port.
© Ivanov Dmitry
December 2006