Current and voltage meter on the microcontroller. Measurement of the effective value of voltage. Schematic diagram of a voltmeter for measuring AC voltage

Often it is required to measure the power of a particular electrical equipment. In addition, sometimes it is useful to know both the load current I and the voltage U, and not just the power (it doesn’t matter which one), but both the total P and the active S (they are often confused and not always specified which of them is meant in one way or another). Also, in a number of specific cases, it is required to know the power factor of the network, equal to P / S (aka cosine φ (phi) - the phase angle between voltage and current), reactive power Q and φ itself.

An explanation of various electrical terms and deep theoretical foundations is beyond the scope of this article, all this can be found in specialized sources, such as textbooks on TOE (for example) and a number of publications on the Internet.

An ordinary multimeter will not help in solving the above problems, because. having measured, even if simultaneously (with 2 devices), the load current and the voltage in the network, we can only get S = UI, and all other parameters remain inaccessible, because U and I alone are not enough to calculate them.

Available solutions

To solve these problems, there are special devices - wattmeters and universal volt-ampere-phase meters, but since. they are special equipment, and not general-purpose devices, they are quite difficult to find and sometimes they are not cheap. In addition, such devices do not always show all the parameters at once. There are very simple and cheap designs on the Internet, for example, but they are very highly specialized (for example, it measures only φ).

The Atmel company publishes, as one of the examples of using the MK AVR, a description of the design of a certain electricity meter on an accessible element base -. But as a measuring device, this product is hardly suitable, because. shows only the consumed power on an electro-mechanical meter with wheels with numbers (similar to household electricity meters).

The author of the article managed to find a fairly versatile device on the Internet -. This is a wattmeter built on the ATMega8 MK, measuring all of the above parameters. But upon detailed analysis, it turned out that the device has many shortcomings, some of which are indicated in that article. This is also discussed in more detail below.

The company offers a whole range of different electrical measuring chips (Energy-Meter IC) designed for building electric meters and solving other electrical measuring tasks. They are not very expensive, they have detailed technical documentation and many examples of their use in conjunction with various microcontrollers, but, unfortunately, these microcircuits are far from everywhere and are not always available (sometimes it’s easier to find some decommissioned or slightly broken electric meter with which -or a microcircuit than the microcircuit itself), which for the author of the article was the main reason for refusing to use them in the proposed device.

At the same time, all the tasks described above are quite “too tough” for conventional AVR MKs, which are much more affordable and sometimes cheaper than AD microcircuits. Moreover, to create a universal measuring device, you still cannot do without MK and other nodes.

Variable voltage/current, power and frequency measurement methods

Before considering the design of the device itself, it is necessary to dwell on some theoretical aspects of measuring alternating voltage, current and other parameters of the electrical network.
We note right away that we will measure the root-mean-square values ​​\u200b\u200bof voltage and current, as most closely corresponding to the usual effective values ​​\u200b\u200b-.

Any signal before measurement must be normalized - i.e. bring it to the allowable range and other parameters of the measuring unit used. In our circuit, the measuring unit is an ADC integrated into the AVR MK, capable of measuring voltage in the range of 0-5V. Applying other voltages to it (negative or large 5v) will lead to failure, at best, only the ADC, at worst, the entire MK.

Mains AC voltage measurement is in 2 points:

  1. "Somewhere to put" the negative half-wave of the sinusoid, because it does not fall within the range of the ADC.
  2. Make sure that the maximum (amplitude) value of the positive half-wave does not exceed 5v.

In the simplest case, both points are solved by a series-connected diode and a voltage divider (you can use ordinary resistors plus a multi-turn potentiometer to facilitate tuning).
A correctly turned on diode plays the role of a half-wave rectifier and cuts off the negative half-wave, not passing it into the further circuit.

The divider reduces (scales) the voltage to the desired range. The division factor should be selected based not on the standard 220v, but at least on the basis of 260v, because the voltage in the network is extremely rarely 220v, it often fluctuates within certain limits and, in addition, there are often short-term “emissions” (high voltage) and “dips” (low voltage).

Such a circuit is simple, cheap, reliable and has sufficient accuracy, as a result of which the vast majority of AC voltmeters, both digital and analog, are based on it. The device works on the same principle.

To obtain a real voltage, it is necessary to multiply the measured voltage at the input of the ADC by the division factor of the divider and by 2, to “compensate” the negative half-wave cut off by the diode.
The disadvantages of this approach are:

  1. Only an ideal diode cuts off the negative half-wave voltage at zero level. Real diodes open a little later, at a voltage of + 0.4 .. + 1v. Those. we always lose part of the positive half-wave.
  2. Multiplication by 2 when calculating the real operating voltage is valid only for a true sinusoid, i.e. when the negative half-wave is absolutely symmetrical to the positive half-wave of the same period. In real power networks, in the presence of a lot of pickups, reactive loads, and other factors, we can say that the halves of the sinusoid are generally asymmetric. Therefore, multiplication by 2 carries some additional error, which cannot be reliably estimated (and taken into account).

However, in conditions of a constantly changing voltage in amplitude and in the effective value of the voltage, these errors can be ignored.

There is another way to measure voltage - to “fit” the entire sinusoid into the range 0..+5V. To do this, you need to “raise” it by half the range of the ADC (i.e., by +2.5 V) and adjust the divider so that the entire sinusoid lies between 0 and + 5V.

In this case, both disadvantages are eliminated - no diode is needed and the ADC measures both voltage half-waves with all their "features". In further calculations, it is also necessary to somehow take into account the + 2.5v added by the circuit. But with the help of software (computing) tools of the microcontroller, this is very easy to do.
The only visible disadvantage of this method is the division coefficient d.b. 2 times more (since we enter both half-waves, and not one), which increases the measurement error. But again, under conditions of constantly changing voltage in amplitude and value, this does not lead to noticeable errors.

There are at least two circuit solutions of this method - dividers and capacitors, as in the mid-point shaper used in the circuit of the proposed device (the same + 2.5v) on the op-amp.
But the dividers do not provide galvanic isolation of the measured network and our device. This creates a number of inconveniences.

So, a device without galvanic isolation must be used with extreme caution, it must not be grounded, it is necessary to carefully isolate all circuit nodes from the environment and take some other precautions. In addition, if we want to transfer the measurement results somewhere, say to a PC, we will not be able to connect our device directly, for example, to a COM port through a simple MAX232 type converter. To do this, you will have to untie all communication lines, for example, with optocouplers, etc.

To overcome this shortcoming, you can put a conventional step-down transformer in front of the divider (as in a power supply unit) and adjust the division factor first to fit the sinusoid into the ADC range. It is this solution that is used in the proposed device.

In conclusion, we give the formula for calculating the rms voltage value: , where N is the number of measurements per period (sampling frequency), u i are instantaneous voltage measurements. K - coefficient taking into account the divider and transformer.
Measurements can be carried out both for a period and for several periods with subsequent averaging. If we are not talking about building structures such as an oscilloscope, then averaging is preferable, because usually it is the average values ​​that are of interest, not the instantaneous ones.

Current measurement.
No ADC by itself can measure current. The ADC only measures voltage. So, it is necessary to convert the current into voltage, measure this voltage, and convert it back into current.
The easiest way to convert current into voltage is a shunt, in fact, a powerful low-resistance resistor Rsh. The flowing load current In creates a voltage drop Ush across the resistor, which is directly proportional to the value of In. Knowing the resistance of the shunt, according to Ohm's law, we can calculate the load current: In = Ush / Rsh. On the basis of the shunt, the vast majority of ammeters, both pointer and digital, are arranged.

This method is very simple, understandable and cheap. In addition, such a node is completely linear (the equality In = Ush / Rsh is observed over the entire range of operating currents) and does not have any reactive components, because resistor is a 100% active element.
But, along with simplicity and low cost, shunt-based schemes have a number of disadvantages:

Disadvantages 2, 3 and 4 are very serious, they can lead to very disastrous consequences (damage to the device, electric shock, etc.). That is why all consumer ammeters have warning labels with the meaning "measure high currents (10A and above) for no more than 10-20 seconds."
The design is built on the basis of a shunt, which means that it has all four disadvantages.

Another way to measure current is to use a current transformer (CT). Such a transformer is a coil through which several (1-3) turns of wire are threaded through which the load is powered. In powerful industrial CTs, a thick metal tire (plate) is used instead of turns of wire. The principle of operation of a CT is essentially the same as that of a conventional transformer - the electromagnetic field of the current of the conductor of the primary winding (I1, load current, In) induces a current (I2) proportional to In in the secondary winding. i.e. I2=In*K, K is the current transfer coefficient (its values ​​are standardized - 1:500, 1:1000, etc.). Further, this current is converted into a voltage by the Rb shunt, which can already be measured with a conventional voltmeter (or ADC) and converted into voltage. Because the secondary current is always very small, then very powerful shunts are not required here and they do not burn out due to the fact that they operate at maximum power.

For CTs up to 25A, the shunt resistor is typically only 0.125W. And this is already an ordinary easily accessible consumer resistor, and not some rare and scarce special item.

The calculation of the load current when using a CT is as follows: In=I2/K. I2=U2/(Rb+R2), where U2 is the voltage across the shunt Rb, R2 is the resistance of the secondary winding. Hence In \u003d U2 / (K * (Rb + R2)). Essentially the same Ohm's law.
More details about CTs and the principles of their functioning can be found in specialized articles, for example, in.

The main advantages of TT over a shunt:

  1. Galvanic isolation.
  2. Ability to measure huge currents (for example, industrial 500A).
  3. Breakage of the winding does not lead to burnout of the rest of the measuring circuit.
  4. The CT does not introduce practically any distortion into the measured circuit due to the fact that the primary winding is a few turns of wire, and its inductance is extremely small. In powerful industrial CTs, there are not even these few turns, there is just one thick powerful wire threaded through the winding or bus.

But there are also a number of disadvantages:

  1. CTs are much more expensive than shunt resistors.
  2. In some cases, CTs give some phase shift of the output current relative to the input.
  3. A break in the shunt of the secondary winding leads to its burnout (in fact, damage to the CT itself) and to a distortion of the parameters of the measured circuit.
  4. Over a wide range of currents, CTs are non-linear, i.e. the above K is not a constant. This is a direct consequence of the magnetic hysteresis of the transformer core. This can be compensated by dividing the entire range of measured currents into parts (sub-ranges) and using its own K for each sub-range. In addition, there are CTs with cores made of various special alloys with a small hysteresis.

Other methods of measuring current and types of CTs are not considered here. There are many reviews and articles on this topic, for example,.

The proposed device uses a CT to provide galvanic isolation from the measured network.
The formula for calculating RMS current is almost the same as for voltage.

Measurement of active and reactive power .
From TOE () it is known that the active power of the load is calculated as the integral of the product of instantaneous voltage and current in one frequency period:. In digital measuring devices, integrals are not calculated, so this formula takes the form: , where u, i are the instantaneous values ​​of current and voltage measured using the ADC, N is the number of current and voltage measurements per period. Similar to voltage and current, active power can be measured over several periods and adjusted N accordingly.
Apparent (S), active (P) and reactive (Q) powers are related by equality. Therefore, knowing S and P, one can easily calculate .

Measurement of network power factor and phase angle.
These two parameters are strictly uniquely interconnected, because the power factor is nothing more than the cosine of the phase angle (φ) between voltage and current (see TOE). Therefore, any of them can be measured, and the second is calculated by the simplest trigonometry.

The first way (perhaps the most obvious and simple) is to detect the time between the beginning of the period of the voltage sine wave and the beginning of the current sine wave, convert it to φ and then determine the cosine. This is how the algorithm for determining the angle in .

However, it has one very serious drawback - this method clearly works only on ideal and “clean” sinusoids without interference, which are extremely rare in real life. In fact, the power grids are full of various pickups, interference, and other “artifacts”, which make it difficult to accurately determine the “real” beginning of the period.

Therefore, if, for example, in an apartment this method will give a completely normal result, then in some factory with a mass of machine tools, welding machines and other powerful power equipment, frank nonsense can turn out (for example, a constantly changing angle value). Even on "harmless" loads, strong distortions can sometimes be observed, for example, current sinusoids. The author, for example, has Sven BF-11R speakers, the shape of the current through which looks more like a kind of mutilated saw with multi-stage pyramidal half-waves than a sinusoid. Although, in fairness, it should be noted that the author did not conduct large-scale studies on this topic due to his lack of technical capabilities.

The second way follows from the relation . That is, knowing the voltage, current and active power, you can easily determine the power factor. Further, . According to the author, this method is the most reliable. It is he who is used in the proposed device.

It is clear that all three powers, angle and cosine should be calculated only when U<>0 and I<>0. Otherwise, they can simply be set to zero without any calculations.

Device diagram, details

The electrical circuit diagram of the wattmeter is shown in fig. 1.


Rice. 1. Electrical circuit diagram

The device circuit consists of 2 parts - analog (to the left of the DIP switches SW1) and digital (to the right).

analog part consists of voltage measuring transformers (T1), current (T2) and matching units.
Resistor R2 is a potentiometer for fine tuning the voltage supplied to the ADC.
Т2 – current transformer Talema AC1025, loaded on a shunt resistor R1 with a nominal value of 100 Ohm and a power of 0.125W. These resistor parameters are recommended by the transformer manufacturer. In addition, according to the research of the author, such a resistor provides the best linearity of the applied CT. The primary winding is 2 turns of a conventional single-core wire with a cross section of 1-1.5 mm, this is quite enough for household loads with a power of up to 2 kW and a current of up to 10A. The characteristics and configuration of the circuit are not affected by the thickness of this wire.

Node R3, C1, C3, DA1.1 is a midpoint shaper for “raising” sinusoids by half the range of the ADC. OS DA1 - in principle, any. The author used both LM358 and rail-to-rail MCP601. According to the pinout of the cases (at least DIP), they are identical.

Divider R4, R5, R6 - a chain for measuring large (from 4-5A) currents.
Diode pairs VD1-VD2, VD3-VD4, VD5-VD6 and R7 are the classic protection of ADC inputs from overvoltage (more precisely, from the output of the sinusoid beyond the limits of 0..+5V). VD1-VD4 - preferably Schottky. You can also use "specialized" diode assemblies like BAV199 (1 assembly contains 1 pair of diodes) or similar.
All potentiometers (R2, R3 and R5) are preferably multi-turn. They will allow you to make the most accurate adjustment of the nodes of the circuit.

The circuit does not have any filters on the ADC inputs, because the transformers used are designed to work with 50/60 Hz currents and do not transmit high-frequency signals well. But detailed studies were not carried out by the author for lack of the necessary equipment (generators of different frequencies, etc.).

To measure the current, 2 channels are provided - low-current (T2-R7-ADC2) and high-current (T2-R4-R5-R6-ADC3). This decision is due to the fact that large loads (4-5A and higher) lead to the appearance of a voltage at the output of the CT that exceeds 4.5-5V in amplitude. The peaks of the half-waves of such a voltage will be cut off by the diode pair VD3, VD4, which means that it is actually impossible to measure the current above the specified values. The controller firmware automatically chooses which of the two signals to use.

digital part circuits - AtMega16 microcontroller, standard HD44780 alphanumeric LCD display and other elements. Switching schemes are standard for these components. When connecting the display, you should be guided by the documentation for a specific model, because. there are different pinouts (pinouts). The author knows 2. The diagram shows the most common.
The only requirement for the display is that it must be Russified. All messages are issued in Russian.

Resistor R8 - ordinary (not multi-turn), serves to set the desired level of image contrast on the LCD.
R9 and SB5 - backlight. The value of R9 is not specified, because Different LCD models have different backlight current. It can be calculated using Ohm's law using the backlight current value for a particular display. If the display is not backlit, then R9 and SB5 are not needed at all.

R11, VD6 - "Power on" indicator.
No special settings for the digital part are required. With serviceable parts, proper installation and a programmed controller, the circuit starts working immediately after power is applied.

The MK itself can be modifications of AtMega 16/16A. The modification with the letter L cannot be used - it does not normally operate at a frequency of 16MHz. Overclocking questions like "how to make AVRs with the letter L work at a frequency of 16 MHz" are not considered here. You can use others - Mega32, 64, 128, but for them it will be necessary to recompile the firmware accordingly.

When programming (firmware), in addition to uploading the wattmetr.hex file to the controller, it is also necessary:
1. set the quartz resonator mode (CKSEL3..0=1111)
2. set CKOPT=0 (required, because quartz is 16MHz)
3. set JTAGEN=1. If this is not done, then the LCD will not work correctly, because the JTAG controller (4 high PC bits) is not turned off by software.
4. flash the EEPROM with initial configuration information (file wattmetr.eep).

The author used a separate PonyProg programmer with an LPT interface for programming. The author's design uses a controller in a DIP package, and a block for it, so there is no connector for connecting an ISP programmer on the diagram and on the printed circuit board, but the PB5-PB7 legs (the programmer is connected to them) are specially left free.

All buttons are non-latching. Their design is any, depending on the expected operating conditions. SB1-SB3 and VD5 are used only when setting up and calibrating the device, so they can be placed directly on the board, SB4 and SB2 are also used to switch the modes of displaying information on the display, so it is better to bring it out or duplicate it for ease of calibration (2 buttons connected in parallel - on the board and on the case). To connect duplicate buttons on the board, special taps for connectors are made.
The purpose of the buttons and the LED will be described below, in the "Calibration" and "Operation" sections.

It should be noted that there is no UART level converter on the diagram (legs 14, 15 of the controller). This is due to the fact that the type and the very presence or absence of such a converter is highly dependent on what the device will be connected to. If it's a COM port, then it's a MAX232 chip, if it's USB, then something like FT232BM, if it's to another controller, then maybe converters are not needed at all, etc.

The author's design involves connecting to another AVR MK, so there is no converter in it at all. Resistor R12 is needed to maintain a high level at the Rx input in the absence of transmission (according to the rules of operation of the UART), or when this interface is not used at all.

Node diagrams for MAX232, FT232, etc. are not shown here, they can be found in the documentation for these microcircuits. You can also use USB cables from old mobile phones with a native UART interface (such as PL2303). But before that, you should make sure that the output of the cord is a log. TTL levels, not RS232.
To test the operation of the interface, the author used a node on the MAX232, assembled on a different board. This node was connected to the device with a standard audio cable from a computer CD/DVD drive.

The circuit is powered from any 5V DC source. For example, from a classic power supply on a single-chip stabilizer LM7805 - fig. 2. You can also use any other PSU that provides 5v, a battery, a USB port on a computer, etc.


Rice. 2. Power supply

If it is supposed to power the circuit from the same network where the measured load is included (as, for example, in everyday life, in an apartment), then the T1 transformers of both circuits can be combined. Those. use one, with two independent secondary windings. So, in the author's copy, one transformer was used with two secondary circuits of 15v each.

The circuit is assembled in any convenient way.

The article is also accompanied by a printed circuit board drawing created in a well-known program. It involves the use of double-sided textolite and the implementation of a small number of transitional (metallized) holes. However, if it is impossible to make double-sided wiring and plated holes (for example, at home, using), then:
1. spread on a single-sided textolite only layer M2, containing the bulk of all tracks;
2. instead of metalized vias, ordinary ones can be made;
3. Replace all traces of layer M1 (together with the corresponding vias) with jumper wires. It is very convenient to use for this trimming the legs of radio components, for example, resistors and capacitors.

The following features should also be noted:

  • Measuring transformers T1 and T2 on the board are not separated, because they can be of different designs and dimensions. The author's copy, for example, uses the second winding of the power supply transformer as T1. The transformer windings are connected to the board by wires with connectors.
  • R1 (CT shunt) is not wired on the board, it should be soldered directly to the CT pins. This reduces the risk of the shunt breaking.
  • To connect the LCD, the board has a connector, the sequence of contacts of which corresponds to the most common display wiring shown in Fig. 1. When assembling the device, be sure to check the description of your copy of the LCD, because. in practice, there are many differences - a non-standard order of contacts, their location on the side of the display board, SMD contacts, etc.
  • The board has a quad DIP switch, because it is not always possible to find a triple for sale. If it is possible to use a triple one, then instead of the left switch on the board (circuit of the 40th leg of the controller), solder a wire jumper (or lay a track in layer M1 and make 2 additional metallized holes).

Attention! The author assembled and debugged the device on a breadboard. it is intended to be used as part of another device. Therefore, the proposed drawing p / n is only theoretical and has not been tested in practice.
BP according to fig. 2 was assembled on a prefabricated basis. Her drawing is also attached.

Schema setup

Attention! Before setting up the circuit, open all 3 DIP switches SW1 (or remove the MK from the circuit). If a quad switch is used, the 40th leg line of the controller does not need to be opened.
In general, manipulation of DIP switches is preferable because there is information that some instances (or models) of the LCD burn out if they are not initialized immediately after being turned on, although the author has not encountered such. If the controller is removed, then there will be no one to initialize it.

Setting up the circuit is reduced to adjusting the potentiometers R2, R3 and R5 in the following order:
1. With the load disconnected, use R3 at point A to set the voltage to + 2.5V relative to the ground of the circuit.
2. Apply voltage to T1 and set output R2 to 1v relative to point A. If you have an oscilloscope, check the sinusoid at the output R2 so that it lies within +1 .. + 4.5v (that is, it is not cut off by diodes VD1-VD2). If there is a laboratory autotransformer, or a stabilizer with the possibility of some increase in voltage, then you can apply an overvoltage to input T1 (for example, 260-270v) and adjust the sinusoid along it so that there is some margin over the input voltage range.
3. Connect a powerful load (4-5A - for example, an iron of 1 kW) and use R5 to set the voltage at the output of the divider by about 5 times less than at its input. If with an ordinary voltmeter, then relative to point A. If there is an oscilloscope, then make sure that the sinusoid from the output of the divider is not cut off by diodes.

Always measure with an oscilloscope with respect to ground.
If the sinusoid is cut off somewhere, then the readings of the device will be incorrect.
After setting, we restore the connection of the analog part of the circuit with the MK (turn on all DIP switches).
Instrument calibration is described below.

Firmware

The controller microcode is written in C language using CvAVR compiler.
It constantly polls the ADC channels, recalculates the voltage at its inputs into real measured values ​​and displays the obtained values ​​on the display.

Each measurement cycle lasts 0.5 seconds, after which the data is processed (the measured parameters are calculated) and displayed. Each measurement includes measuring the voltages at the ADC1-ADC3 inputs and calculating preliminary values, on the basis of which the desired voltage, current, etc. are calculated. This approach is described in more detail below.

Measurements are carried out on timer interrupts TC0 with a frequency of 5 kHz.
Those. 100 times per period (20 ms), in a timer interrupt, measurements are taken from all 3 ADC channels (ADC1-ADC3). After 0.5 seconds, the timer turns off and calculations are carried out. The mid-point voltage (ADC0) is measured each time before the timer is started. This reduces the effect of random mid-point voltage ripple on instrument readings.

Now consider the methods of measuring physical quantities, implemented in the microcode of the controller.
Theoretical approaches to measuring various electrical quantities were given above, but here it is necessary to consider the practical differences from the theory and the features of the implementation of these measurements.
It is very difficult to directly implement all the formulas given in the theoretical introduction in a microcontroller, if not to say that it is impossible at all.

The fact is that all of them always imply that all the quantities included in them (for example, instantaneous voltage and current) are real (floating point, speaking in programming language) numbers. But in microcontrollers in general, and in AVR in particular, there is no arithmetic coprocessor capable of adding or multiplying two such numbers even in 10 cycles. Such actions are carried out by software emulation, which is very slow. Not to mention long, iterative algorithms for extracting the square root and calculating the trigonometric function arccos (arccosine) used in calculating φ.

In other words, if you implement such actions in an interrupt handler that is called even once per millisecond, then such an handler will not be able to complete within 1 ms, which at best will lead to terrible “brakes”, and most likely to a complete freeze of the controller. Both that, and another actually means complete inoperability of the device.

You can use other ways to calculate them, such as tabular algorithms (for square root and arc cosine) and manipulation of "scaled" values ​​(for example, the current can be calculated not in fractional amperes, but in integer milliamps - 1.253A=1253mA), etc. But they have a lot of their drawbacks - the program code is "bloated" with unnecessary operations, making the already rather complicated algorithms confusing and incomprehensible. In addition, at the same time, the consumption of memory (both RAM and Flash) also increases, which is sometimes very lacking in MK. Also, the accuracy of such calculations often suffers.
At the same time, simple mathematical transformations of theoretical formulas make it possible to completely avoid all these problems while maintaining the possibility of using floating point and the sqrt and arccos functions from the standard C library.

Consider this method using the example of calculating voltage.
The theoretical part of the article contains formula (1), where u i is the instantaneous voltage value, which, in turn, is calculated as u=K*u adc (2), where u adc is the voltage at the ADC input, K is a constant that takes into account the total division factor of transformer T1 and divider R2. According to the documentation for the MK (3). Substituting (3) into (2) and then into (1), we get , where ADC i is the value read from the ADC data register upon completion of the measurement. And this is a purely integer value and even unsigned.
It follows that squaring (essentially multiplication) and summation (which must be carried out in the body of the TC0 timer interrupt handler) are integer operations that the MK (let's not forget that it contains a hardware integer multiplier) can easily handle for 1 -2 beats. And having on hand an integer sum of squares of instant ADC readings for a certain number of frequency periods and knowing their number (N in the above formulas), you can stop measurements and carry out all further calculations already using floating point and standard mathematical functions of the language Si.

Also, immediately after each channel is measured, the code from the ADC0 channel (midpoint) is subtracted from the read ADC code, thereby compensating for the rise of the sinusoids up by 2.5v.

Related statements are also valid for the current (there is only a different coefficient K, which takes into account the relationship between the load current and the voltage on the shunt R1) and for active power.

For cosine and other quantities, no transformations of formulas are required, because they are all calculated outside of the timer interrupt based on the voltage, current and active power already available.

A significant drawback of the proposed firmware is the almost complete absence of mechanisms for compensating for the non-linearity of the CT. There are two reasons for this.

The first and main one is the author's lack of some kind of test bench for creating various load currents in order to build an accurate graph of the dependence of the voltage at the output of the CT on the load current. Household appliances are poorly suited for this, because. they do not allow uniform investigation of the entire range of currents. The graphs given in the LH on the TT are also not suitable, because. they are too small and too coarse for this kind of task. This disadvantage affects the LH on many TT models.

The second is the possible lack of RAM in the used MK for the implementation of such an algorithm. It may be necessary to replace it with another MK with a large amount of memory, for example, with AtMega32. However, detailed studies in this direction have not been carried out due to the first reason.
This drawback is partly compensated by the presence of 2 current measurement channels and a controlled switching threshold between them, because Each channel has its own calibration factor. Those. you can achieve acceptable readings for the most commonly measured loads.

Another drawback is that the device sometimes shows negative active power P (which cannot be, unless, of course, you plug the generator J into the socket). This is due to the non-synchronization of measurements with the network - i.e. measurements should be started from the beginning of the period, but in the proposed scheme and microcode, such synchronization is observed.

Because the error concerns only the power sign, then this disadvantage can be partly “compensated” by using P modulo, which is set in the settings.

Instrument calibration/setup

Because measuring instrument, it must be calibrated before use.
Calibration is performed using the buttons SB1-SB4. Entering the settings / calibration mode and switching the calibration stages is carried out with the SB1 button. In some cases, several values ​​may be displayed on the screen, but the value changed at each stage is always the same, it is enclosed in angle brackets "<", ">". The rest are for reference and general information.

Editable values ​​can be changed with the buttons SB2, SB3 - decrease / increase, respectively. All values ​​(unless otherwise specified) should be specified to the nearest hundredth. The accuracy mode is set by the SB4 button and displayed by the VD5 LED. If VD5 is enabled, the change step is 0.01 (increased accuracy), otherwise it is 0.1.

Calibration / adjustment progress:

  1. Apply power to the circuit.
  2. Press SB1. The device will enter the settings mode, the display will show the inscription “Settings”, then, after about 1 second, “U supply (supports)”. Here you should specify the supply voltage of the circuit, or the voltage of the support (leg AREF of the controller).
  3. Press SB1. The word "Voltmeter" will appear. The number to the right of it is the effective alternating voltage at the ADC1 input (relative to point A), in the 2nd line is the coefficient for converting the ADC1 voltage into the resulting voltage and the editable, so-called. "desired" voltage - what we want to see on the display. Here you should set the desired voltage (according to the reference voltmeter). The conversion factor is calculated automatically.

Then both channels of the ammeter are calibrated in the same way, the threshold for switching current measurement channels and the mode of active power use are set - as is or by module .. Then you can save the settings in the EEPROM of the controller or restore the defaults (the so-called "factory" settings).
The current channels are referred to as Lo (ADC2) and Hi (ADC3). They must be calibrated with a reference ammeter connected in series with the load.

The high current channel (Hi) should be calibrated on a powerful (1 kW and above) load. This is due to the fact that low load currents give a low voltage at the CT output, which, being also a reduced divider R4-R6, can go into the region of ADC noise and errors. As a result, the testimony m.b. are wrong.
The switching threshold is set in amperes with an accuracy of tenths. Using this value, the controller selects which current channel to use for displaying on the display and further calculations of S, P, Q, etc. The threshold should be selected so that the controller measures a sinusoid undistorted by diodes VD3, VD4. According to the results of the author's research, a value of 4A is quite acceptable. This is usually slightly less than the iron's current consumption of 1 kW. To diagnose the operation of the threshold, you can use the leg 19 (PD5) of the controller. Log. 0 is formed on it if the device uses the Lo channel, 1 - Hi. If desired, you can connect a diagnostic LED to this leg.

"Factory" settings:
ADC support (supply voltage) - 5v.
Voltage conversion factor - 150.
Low current channel conversion factor – 1.30.
High current channel conversion factor – 6.50.
The current channel switching threshold is 4.00 A.
Display profile - 1.
Active power mode - "as is".

Instrument operation

The device is very easy to use.
Immediately after turning on the power, a welcome message appears, after 1 second the device enters the operating state and begins to display the measured parameters on the display. The readings are updated about once per second.
The device has two so-called. "display profiles" - sets of simultaneously displayed parameters:

  1. 1st display line - U, I, S; 2nd - P, cos(φ),φ.
  2. 1st - U, I, S; 2nd - P, Q, φ.

The set of profiles and their composition are fixed; no means of modification are provided.
To change the profile, press the SB4 button and hold it until the message “Profile changed” appears on the display. Release the button when this message appears.

"Factory" settings contain active 1st profile. You can remember the current profile so that the device immediately uses it when turned on, using the SB2 button. The SB2 button must be held until the inscription "Profile memorized" appears. When calibrating the device, the current profile does not change, but when resetting to factory settings, profile 1 becomes the current one.

Profile selection is not automatically saved. This is done in order to save the EEPROM resource.
The choice of profile does not affect the composition of the information output via UART.

You should also pay attention to the following feature - a CT with a primary winding in operation and is structurally similar to a radio receiver antenna. According to this principle, search devices hidden in the walls of wiring and related designs work. In this regard, in the absence of load, the device sometimes shows "garbage" - some kind of current and power induced by interference. These pickups do not appear on the measurement results when the load is connected.
There are no means to combat this phenomenon.

According to the author, the most cardinal way to overcome this is to install some kind of microswitch in the socket for loading and interrogate it in the microcode. If the switch is open, no load is connected and current measurements are not made or ignored (current is forced to zero).

Data exchange interfaceUART

The proposed device has the ability to output measurement results via a standard UART serial interface. That. you can use it as part of more complex devices or connect it to a computer for automated collection of information.
Data exchange parameters - 38400, 8N1.
The exchange protocol is very simple - with a single-byte command 0xAA, the controller issues a block of information with a size of 15 bytes of the following format - Table. 1.

Table 1.

The following feature of the protocol should be noted - all values ​​are transmitted in integer format (currents in milliamps, cosine, which is always less than 1, multiplied by 100). This is done for the following reasons:
- Integers take up less space - 1 or 2 bytes. Floating point numbers in the dialect of C used are always 4 bytes. In addition, all returned values ​​fit into the integer format without any significant loss of precision.
- because It is not known in advance which computing system of what architecture will be connected to the device, then the format of floating numbers may turn out to be completely different from that used in the device, which will introduce additional difficulties in decoding the data block.

Double-byte numbers are transmitted in the format of the so-called. little Indian - i.e. low byte first, then high byte.
There are also features:
- there is no possibility of calibration and reading of calibration information via UART;
- in the calibration mode, the UART interface is not available (the MK does not respond to it). Data requests sent while the calibration was in progress are lost;
- MK can send information about once per second (after the end of measurements and calculation of all measured values), this should be taken into account when developing a device polling system. Therefore, you should not “overwhelm” it with data requests, this may interfere with the operation of the measuring module.

To illustrate the work with the device, the author has developed a demo Windows application WinAppWattmeter.exe for PC. It is written in C# and runs on WinXP and above. It is also necessary to have the .NET 2.0 platform and one COM port (physical or virtual USB) where the device should be connected. The sources for this application are compiled in VS.NET 2005 and above. Versions of VS Express and .NET Compact have not been tested.

Technical characteristics, advantages and disadvantages of the device

Advantages:

  1. Full galvanic isolation from the measured network.
  2. Possibility of power supply from any source - PSU, batteries, USB port of the computer, etc.
  3. Wide range of settings.
  4. Available element base.
  5. Large range of measured values.
  6. Ability to transfer measurement results to other computing systems (for example, to a PC).

Flaws:

  1. The non-linearity of the CT leads to current measurement errors over the entire range. This significantly complicates the assessment of measurement accuracy (some ranges of currents are measured accurately, the rest with errors, and different ones). These ranges are highly dependent on the coefficients adjusted in the calibration mode of the instrument, and therefore are not fixed. For example, you can calibrate so that at small loads such as mobile phone chargers, soldering irons or apartment light bulbs, the readings will be correct, while more powerful ones (irons, hair dryers, electric stoves, ovens, microwaves, washing machines) will be measured with errors.
  2. The TT itself can be a hard-to-find and expensive part.
  3. When there is no load, the device sometimes shows some current induced in the primary windings of the CT and, as a result, some power and other parameters.

Detailed technical characteristics of the device are not given, because there are quite a lot of opportunities for its configuration and adjustment.

The used CT model potentially allows measuring currents up to 25A, but in order to fully use this range, it is necessary to refine the input (analogue) stage of the circuit and microcode.
The range of measured voltages also depends on the transformer used. If it’s normal, “from the power supply”, then this is a “standard” range of about 180-250v, and if you take some specially made transformer, then 380 volts can also be measured.

Ranges of values ​​determined by the used data types and algorithmic features of the microcode – U=1..999v, I=1mA..65A, S/P/Q – each 1..999 corresponding units.
The current consumption of the circuit is 28-30 mA without taking into account the display backlight current. This current is different for different LCD models. Its typical value is 100-120 mA.
Also, the current may differ slightly from the values ​​shown when using different LCD models and op amps.

Photos

In conclusion, a few photos of the device.

Power unit. The transformer is physically one, with two independent windings. One serves the PSU itself, the 2nd (2 yellow wires on the right) - measuring T1.

The breadboard of the device. Note (again): this is a mock instance. According to the Sprint drawing, the p / p was not made, because it is planned to operate the device as part of another product, which is still under development. Therefore, please do not pay attention to two pads, a second display and an LED on the left. They are not related to the described device.

Soldering iron for 25W. Display profile 2.

Without load. Display profile 2. We catch pickups and glitches on the CT winding. The result is a "left" current of 68 mA with all the consequences.

The same as above, but without interference. Display profile 2.

Iron 1 kW. Display profile 1. Negative active power J - "correction" mode is disabled. The second LED from the left is lit - a sign of using a high current channel (leg 19 (PD5) of the controller). The threshold is set - 4A

List of attached materials

Wattmetr-Mega16-16MHz.zip - controller firmware with sources. Also in the archive there is a ready-made microcode file wattmetr.hex and a factory settings file (EEPROM) - wattmetr.eep.
WinAppWattmeter.zip is a demo application with sources (.NET 2.0, C# under VS.NET 2005+). There is also a ready-made exe file (without viruses).
Plata\*.* - PCB drawings in .lay format (Sprint 5).

  1. L.A. Bessonov, Theoretical foundations of electrical engineering, ed. 9, in 2 volumes. Moscow, Higher School, 1996.
  2. Electronic phase meter - http://kazus.ru/shemes/showpage/0/104/1.html He is the same - Radio No. 5, 1990, p. 56
  3. Atmel AVR465: Single-Phase Power/Energy Meter with Tamper Detection.
  4. Digital wattmeter on MK - http://radiokot.ru/circuit/digital/measure/23/
  5. Current transformer - http://bsvi.ru/transformator-toka/
  6. Modern industrial current sensors. "Modern Electronics", October, 2004
  7. RMS voltage measurement - http://arv.radioliga.com/content/view/107/43/

List of radio elements

Designation Type Denomination Quantity NoteShopMy notepad
Device diagram
DD1 MK AVR 8-bit

ATmega16

1 To notepad
DA1 Operational amplifier

LM358

1 To notepad
VD1-VD4 Schottky diode

A simple AC voltmeter with a frequency of 50 Hz is designed as a built-in module that can be used both separately and be built into a finished device.
The voltmeter is assembled on a PIC16F676 microcontroller and a 3-digit indicator and does not contain very many details.

The main characteristics of the voltmeter:
The form of the measured voltage is sinusoidal
The maximum value of the measured voltage is 250 V;
The frequency of the measured voltage - 40 ... 60 Hz;
Discrete display of the measurement result - 1 V;
Voltmeter supply voltage - 7 ... 15 V.
Average current consumption - 20 mA
Two design options: with and without PSU on board
Single sided PCB
Compact design
Display of measured values ​​on a 3-digit LED display

Schematic diagram of a voltmeter for measuring AC voltage


Implemented direct measurement of alternating voltage with subsequent calculation of its value and output to the indicator. The measured voltage is fed to the input divider, made on R3, R4, R5, and through the separating capacitor C4 is fed to the input of the ADC of the microcontroller.

Resistors R6 and R7 create a voltage of 2.5 volts (half power) at the input of the ADC. The relatively small capacitor C5 shunts the ADC input and helps to reduce the measurement error. The microcontroller organizes the operation of the indicator in dynamic mode by interrupts from the timer.

--
Thank you for your attention!
Igor Kotov, editor-in-chief of Datagor magazine


🕗 01/07/14 ⚖️ 19.18 Kb ⇣ 239 Hello reader! My name is Igor, I'm 45, I'm a Siberian and an avid amateur electronics engineer. I came up with, created and maintain this wonderful site since 2006.
For more than 10 years, our magazine exists only at my expense.

Good! The freebie is over. If you want files and useful articles - help me!

AC Voltmeter

N. OSTROUKHOV, Surgut

The article describes an AC voltmeter. It is collected on
microcontroller and can be used as a stand-alone measuring device
or as a built-in voltmeter in the LF generator.

The proposed voltmeter is designed
for measuring alternating voltage of a sinusoidal form with a frequency from 1 Hz to
800 kHz. Measured voltage interval - 0…3 V (or 0…30 V with external
voltage divider 1:10). The measurement result is displayed on
four-digit LED indicator. The measurement accuracy is determined
parameters of the ADC built into the microcontroller and the source of the exemplary
voltage and is equal to 2 mV (for an interval of 0 ... 3 V). The voltmeter is powered by
stabilized voltage source 5 V and consumes a current of 40 ... 65 mA in
depending on the indicator used and the brightness of its glow. Current consumed
from the built-in polarity converter, does not exceed 5 mA.

Into the device (see diagram on
rice. 1) includes an AC-to-DC converter, a buffer
DC voltage amplifier, digital voltmeter and converter
polarity of the supply voltage. AC voltage converter
constant collected on the comparator DA1, pulse generator on the elements
DD1.1-DD1.4 and switching transistor VT1. Consider his work
more. Assume that there is no signal at the input of the device. Then the voltage
at the inverting input of the comparator DA1 is zero, and on the non-inverting input is determined
voltage divider R19R22 and at the ratings indicated in the diagram is about -80
mV. At the output of the comparator in this case there is a low level, which
Enables the pulse generator. The peculiarity of the generator is that when
each voltage drop at the output of comparator DA1 at the output of the generator (pin 8
element DD1.2) one pulse is formed. If by the time of its decline the day off
the state of the comparator will not change, the next pulse will be generated, and so on.

The pulse duration depends on
denominations of the elements R16, C5 and is approximately 0.5 μs. At a low level
voltage at the output of the element DD1.2 opens the transistor VT1. Denominations
resistors R17, R18 and R20 are selected so that through an open transistor
a current of 10 mA flowed, which charges the capacitors C8 and C11. During the duration
each pulse, these capacitors are charged by fractions of a millivolt. in steady state
mode, the voltage on them will increase from -80 mV to zero, the repetition rate
the generator pulses will decrease and the pulses of the collector current of the transistor VT1
will only compensate for the slow discharge of the capacitor C11 through the resistor
R22. Thus, due to the small initial negative bias,
even in the absence of an input signal, the inverter operates normally
mode. When an input AC voltage is applied due to a change in the repetition rate
pulse generator voltage across capacitor C11 changes in accordance with
amplitude of the input signal. LPF R21C12 smoothes the output voltage
converter. It should be noted that only
positive half-wave of the input voltage, so if it is unbalanced
relative to zero, there will be an additional error.

Buffer amplifier with gain
transmission 1.2 is assembled on the op-amp DA3. The VD1 diode connected to its output protects
microcontroller inputs from negative polarity voltage. From the output of the op-amp DA3
through resistive voltage dividers R1R2R3 and R4R5 constant voltage
enters the lines PC0 and PC1 of the microcontroller DD2, which are configured as
ADC inputs. Capacitors C1 and C2 additionally suppress interference and interference. Actually
digital voltmeter is assembled on a DD2 microcontroller, which uses
built-in 10-bit ADC and an internal reference voltage source of 1.1 V.

Program for the microcontroller
written using the BASCOM-AVR environment and allows the use of three or
four-digit digital LED indicators with a common anode or common
cathode and allows you to display the effective (for a sinusoidal signal) or
the amplitude value of the input signal voltage, as well as change the brightness
indicator glow The logical level of the signal on the PC3 line sets the type of applied
indicator - with a common anode (low) or with a common cathode (high), and on the line
PC4 is the number of its bits, four for low and three for high. Program
at the beginning of work, it reads the signal levels on these lines once and adjusts
microcontroller to work with the corresponding indicator. For four-digit
indicator, the measurement result is displayed as X.XXX (V), for a three-digit
- XXX (mV) up to 1 V and X.XX (V) if the voltage is more than 1 V. When used
three-digit indicator, the conclusions of its digits are connected as the conclusions of three
senior digits of the four-digit in fig. 1.

The signal level on the PC2 line controls
by multiplying the measurement result by 10, which is necessary when using an external
voltage divider 1:10. At a low level, the result is not multiplied Signal by
line PB6 controls the brightness of the indicator, at a high level it
decreases. The change in brightness occurs as a result of a change in the ratio between
glow time and extinguishing time of the indicator within each measurement cycle.
With the constants set in the program, the brightness changes by about half.
The effective value of the input voltage is displayed when applied to the PB7 line
high level and amplitude - low. Signal levels on the lines PC2, PB6 and
PB7 program analyzes in each measurement cycle, and therefore they can be
changed at any time, for which it is convenient to use switches. Duration
one measurement cycle is equal to 1.1 s. During this time, the ADC performs about 1100
samples, the maximum is selected from them and multiplied, if necessary, by
the desired ratio.

For a constant measured
voltage would be enough for one measurement for the entire cycle, and for alternating
with a frequency of less than 500 Hz, the voltage across the capacitors C8. C11 noticeably changes
during the cycle. Therefore, 1100 measurements with an interval of 1 ms allow
fix the maximum value for the period. Polarity converter
supply voltage is assembled on the DA2 chip according to the standard scheme. his day off
voltage -5 V supplies comparator DA1 and op-amp DA3. The XP2 connector is designed for
in-hardware programming of the microcontroller.

The voltmeter uses constants
resistors C2-23, MLT, trimmers - Bourns 3296 series, oxide
capacitors - imported, the rest - K10-17. Chip 74AC00 can be
replace with KR555LAZ, transistor KT361G - with any of the KT3107 series. Diode 1N5818
replace with any germanium or Schottky diode with a permissible forward current of at least
50 mA. The replacement for the ICL7660 chip is unknown to the author, but the converter
voltage polarity +5 / -5 V can be collected according to one of the published in
magazine "Radio" schemes. In addition, the converter can be excluded
completely, using a bipolar stabilized power supply. especially
should focus on the choice of comparator, since the range depends on it
operating frequencies. The choice of comparator LM319 (analogues KA319, LT319) is due to two
criteria - the necessary speed and availability. Comparators LM306,
LM361, LM710 are faster, but it turned out to be more difficult to obtain them, to
besides, they are more expensive. More accessible are LM311 (domestic analogue of KR554SAZ) and
LM393. When the LM311 comparator is installed in the device, as expected,
the frequency range narrowed to 250 kHz. Resistor R6 has a relatively
little resistance because the device was applied as a built-in
voltmeter in the oscillator. When using the device in a stand-alone meter, its
resistance can be increased, but the measurement error will increase due to the relatively
large input current comparator DA1.

Voltage divider circuit 1:10
shown in fig. 2. Here, the functions of the resistor R2 in the divider are performed by the resistor
R6 (see fig. 1). Adjust the voltage divider in a certain sequence.
Rectangular pulses with a frequency of several kilohertz are fed to its input,
amplitude 2 ... 3 V (such a calibration signal is available in many
oscilloscopes), and to the output (to pin 5 DA1) connect the input of the oscilloscope. fine tuning
capacitor C1 achieve a rectangular pulse shape. Oscilloscope should
apply with input voltage divider 1:10. All parts except indicator mounted
on a breadboard circuit board measuring 100 × 70 mm using a wired
installation. The appearance of one of the variants of the device is shown in Fig. 3. For
convenience of connecting a digital indicator, a connector is used (not shown in the diagram)
shown). During installation, the common wire of the XP1 input plug and the corresponding capacitor terminals
C8, C10, C11 and C13 should be connected to a common wire in one place with wires
minimum length. Elements VT1, R20, C8, C10, C11 and C13 and comparator DA1
should be placed as compactly as possible, capacitors C3, C6 - as possible
closer to the pins of the comparator DA1, and C4, C14, C15 - to the pins of the microcontroller
DD2. To establish the input of the device is closed, the common output of the oscilloscope probe
connected to the positive terminal of the capacitor C13, and the signal - to the emitter
transistor VT1. A pulse of negative polarity should appear on the screen
with an amplitude of about 0.6 V and a duration of 0.5 μs. If due to the low frequency
pulses will be difficult to observe, then temporarily in parallel
capacitor C11 is connected to a resistor with a resistance of 0.1 ... 1 kOhm. Voltage
on capacitor C12 is controlled by a high-ohmic voltmeter, it should be
close to zero (plus or minus a few millivolts).

The output voltage of the op-amp DA3
(which should not exceed a few millivolts) resistor R27
set to zero. Required operating mode of the microcontroller
set by supplying the required levels to the lines PB6, PB7, PC2-PC4, for which they
connected to a common wire or to a +5 V power line through resistors
resistance 20 ... 30 kOhm. An exemplary one is connected to the input of the device.
voltmeter and apply a constant voltage of 0.95 ... 1 V. Trimmer resistor
R4 equalize the readings of both voltmeters. Then the voltage is increased to
2.95 ... 3 V and resistor R1 again equalize the readings. A selection of resistors
R8-R15 you can set the desired brightness of the indicator. Pick up first
the required denomination of only one of them, and then set the rest. At
selection, remember that the maximum output current of the port of the applied
microcontroller should not exceed 40 mA, and the total current consumption - 200
ma.

Editorial. The program for the microcontroller is on our
FTP-cep-vere at ftp://ftp.radio.ru/pub/2011/02/Vmetr.zip

Ibrahim Kamal (IKALOGIC)

Note. Samples of source code placed in the description text are not recommended for use in your projects. At the end of the description there is a link to the archive with the full source code for the project.

This article is for educational purposes. We will consider the hardware solution and software implementation in the task of measuring the voltage level of a battery (accumulator) using a microcontroller that is powered by the same source. Users are expected to be familiar with AVR microcontroller programming and have a basic knowledge of the C language. The compiler used is WinAVR.

Obviously, while very simple, the task of measuring the supply voltage of a microcontroller can be very important and serious, especially in battery-powered devices and applications.

There are many ways and solutions to monitor battery voltage levels, many of which require the use of external components and assemblies. The solution we are considering does not require external components, we will use only the resources and peripherals of the microcontroller - the built-in ADC.

We will use the ATMEGA48 microcontroller, but the program code is fully compatible with the ATMEGA88, ATMEGA168, ATMEGA328 microcontrollers. In addition, by slightly correcting the source code, this solution can be applied to AVR microcontrollers with built-in ADC.

Users are probably wondering: “Is the process of measuring the microcontroller supply voltage really that complicated?” To solve this problem, we have a microcontroller, and we need to convert the analog voltage value into a digital value that can be used by the microcontroller for further calculations and actions.

You will probably say: "So what's the deal. We will connect the positive terminal of the battery that powers the microcontroller to the input of the ADC and convert the voltage value into a digital value!

However, in this case you will be wrong, it is not so simple. The problem is that the voltage source is used to power the microcontroller itself (Vcc) and also as the ADC voltage reference.

If you consider this problem from a mathematical point of view, if you understand the problem. In general, the relationship between the measured voltage and the digital value converted by the 8-bit ADC is:

,

Where ADC_VALUE- value obtained by analog-to-digital conversion,
V_measure- measured voltage value, V_REF- reference voltage for the ADC.

Now, by the conditions of our problem, we know that V_measure = V_REF = Vcc and in the end the result of the equation will always be a value of 255 and it will not change when the battery voltage changes. This situation will always occur when measuring battery voltage, which is also used as a voltage reference.

To solve the problem without using any external components, the AVR microcontroller has a very useful built-in node called the internal Band Gap reference voltage source (Band Gap Reference Voltage). The output voltage of this source is about 1.1 V, and it remains unchanged with changes in temperature and the supply voltage of the microcontroller. This voltage can be applied to the input of the ADC, like any external voltage, with the only exception that this is done in software, without including additional external components.

Although this node was not designed for our specific purpose, we will use it in our task of measuring the supply voltage of the microcontroller.

Consider our equation

ADC_VALUE = V_measure * 255/V_REF ,

But, deciding to measure the reference voltage V_BG, we get the following expression

ADC_VALUE = V_BG * 255/V_REF

And since in our case the reference voltage of the ADC is equal to Vcc(the main point of our problem), then the equation will take the form

ADC_VALUE = V_BG * 255/Vcc

Knowing that V_BG=1.1V, from the equation we can calculate the microcontroller supply voltage

Vcc = 1.1 * 255/ADC_VALUE

Thanks to the last expression, you will be able to calculate the actual voltage value of your device's power supply on the microcontroller without using any external components.

Let's consider an implementation example.

circuit diagram

We use three NiCad batteries to power the microcontroller. The supply voltage, with fully charged batteries, will be 4.2 V. We need to turn on the LED connected to the PB0 port if the voltage is below 3.2 V.

Listing

#include avrio.h #include avrinterrupt.h
// global variables
float vcc;//variable to hold the value of Vcc
void setup_adc(void)
{
ADUX=0xE; //Set the Band Gap voltage as the ADC input
ADCSRA = (1ADEN)|(1ADATE)|(1ADIE)|(1ADSC)|5;
}
ISR(ADC_vect) //ADC End of Conversion interrupt
{
unsigned char adc_data;
adc_data = ADC>>2; //read 8 bit value
vcc=1.1*255/adc_data;
}
// main program
// ***********************************************************
int main(void)
{
DDRB = DDRB | (1PB0); //set PB0 as output (for the LED).
sei(); //Activate interrupts setup_adc();
//setup the ADC

while(1)
{
// infinite loop
if (vcc< 3.2)
{
PORTB |= (1PB0);
}
else
{
PORTB &= ~(1PB0);
}
}
}

It should be noted that the voltage V_BG will be different for different microcontrollers, especially from different batches, and can be in the range of 1.01 V - 1.2 V, therefore calibration will be necessary. Thus, if the calculated value of Vcc using this code is incorrect, you must do the following: measure the supply voltage Vcc with a voltmeter and, using the equation below and knowing the value ADC_VALUE, calculate value V_BG

As you know, many modern microcontrollers have a built-in multichannel ADC, as a rule, physically ADC only one, and multi-channel is provided using multiplexing. The range of voltages with which the ADC can operate is determined by the levels of reference voltages ( +VREF And -VREF), they should not go beyond the power supply range of the microcontroller. The range of voltages supplying the microcontroller can be from 0 to 3.3, or from 0 to 5 volts. From this it becomes clear that to measure negative voltages ADC cannot, but it is necessary.

There are several ways to measure negative voltages using an ADC, in all examples we will assume that -VREF=0, A +VREF = 5 volt.

Only negative voltages need to be measured, e.g. -5 to 0.
In this case, you can use an inverting amplifier built on an operational amplifier (op-amp) with a gain of -1.

When -1 volt comes to the input of the circuit, +1 volt will go to the input of the ADC. If the signal that we want to measure needs to be amplified, it is enough to change the values ​​of the resistors R1 and R2.

Only negative voltages need to be measured, e.g. -15 to 0.
In this case, you can use the adder built on the op-amp


The values ​​of resistors R1 and R2 are calculated as follows, when Vin = -15 volts, the total voltage drop across resistors R1 and R2 is 20 volts. In this case, there should be 0 volts at the direct input of the op-amp, from here it becomes clear that 5 volts will fall on R1, and 15 volts will fall on R2, it follows that the resistor values ​​​​should be related as R2 / R1 = 3/1. On the other hand, since the resistors are connected in series and the same current flows through them, the formula can be written.


We go further, since there is negative feedback in the circuit, the voltage on the direct and inverse output should be equal. When Uin \u003d 0, the output of the op-amp will be 5 volts (in this case, zero at the input is the maximum value, which means that the output should have a maximum value equal to 5 volts). At the same time, there will be 3.75 volts at the direct input of the op-amp, and the same 3.75 will be at the inverse input. Since the output of the op-amp is 5 volts, and the inverse input is 3.75, it is easy to calculate the ratio of R3 to R4 (a conventional voltage divider).


Assuming that R1 and R4 are 10K, we get


R1 = 10K

R2 = 30K

R3 = 30K

R4 = 10K

It is necessary to measure the voltage, which can vary from -10 to 10 volts.

It is very simple to do this, for this you need to create a bias so that when -10 volts is applied to the input of the circuit, the ADC input is 0 volts, then when 10 volts is applied, the ADC input will be 5 volts.

This can be implemented in several ways:

  • on resistors


The values ​​​​of the resistors are calculated very simply, when we apply -10 volts to the left input of R2, its right output should be 0 volts, in which case the current does not flow through R3, since there is no potential difference at its ends.

The current flowing through R2 is


The current flowing through R1 is


Since resistors R1 and R2 are connected in series, the currents flowing through them are equal.


Suppose R2 equals 10K, then R1 equals 5K.

The current through R2 is equal to the current through R3, we get


we get

R1 = 5K

R2 = 10K

R3 = 10K

Minus circuits on resistors, this is what R2 limits the current going to the input of the ADC and that any noise in the power circuit will get to the input of the ADC. I would like to draw attention to the fact that the ADC has such a parameter as the input impedance, which, as a rule, depends on the sampling frequency, below is a table that shows how the input resistance depends on the ADC conversion period for STM32


the resistance of the signal source must be less than this value, and the series-connected resistor R2 clearly does not reduce it. In simple terms, in a short period of time, the ADC must receive enough charge to work with it, and a resistor connected in series with the input does not allow this.

This drawback can be corrected by assembling a circuit that has a low output impedance, that is, it can deliver a large current.

  • adder on the operational amplifier


And again, the adder on the operational amplifier will help us, as the resistor values ​​\u200b\u200bare calculated, described above, but the essence is the same, you need to take two extreme values ​​​​of the incoming voltage, at the minimum value at the output of the op-amp it should be zero, at the maximum it should be 5 volts (do not forget that -VREF=0, A +VREF = 5 volt). If it is necessary to measure positive and negative voltages, it is convenient to use half the reference voltage, that is, 2.5 volts, as an offset.
Here's what happened in the microcap, the picture can be enlarged by clicking on it.


The op amp circuit has a low output impedance, which means it can deliver high current and can be scaled to measure other voltages, such as ±2.5 volts.
we will look at a few more ways to measure negative voltage using an ADC.