Menu English Ukrainian russian Home

Free technical library for hobbyists and professionals Free technical library


ENCYCLOPEDIA OF RADIO ELECTRONICS AND ELECTRICAL ENGINEERING
Free library / Schemes of radio-electronic and electrical devices

How to connect a microcontroller and a computer via RS-232. Encyclopedia of radio electronics and electrical engineering

Free technical library

Encyclopedia of radio electronics and electrical engineering / Microcontrollers

Comments on the article Comments on the article

This article was conceived as an example of the implementation of the development of a microcontroller device controlled by a personal computer via a serial channel. It is intended for those who do not yet have experience in such developments. Once you understand how the PC controls the microcontroller, displays, processes and stores the information received from it, you can apply this knowledge to your own developments. In addition, the described device also has an independent value: it is a controlled digital voltmeter, the measurement results of which, before displaying, can be processed by a computer according to a predetermined algorithm, and also saved in a file on your PC's hard drive, viewed and printed. All this makes the described device the basis for a simple system for collecting, processing and documenting data, useful for electronics engineers who have insufficient knowledge of microcontroller technology for independent development.

Introduction

The purpose of this work was to develop and create the simplest measuring device based on the microcontroller of the x51 family, which is still the most common today, which could exchange information with a personal computer. It was supposed to implement a voltage meter in the device, which could later be supplemented with various prefixes that convert other directly measured physical quantities into voltage. Such a device would make it easy to carry out a series of measurements, being controlled by a computer, as well as to accumulate the results and carry out their computer processing. Subjected to minor changes, it could easily turn into a system for remote monitoring and control of equipment or other instruments and devices.

General description of the device. Electrical part of the device

The device (Fig. 1), in fact, is a digital voltmeter. At the input of the voltmeter is an operational amplifier (DA1), which has a high input impedance. The operational amplifier is followed by an ADC (DD2), which allows us to digitize the voltage of interest to us for subsequent transmission to the microcontroller. The DD3 microcontroller is the main control element of the device, as it reads information from the ADC and communicates with a personal computer via a serial channel. The device also includes power converters for generating +5 V for the digital part and for generating +/-10 V for the operational amplifier, as well as a level conversion chip (logic <0> and <1> to -15: +15 V and vice versa) for the exchange of information over a serial channel such as RS232.

How to connect a microcontroller and a computer via RS-232
Rice. one

The value sent to the computer lies in the range 0...4095 (which corresponds to the ADC bit depth), 0 corresponds to the input level 0V, 4095 - the level 5V, the dependence is linear.

The information exchange rate can be selected as less than 9600 baud, and higher - up to 115 baud. On fairly old computers, such as 200 and earlier, the upper limit is much lower - 386 baud. This is because the serial port chips installed in these computers were not designed for higher speeds.

Description of chips

MAX680 Power Supply Converter

Op-amps typically require a bipolar power supply (for example, +10 V and -10 V to ground). Radio amateurs who are little familiar with the modern element base usually use a transformer with two secondary windings (or with one, but with a tap from the middle), two filter capacitors, two stabilizers, etc. to obtain such a voltage. However, if you have at your disposal stabilized voltage is 5V, and the used operational amplifier, which requires a bipolar supply, can get by with only +7:10 V, while consuming 1:2 mA, then the two windings and two stabilizers mentioned are not needed. It is enough to use the MAX680 chip from Maxim (note that such chips are produced by Linear Technology and a number of other well-known companies).

A voltage Uin is supplied to the input of the microcircuit, ranging from 3:5 to 6:10 V (depending on the type), voltages equal to approximately + 2Uin are formed at its outputs. It is remarkable that, firstly, in addition to the 8-pin MAX680 or LT1026, only 4 small electrolytic capacitors are needed to form these voltages (see Fig. 1), and secondly, when the input voltage changes, the doubled output voltage changes in phase, which practically does not affect the output signal of the op-amp. For a more detailed acquaintance with such microcircuits, the author recommends referring to the corresponding company descriptions.

ADC MAX1241

In recent years, in microcontroller technology, microcircuits controlled via a serial channel have been widely developed. One of these microcircuits is the 12-bit ADC MAX1241. As in the case of MAX680, MAX1241 has quite a lot of exact and approximate analogues (MAX187 from Maxim, LTC1286, LTC1298 from Linear Technology, AD7894 from Analog Devices and a number of others).

MAX1241 is packaged in an 8-pin package, powered by a voltage of 2,7 to 5 V, consuming a current of about 5 mA. It requires the use of an external reference voltage source (in this case, a precision zener diode KR142EN19 is used, which generates a voltage of 2,50 V) and uses only 3 lines to communicate with the microcontroller.

The operation of MAX1241 is illustrated by the timing diagrams shown in fig. 2. Prior to conversion and exchange, the CS# MAX1241 input must be maintained by the microcontroller in a single state. To start the conversion, a logic zero level must be applied to this input. The conversion process in MAX1241 takes just under 8 µs. During the entire conversion time, MAX1241 maintains a logic 0 level at its DOUT output. After the conversion is completed, MAX1241 sets the DOUT output to a single state.

How to connect a microcontroller and a computer via RS-232
Rice. one

Before starting the conversion, the microcontroller at the SCLK MAX1241 input must set the zero logic level. When the conversion process inside the ADC is completed, the microcontroller must generate a sequence of at least 12 positive pulses at the SCLK input (Fig. 2). The rising edge of the first pulse prepares the MAX1241 for data transmission. On the decline of the pulse on DOUT, the most significant 12th bit appears as a logical zero or one. The microcontroller reads this bit, generates the front of the second pulse on SCLK, and after a while - its decline. By the fall of the second pulse, the 11th bit, which is then read by the microcontroller, appears on DOUT, etc.

On the decline of the 12th pulse, the least significant 1st bit is set at the DOUT output. The fall of the 13th pulse puts DOUT in the zero state, in which it is before the CS# input is set to 1. By transferring CS# to a single state, the microcontroller informs MAX1241 about the completion of the process of reading the result of the conversion. The next MAX1241 conversion can take about 1 µs after setting CS# to 1.

The operation algorithms of LTC1286, LTC1298 from Linear Technology and AD7894 from Analog Devices differ slightly from those described for MAX1241. More details can be found by referring to the respective company descriptions.

Level converter MAX202E

It is not a secret for anyone that in standard logic one is represented by a voltage level from 2,4 to 5 V, and zero - from 0 to 0,8 V. However, beginners may not be aware that zero and one are transmitted over the RS-232 channel. are encoded with the same value (from 5 to 12 V), but different in sign signals. Within the framework of this article, it is not intended to explain why it is customary to do this and not otherwise - we will confine ourselves to stating this fact.

Since standard logic signals must be converted to signals of another level for transmission via RS-232, it is necessary to provide appropriate means of conversion in the circuit. About 10 years ago, specially designed cascades of three or four transistors, a pair of diodes and almost a dozen resistors were used for this purpose. Now the situation has changed significantly: the leading manufacturers of microcircuits produce completely finished converters that require a minimum number of additional elements. These include MAXIM's MAX202E and AD232 from Analog Devices, which is completely identical to it, right down to the pinout. Inside, both microcircuits contain a +5 V to +10 V voltage converter, identical to the MAX680 described above, and cascades that convert standard-level logic signals into RS-232 level signals. Each of these microcircuits contains logic level converters for two receivers and two transmitters. We will use only one transceiver channel.

Mode of operation of the MK with a serial channel

As you know (see, for example, issues 10 and 11 of the Radio magazine for 1994), microcontrollers of the x51 family have four modes of transceiver operation. We will be interested in mode 1 as the simplest and most acceptable.

Mode 1 is characterized by the following parameters:

  • asynchronous information exchange;
  • 10 bits are transmitted per exchange act (start bit (0), 8 data bits and stop bit (1));
  • the rate of reception / transmission is programmable and is set by a timer.

This is a convenient mode for programming: very little programming code is required to set up and operate the transceiver. Although you can use other modes of operation if you wish. The purpose of this article is to describe a device that has the ability to communicate with a personal computer.

We will not give here a description of how exactly the transceiver works. This information can be gleaned from the mentioned magazines "Radio" or other literature.

Basic routines for MK

The main routines for the microcontroller will be: reading data from the ADC, initializing the UART, receiving a byte and sending a byte.

Reading data from ADC

Setting up a PC to exchange information over a serial link.

In order to set up a PC to exchange information over a serial channel, you must do the following:

  • disable all interrupts, since there is no need to use them;
  • set timer 1 to work in mode 2 with automatic content reloading. This is necessary to set the speed of information exchange and maintain it constant;
  • load initial values ​​into the timer counter;
  • start timer 1.

An example of a code designed for an exchange rate of 9600 bps for a quartz resonator with a resonant frequency of 11,059 MHz:

GET_VOLT: SETB DOUT ; ALLOWED DATA ENTRY FROM ADC SETB CS ; SET INITIAL STATE ADC CLR SCLK ; SET INITIAL STATE ADC CLR CS ; REPORTED TO READ MUL AB DATA; 4 MKS AT 12 MHZ\ MUL AB ; 4 ISS | MULAB ; 4 ISS} WAIT FOR THE END; | DIGITATIONS MUL AB ; 4 MKS / MOV R0,#12 ; READ 12 BIT GET_VC: SETB SCLK ; \ NOP ; | NOP ; | CLR SCLK ; }HAVE GENERATED A PULSE FOR READING BIT NOP ; | NOP ; / MOV C, DOUT ; READ BIT MOV A, R2 ; \ RLC A ; | MOV R2,A ; | MOV A, R3 ; } PUSH BIT INTO WORD ; | RESULT - R3R2 RLC A ; | MOV R3,A ; / DJNZ R0,GET_VC ; LOOP ANL A,#0FH MOV R3,A ; CLEARED HIGH BITS R3R2 SETB CS ; DO NOT WANT TO READ OUT ; (REMAINING BITS = 0) MUL AB ; 4 MKS AT 12 MHZ \ MUL AB ; 4 ISS | MULAB ; 4 ISS | MULAB ; 4 µs }MIN DELAY ; | BEFORE NEXT MULAB ; 4 ISS | MULAB ; 4 ISS / RET   

This subroutine is called the very first in the main microcomputer program. In principle, it can not even be designed as a subroutine.

Receiving and sending a byte

The routines for receiving and sending a byte over a serial link are very simple.

SERINIT: MOV IE, #0 ; Disable all interrupts MOV TMOD, #20H ; Set mode 2 for timer 1 MOV TH1, #REL96 ; Value for autoreloading counter MOV TL1, #REL96 ; Initial counter value for 9600 bps ; with SMOD = 0 ANL PCON, #7FH ; Cleared SMOD MOV SCON, #50H ; Mode for 8 bits of data and baud rate, ; timer dependent SETB TR1 ; Start timer/setter 1 RET where REL96 is a constant equal to 0FDh

A byte can only be read from the SBUF I/O port when the RI bit in the SCON control/status register is set, indicating the presence of a byte in the receive buffer. After reading this byte, the RI bit must be reset.

After writing a byte to the I / O port, you need to wait for the TI bit to be set, which will signal the end of sending the byte to the line. Then the TI bit will also need to be reset.

Subroutine for receiving a byte into the accumulator:

GETCH: JNB RI, GETCH MOV A, SBUF CLR RI RET

Subroutine for sending a byte from the accumulator:

PUTCH: MOV SBUF, A SEND: JNB TI, SEND CLR TI RET

It should also be noted that the microcomputer does not have any means for detecting I/O errors.

In order to organize the check in a hardware-software way, it is possible to expand the number of input / output lines through which additional signals will be transmitted, and it will be possible to determine the states in which the participants in the dialogue are located, as well as detect errors.

It is possible to increase the reliability of receiving/transmitting information in another way: to transmit one more bit with eight data bits - the parity bit, which is calculated similarly to the parity flag in the program status word (bit 0 PSW). Only it should be calculated for the transmitted or received byte. After receiving the byte and the parity bit, you need to compare them to match each other. If they do not match, then an I/O error has occurred. To transfer an additional 9th ​​information bit, you must use the mode 2 or 3 of the timer / counter.

General program for MK. Device State Diagram

The general microcomputer program is based on the algorithm described below. The algorithm is rather complicated, because still, you need to somehow, at least programmatically, detect input / output errors and respond to their appearance.

For greater clarity, the algorithm, described in ordinary words, is accompanied by a figure - the so-called device state diagram (Fig. 3), which shows the four main states of the device in terms of information exchange with a computer.

How to connect a microcontroller and a computer via RS-232
Rice. one

Let us stipulate in advance the fact that our micro-computer is a slave, and a personal computer is a leader in data exchange. In other words, the device itself, without an order from the PC, should not do anything. It is completely subordinate to the control computer. The personal computer is chosen as the leader for the simple reason that it has more power and is able to control the device without any special problems. In addition, it can give the user more service functions.

State one - Wait

The device is in this state immediately after switching on the supply voltage. Here it waits for an initialization request from the computer, which is expressed in the computer sending the NUL character. The device, in turn, must, in response to the received request, enable and configure, if necessary, additional modules and resources, and then, if everything went well, send an ACK symbol to the computer. In case of an error, it should send a NAK. Thus, the first "communication" of two "interlocutors" takes place. If you like, they should "exchange greetings" or "shake hands".

If the device initializes successfully and then sends an ACK character, it automatically moves to the next state. This transition is indicated by arrow 1 in the diagram.

Ready state

In this state, our micro-computer is waiting for a PC request to send the measured value read from the ADC. The request is an XON character. Upon acceptance of this symbol, the device enters a new state - Sending. Arrow 2 corresponds to the transition.

Sending state

Getting here, the microcontroller reads a binary twelve-bit number from the ADC by the previously indicated method and sends it in parts to the computer. This implementation converts the binary number to its three-character hexadecimal equivalent, such as <1FF> for decimal 511. Send <1> first, then and another .

Upon completion of transferring the value to the computer, the micro-computer passes to the next state according to arrow 4.

Sent State

This state is the last and, as it were, closes the circle of a single act of communication between the device and the computer. Here, the computer is expected to confirm that it has correctly received the value that was addressed to it.

There are several options for the PC to respond to the sent number: it can answer about successful reception with the XOFF symbol, which will mean that no other values ​​​​are required yet, or it can answer with the XON symbol, which means that one more value is needed. If XOFF is received, then the device returns to the Ready state (transition 7 in the diagram). If the XON symbol is received, then the device again finds itself in the Sending state (transition 5) and repeats the reading from the ADC with the subsequent transfer of the number to the line. The only case that was not considered was when the PC did not like what it received: for example, instead of characters in the range <0>...<9>, ...He got something different or <,>. In this situation, it sends a NAK character to our device, which should be interpreted as a request to resend the last value, which happens: the device is again transferred to the Sending state (transition along arrow 6).

The transitions indicated by arrows 3 and 8 of the diagram remained undescribed. If the computer detects a serious I/O error or needs to stop communicating with the device, then it will simply send an initialization NUL, which will initialize the device and put it in the Ready state.

Those. Whatever state our device is in, it must respond to the initialization request in the same way as during the initial initialization (see the Wait state item). If the microcomputer received some unexpected or incorrect character or request, then it should always respond to it with the NAK character.

Such a strategy is advantageous, since such an organization of the program for the device makes it easier to perform several tasks at once: microcomputers and PCs will not play a damaged phone, and, secondly, they will be able to simply and effectively "communicate" with each other. with a friend.

Let's move on to PC. General program for PC. PC State Diagram

Fundamentally, a common program for a computer will not differ in any way from that used in a microcontroller. The algorithm will be similar, and the state diagram will be similar.

First State Initialization

The computer gets here when the user presses a key on its keyboard that corresponds to accepting a single value. In this state, the computer sends a NUL initialization character to the device and waits for an ACK or NAK response. If an ACK was received, then the initialization went well and you can continue working - go to the next state according to arrow 2 in the diagram. If the NAK is received, the operation should stop and the computer should go to the final state Done, following arrow 1.

Ready state

In this state, the computer prepares to receive the characters that will make up the value requested from the microcomputer. There are two requests to send a value. The first is a normal value request, and is matched by the XON character.

The second request is a request to resend the last value. This is necessary if the value has not been accepted completely for some objective time or incorrect characters have been received that do not fall in the ranges from <0> to <9> and from to . For a retransmission request, the character NAK is allotted.

Next, after preparing to receive the value characters, one of the two above requests to our device occurs, then the computer moves along arrow 4 to the state of receiving the value.

Receiving state

Here the PC simply reads three characters of the value measured and converted by the ADC. As mentioned earlier, there is some objective time for the computer to wait for a character. If the character has not been read during this time, then this situation is interpreted as erroneous, i.e. an I/O error has occurred.

By the way, at fairly high information exchange rates (more than 19200 bps) or when working in the MS-Windows operating system (any version), it often happens that a computer receives only two of the three characters sent to it, and sometimes even less - one . To prevent the computer from "hanging" - waiting for an infinitely long missing or missing character - some time is introduced to limit this expectation. Unfortunately, these omissions are not detected by the hardware method.

This implementation defines two types of timeout that can be set by the user from the keyboard. The first type is the timeout for 1 of 3 characters. It allows the device to calmly, without hurrying, measure, digitize the number we need and convert it to a symbolic equivalent. And the second type is the time limit for sending the second and third characters.

Now let's move on to possible transitions from the Receiving state to other states.

If all 3 characters of the value have not been received in the allotted time, then the computer must ask our device to send it the value again. This situation corresponds to the transition along arrow 5, i.e. the computer makes a request with a NAK character and transitions back to the Ready state.

If an I/O error was detected during the reception by the computer (and the PC has such an opportunity to analyze the serial port status register enough), then it is better to reset both the computer and the micro-computer to its original state, i.e. repeat initialization. Therefore, arrow 3 is also present in the diagram.

And, finally, if the computer has received all three characters from the device, then it goes into the analysis state of the received value - into the Received state along arrow 8.

Publication: cxem.net

See other articles Section Microcontrollers.

Read and write useful comments on this article.

<< Back

Latest news of science and technology, new electronics:

Machine for thinning flowers in gardens 02.05.2024

In modern agriculture, technological progress is developing aimed at increasing the efficiency of plant care processes. The innovative Florix flower thinning machine was presented in Italy, designed to optimize the harvesting stage. This tool is equipped with mobile arms, allowing it to be easily adapted to the needs of the garden. The operator can adjust the speed of the thin wires by controlling them from the tractor cab using a joystick. This approach significantly increases the efficiency of the flower thinning process, providing the possibility of individual adjustment to the specific conditions of the garden, as well as the variety and type of fruit grown in it. After testing the Florix machine for two years on various types of fruit, the results were very encouraging. Farmers such as Filiberto Montanari, who has used a Florix machine for several years, have reported a significant reduction in the time and labor required to thin flowers. ... >>

Advanced Infrared Microscope 02.05.2024

Microscopes play an important role in scientific research, allowing scientists to delve into structures and processes invisible to the eye. However, various microscopy methods have their limitations, and among them was the limitation of resolution when using the infrared range. But the latest achievements of Japanese researchers from the University of Tokyo open up new prospects for studying the microworld. Scientists from the University of Tokyo have unveiled a new microscope that will revolutionize the capabilities of infrared microscopy. This advanced instrument allows you to see the internal structures of living bacteria with amazing clarity on the nanometer scale. Typically, mid-infrared microscopes are limited by low resolution, but the latest development from Japanese researchers overcomes these limitations. According to scientists, the developed microscope allows creating images with a resolution of up to 120 nanometers, which is 30 times higher than the resolution of traditional microscopes. ... >>

Air trap for insects 01.05.2024

Agriculture is one of the key sectors of the economy, and pest control is an integral part of this process. A team of scientists from the Indian Council of Agricultural Research-Central Potato Research Institute (ICAR-CPRI), Shimla, has come up with an innovative solution to this problem - a wind-powered insect air trap. This device addresses the shortcomings of traditional pest control methods by providing real-time insect population data. The trap is powered entirely by wind energy, making it an environmentally friendly solution that requires no power. Its unique design allows monitoring of both harmful and beneficial insects, providing a complete overview of the population in any agricultural area. “By assessing target pests at the right time, we can take necessary measures to control both pests and diseases,” says Kapil ... >>

Random news from the Archive

Squid cage camouflage 26.02.2022

Researchers at the University of Pennsylvania have developed an artificial version of squid and octopus cells called chromatophores. In nature, these cells help cephalopods to change their color to match the shades of the environment.

Chromatophores are special cells of octopuses and squids. Inside they contain elastic membranes that can expand and contract in response to external stimuli. This allows the clams to camouflage themselves in the environment and also scare away other predators.

In the study, the engineers also used thin and flexible membranes made from a liquid crystal polymer network. The membranes are placed over tiny cavities, each of which can be "inflated" to the desired volume. As the membrane stretches, it decreases in thickness and changes color.

As a result, it turned out to create a completely artificial chromatophore, which is able to instantly change its color.

The scientists then measured the pressure levels needed to give the chromatophores each desired color. This allowed them to program the camouflage like display pixels.

The resulting prototype is able to create checkerboard patterns, as well as merge with the shade of the surrounding surface.

Other interesting news:

▪ Premium electric car Mercedes-Benz EQS

▪ Free Internet from Facebook

▪ Beta Music Audio Systems by Infinity

▪ First anion in space

▪ Dandelion Sensors

News feed of science and technology, new electronics

 

Interesting materials of the Free Technical Library:

▪ section of the site Life of remarkable physicists. Article selection

▪ article fail. Popular expression

▪ article What is pop music? Detailed answer

▪ article Instruction on labor protection

▪ article Laying wires on rollers. Encyclopedia of radio electronics and electrical engineering

▪ article Electric stove for the owner. Encyclopedia of radio electronics and electrical engineering

Leave your comment on this article:

Name:


Email (optional):


A comment:





All languages ​​of this page

Home page | Library | Articles | Website map | Site Reviews

www.diagram.com.ua

www.diagram.com.ua
2000-2024