Multifunctional wattmeter with galvanic isolation. Mains voltage measurement Voltage measurement with a microcontroller

A simple alternating voltage voltmeter with a frequency of 50 Hz is made in the form of a built-in module that can be used either separately or built into a finished device.
The voltmeter is assembled on a PIC16F676 microcontroller and a 3-digit indicator and does not contain very many parts.

Main characteristics of the voltmeter:
The shape of the measured voltage is sinusoidal
The maximum value of the measured voltage is 250 V;
Frequency of measured voltage - 40…60 Hz;
The resolution of displaying the measurement result is 1 V;
Voltmeter supply voltage is 7…15 V.
Average current consumption - 20 mA
Two design options: with and without power supply on board
Single Sided PCB
Compact design
Display of measured values ​​on a 3-digit LED indicator

Schematic diagram of a voltmeter for measuring alternating voltage


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

Resistors R6 and R7 create a voltage of 2.5 volts (half the power) at the ADC input. Capacitor C5, of relatively small capacity, bypasses the ADC input and helps reduce measurement errors. The microcontroller organizes the operation of the indicator in dynamic mode based on interruptions 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 have been maintaining this wonderful site since 2006.
For more than 10 years, our magazine has existed only at my expense.

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

Preface

In the old, pre-digital times, any of us had to be content with pointer measuring instruments, starting from ordinary watches, scales and ending with... hmm, so right away we can’t even find the limit of their use! Well, let's say - a precision laboratory micro- or even more impressive - picoammeter. And there were quite a lot of accuracy classes, depending on the purpose.

For example, an ordinary indicator of the amount of fuel in a car tank is the clearest example of the maximum inaccuracy of readings! I don’t know a single motorist who would rely on this “display meter” and would not refuel in advance. The inveterate pessimists of the drivers never drove out without a canister of fuel in the trunk!

But in the laboratories, especially in the State Verification Committee, there were switchmen with a mirror scale and an accuracy class much better than 0.5.

And almost all of us were satisfied and happy. And if they were not satisfied, then they purchased more accurate instruments, of course, if possible!

But now the digital age has arrived. We were all happy about it - now we can immediately see the numbers on the indicators and are happy with the “accuracy” offered to us. Moreover, in modern times, these ubiquitous “digitals” cost an order of magnitude less than the “inaccurate switchmen” that have become a rarity. However, few people think that the quantities shown to us in numbers still remain analog, whether it is weight or current strength - it does not matter. This means that these quantities are still measured analogue! And only for processing and presentation they are converted into a digital value. This is where errors are hidden, leading us to surprise when two different room thermometers in the same place show different values!

Path from measured value to indicator

Let's take a look at the entire measurement-indication process. Moreover, I deliberately choose an electrical quantity. Firstly, we are still on the site of electronics engineers, not thermal physicists or bakers, may they forgive my license of comparison! Secondly, I want to strengthen my reasoning with examples from personal experience.

First, I choose the current strength!

I will have to repeat the platitude that to obtain a digital representation of an analog quantity, you need an analog-to-digital converter (ADC). But since by itself it is still of little use to us, we will need other nodes to complete everything planned. Namely:

  1. in front of the ADC itself, you need a normalizing device, say: a normalizing amplifier or attenuator, depending on the ratio of the input value to the ADC conversion range;
  2. decoder after the ADC, to represent the converted numerical equivalent into the digital code of the corresponding indicator.

There are ready-made microcircuits that combine both an ADC and a decoder. For example, ICL7136 or similar, used in multimeters.

Essentially, all these nodes in one form or another are simply necessary. I have not yet named the sensor itself - in this case, a current-to-voltage converter, or simply a shunt.

So, let's briefly go through the entire chain. Current flowing through a shunt (a powerful resistor with very low resistance) creates a potential difference at its poles. Guten Tag, Herr Ohm! But this difference is quite small and not every ADC is able to fully convert this value, so the signal (voltage) from the shunt must be amplified to an acceptable value. This is why a normalizing amplifier is needed. Now the ADC, having received a digestible voltage at the input, will perform the conversion with the minimum possible error. At its output we get a number corresponding to the current value of the measured current in the selected range, which must be decoded accordingly to display on the indicator. For example, convert it to a seven-segment indicator code.

Here I do not see the need to dwell in more detail on each of the above stages, since in the article I pursue a different goal. And details can be found in abundance on the Internet.

Specifics

I have the so-called electronic load with current flow indicator. There is a basic diagram of the load itself, but there you will need an external ammeter to more accurately set the current. I decided to connect both devices to save space and not have a whole flock of multimeters.

My built-in ammeter is assembled and programmed on the Tiny26L MK. Part of this ammeter is the second (free) op-amp of the LM358 chip, which is part of the basic ballast circuit. Those. This is my standardizing amplifier because the maximum voltage drop across the shunt (5A x 0.1 ohm) is only 0.5 volts, which is clearly not enough for the full conversion range with the internal reference voltage.

According to T.O. (English = Datasheet) the nominal voltage of the built-in reference source (ION) is 2.56 volts. Very convenient size! However, in practice it doesn’t turn out so great: the adjusted ION voltage of my MK turned out to be 2.86 volts! How I determined this is a separate topic. Let's still go back to a convenient 2.56 volts. Look what happens: a maximum of 0.5 volts drops on the shunt, the ADC converts a maximum of 2.56 volts. A normalizing amplifier with a gain of 5 suggests itself, then the number obtained during the conversion will not require any advanced arithmetic to represent the result: 5 amperes = 2.5 volts = 250 units (for 8-bit conversion). You just have to multiply the result by two and put a decimal point between hundreds and tens to get a very convenient representation: units, tenths and hundredths of an ampere. The final transformation into seven-segment signs is a matter of technology. Everything is fine, you can implement it in hardware!

However, as I have already shown with the example of the built-in ION, it is not so easy to obtain acceptable (not to mention high!) accuracy with the components used. You can take the path of compensating for errors mathematically, using a program in the MK, although this will require calibration. This path is quite easily implemented in C and other high-level languages. But for me, a stubborn assembler, messing around with mathematics using RISC instructions is an extra headache!

I chose a different path - correction of the gain of the normalizing amplifier (NA). You don’t need much for this – one trimming resistor! Its value must be chosen correctly so that the adjustment range is sufficient, but not exaggerated.

Selection of normalizing amplifier elements

So, it is necessary to determine the adjustment range. The first step is to determine the tolerances of the components. For example, my shunt has an error tolerance of 1%. Other resistors in the normalizing amplifier circuit may have a tolerance of up to 10%. And don’t forget the inaccuracy of our ION, which in my case amounted to almost +12%! This means that the actual converted number will be almost 12% less. But since I already know this error, I take it into account in the NU gain, which should be 5.72. And since the real errors of other components are not known, it remains to find the maximum possible total error in order to calculate the adjustment range.

A simple sum of these “percentages” suggests itself: 1% of the shunt plus 2 times 10% of the op-amp feedback resistors. Total: 21%.

Let's see if this is really so. To do this, let’s take a look at the part of the diagram where this NU with already selected values ​​is presented:

As you can see, there is a non-inverting amplifier with a tunable transmission coefficient, theoretically adjustable from 4.979 to 6.735 at the ratings indicated in the diagram. But, if we take into account our ±10% possible error of each of the resistors, we get, with the worst combination, Ku = 5.864 - 8.009, which clearly exceeds the required coefficient! If this combination occurs, then you will have to take other denominations. It’s better to immediately increase the value of the tuning resistor, for example, to 39k. Then the lower limit of Ku will be 5.454, which is already acceptable.

Well, I – a “real radio junkie” – had to choose a trimmer from what was available, and was simply lucky to invest in the range! If I had a trimmer of a different value, it wouldn’t matter, I would recalculate R2 and R3, which in my case have a tolerance of 5%, so I didn’t have to take another trimmer.

Overcoming your shortcomings and omissions

It would seem that everything has been thought out and calculated - add a fee. Let's test this design on a breadboard first! No sooner said than done! Ku is being rebuilt not quite as expected, but within the limits of what is necessary. However, the indicator was not going to show 0.00 when there was no load current! First of all, I suspected the program was in the MK, but when the ADC input was short-circuited to the common wire, the treasured zeros appeared. This means that something does come to the input of the MK, other than zero volts. Testing with a multimeter confirmed this assumption and set the next task. Without going into details of my research, I will only describe the result.

The reason turned out to be the following: I completely did not take into account that the op-amp I used was far from being of the best quality. He's not even so-called. "rail-to-rail". This means that its output potential will never reach any of the supply poles, i.e. in my case it will never be equal to 0 volts! Now, if it were powered from a bipolar source, then the output would be the expected zero. But my power supply is unipolar and I did not intend to complicate the circuit with any converter. The solution was found in the creation of a “virtual land”, i.e. Thanks to a separate power source (as opposed to the basic circuit), I was able to use a diode to shift the potential of the common wire relative to the negative pole of the battery.

So, the board is etched and soldered. It's time to pack this design into a case. Which, in fact, was done. However, during operation, another small flaw emerged - drift of the input circuits of the op-amp. This was expressed in a negative shift in readings, i.e. at a current of a couple of tens of milliamps, the indicator still showed zeros, which did not suit me! I would allow a shift of several mA - still milliamp units are not displayed. I had to introduce a bias circuit to the input of the NU.

The ratings of R4 and RZ are selected so as to provide a bias of plus/minus several tens of millivolts relative to the “virtual ground”. I had no desire to remake the finished board and I added the necessary adjustable divider in place of the Ku adjuster.

In general, the resulting device satisfies my needs. Of course, it can be improved for a long time, but there is no need yet!

I’ll talk about the digital part and mathematics next time using the example of a volt-ampere meter in a laboratory power supply.

Ibrahim Kamal (IKALOGIC)

Note. It is not recommended to use source code samples located in the description text in your projects. At the end of the description there is a link to an archive with the complete source code for the project.

This article is for educational purposes. We will consider a hardware solution and software implementation in the task of measuring the voltage level of a battery (battery) using a microcontroller that is powered from the same source. It is assumed that users are familiar with programming AVR microcontrollers and have 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 methods and solutions for monitoring 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 only use 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 ATMEGA88, ATMEGA168, ATMEGA328 microcontrollers. In addition, by slightly correcting the source code, you can apply this solution to AVR microcontrollers with a built-in ADC.

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

You'll probably say: "So what's the deal. We will connect the positive terminal of the battery from which the microcontroller is powered 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 a voltage reference for the ADC.

If you look at 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 as follows:

,

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

Now, according to the conditions of our problem, we know that V_measure = V_REF = Vcc and as a result, the result of the equation will always be a value equal to 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 component called an internal Band Gap Reference Voltage. The output voltage of this source is about 1.1 V, and it remains unchanged when the temperature and supply voltage of the microcontroller changes. This voltage can be applied to the ADC input, 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 a 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 ADC reference voltage 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.1 V, from the equation we can calculate the supply voltage of the microcontroller

Vcc = 1.1 * 255/ADC_VALUE

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

Let's look at an example implementation.

Schematic 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)
{
ADMUX = 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);
}
}
}

Please note 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 Vcc value 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

We are moving on to the final part of the sensor review cycle, in which we will look at DC and AC current and voltage sensors. For all other sensors that were not included in the main series, we will make additional reviews when they are suddenly needed in future articles.
This article opens a new series of materials about measuring power quality parameters, which will include issues of connecting current and voltage sensors to a microcontroller, consideration of algorithms for the operation of power quality analyzers, the meaning of certain power quality indicators and what they mean. In addition, we will touch upon the topic of concern to many about the accuracy of digitization and data processing, mentioned in the comments to the first article.

Current sensors

Measuring shunt

The simplest and most accurate way to measure current. As you know, when current flows through an active resistance, a voltage drop occurs across it, proportional to the measured current. Great, we take a resistor and place it in the open circuit of the measured circuit:


Figure 10: Current sensor current shunt
The voltage drop across the shunt is proportional to the current passed:
(10)
Accordingly, depending on the required voltage at the sensor output, we select the required shunt resistance. But! The voltage drop across the shunt will lead to losses and heat, so at high currents we are forced to be content with low input voltage values ​​in order to limit losses. These commercially produced guys provide a standard output voltage of 75mV:

Figure 11: ShSM type current shunt
Most shunt measuring heads are calibrated to 75mV. Pay attention to the second pair of screws - they are designed specifically for connection to a measuring device to reduce losses.
To measure current using such shunts, the use of operational amplifiers is required. At the same time, the average gain is 20-40, which is within the capabilities of widely used operational amplifiers. In principle, this can be made on the basis of one bipolar transistor.
We get the following diagram:


Figure 12: Using an op amp as an amplifier
It should be taken into account that when measuring alternating current, the output signal will be bipolar and the operational amplifier must be powered from a bipolar power source.
Just in case, let's see how our scheme works:


Figure 13: Current Sensor Amplifier Simulation
We apply 75mV to the input, multiply by 20, at the output we have a signal with an amplitude of 1.5V for a current of 10A. In the next article we will figure out why a bipolar signal is bad.
Advantages:

  • high accuracy;
  • wide range of voltages and frequencies;

Flaws:

  • there is no galvanic isolation;
  • low efficiency.
Instrument current transformer

A measuring current transformer is a transformer, the primary winding of which is connected to a current source, and the secondary winding is connected to measuring instruments or protective automatic devices.
Current transformers are used to measure currents in high-current circuits, often at high potential. For example, we wanted to measure the current in a 10 kV network. Or, we want to get a simple and relatively cheap way of galvanic isolation of the measured current circuit of our 220V device. The main problem with current transformers is that they can only measure alternating voltage.
The current transformer is always loaded. If the secondary winding of the current transformer is open-circuited, then a potential of a couple of thousand kilovolts will arise on it, which will injure personnel and disable the device by breaking through its insulation.
Transformers come with a built-in primary winding. For example:

Figure 14: Coilcraft CS2106L Series Current Transformer
Either these elephants, which have something like a primary winding in the form of a huge bus, or even a window for passing wires through it


Figure 15: Industrial multi-amp current transformer
The main disadvantage of a current transformer is that it only operates at a certain frequency. A step to the left, a step to the right - execution. The metal core is to blame.
But if we remove it, we get an air transformer, or so-called. Rogowski coil:

Figure 16: Rogowski coil connection diagram
Unlike other sensors that require interaction with the measured circuit, the Rogowski coil can be installed on top of the wires of the measured circuit like a belt.
Some measuring instruments are equipped with the following sensors:


Figure 17: Rogowski coil sensor
The range of measured currents is from tens to thousands of amperes, but they suffer from low accuracy.
Advantages:

  • galvanic isolation;
  • work with high currents of thousands of Amperes;

Flaws:

  • measures only alternating current in a certain frequency range (except for the Rogowski coil);
  • changes the phase of the signal and requires compensation
Hall effect current sensors

Sensors of this type use the effect of a potential difference occurring when a current-carrying conductor is placed in a magnetic field.

Figure 18: Hall effect
When creating a sensor, we take a magnetic circuit, pass the wire of the circuit being measured through it, and place a Hall sensor in the section of the magnetic circuit, obtaining an open-type current sensor:


Figure 19: Open type Hall effect current sensor
The advantage of such a sensor is its simplicity. The disadvantage is the presence of core magnetization, therefore increasing the nonlinearity of the readings.
Let's add a winding to the core and pass through it a current proportional to the measured current:


Figure 20: Compensating Hall Effect Current Sensor
With zero core bias we increase the linearity of the sensor and its accuracy class. However, in its design, such a sensor is close to current transformers, and accordingly its cost increases significantly.
Like transformers, there are types of sensors that allow you to pass a power wire through them:


Figure 22: Hall effect current sensor
There are sensors with a split core - but their cost is simply off the charts.
Sensors with an integrated power circuit based on the Hall effect with galvanic isolation of 2.1 kV and 3 kV are produced by Allegro. Due to their small size, they do not provide high accuracy, but they are compact and easy to use.


Figure 23: Allegro ACS754 current sensor

  • ACS712 sensor – measurement of direct and alternating current up to 30A with an accuracy of ± 1.5%
  • ACS713 sensor – optimized for DC current measurement up to 30A. Has twice the sensitivity of its universal counterpart.
  • ACS754 sensor – measurement of direct and alternating current up to 200A with an accuracy of ± 1.5%
  • ACS755 sensor – optimized for DC current measurement.
  • Sensor ACS756 is a sensor for measuring direct and alternating current up to 100A with a supply voltage of 3-5V.


Figure 24: Sensor output voltage versus current
Advantages:

  • wide range of measured currents with frequencies up to 50-100 kHz and higher;
  • measures direct and alternating current.
  • galvanic isolation

Flaws:

  • Expensive
Additional links:

DC measuring transformers analogiu.ru/6/6-2-2.html
Rogowski coils www.russianelectronics.ru/leader-r/review/2193/doc/54046
Hall effect on Wikipedia: ru.wikipedia.org/wiki/Hall_Effect
Hall sensors robocraft.ru/blog/electronics/594.html
Danilov A. Modern industrial current sensors www.soel.ru/cms/f/?/311512.pdf
Design of circuits based on the analog amplifier HCPL-7851 www.kit-e.ru/assets/files/pdf/2010_04_26.pdf

Conclusion

I set myself the task of making a review of the sensors most commonly used by the community when developing various devices. Most of the sensors were not included in the cycle only for the reason that they will not be needed in the near future for my materials, but some of them are in the plans. I will definitely make a separate material with acceleration and angular velocity sensors, a compass and examples, so stay tuned for new articles!

Voltmeters on a microcontroller - what could be simpler? This is true when we are talking about measuring direct current, or determining instantaneous alternating current values. But the dimension effective value alternating voltage, especially non-sinusoidal forms is a non-trivial task. However, it can also be solved, and on a fairly simple and inexpensive microcontroller of the AVR family.

This article is more of a discussion on the topic than a description of a specific project. Its purpose is to direct thought in the right direction, to identify goals, pitfalls, to lay out a “pilot” to bypass them... So that everyone can independently implement the stated principle.

So, first, a micro-excursion into the theory. As you know, the effective value of alternating current and voltage is the value that is taken in the calculations of the released heat or power. For direct current, the effective value is equal to the amplitude, average and instantaneous; for alternating current, these are all different quantities.

Instant AC voltage value is the absolute voltage level at a specific point in time, a single reading. Amplitude value is the largest value of the sine wave (or other curve for a non-sinusoidal waveform) over a period. The amplitude value is taken modulo, i.e. There is no minus and plus amplitude. Average value, as follows from the term itself, is the sum of all instantaneous values ​​(samples) for a period, divided by the number of samples. Mathematically, it is the integral of instantaneous values ​​over a period. Obviously, for a sinusoidal shape, the average value over the period will be zero. If the shape of the voltage curve is distorted, then the average value over the period may turn out to be non-zero - then it is called constant component alternating voltage. Finally, current or efficient the voltage value is a value numerically equal to half the integral of the square of the instantaneous voltage values ​​over the period. That's why it is also called root mean square tension.

Now let's think about how this theory will help us solve our problem. In an MK we are dealing with an ADC, which (to some approximation) is capable of giving us individual voltage readings, i.e. it can determine instantaneous voltage values. It is easy to understand that to determine the effective value we need integrate(those. sum up) squares of ADC results, taken at regular intervals during one period measured voltage. Why am I not talking about the need to divide the sum of squares in half, although the theory seems to require this? Yes, because the ADC gives us the result in abstract numbers, divorced from reality. In order to get a real value from this abstraction, we still need to multiply them by some kind of dimensional coefficient, which can take into account that same division by 2. Let me explain: if “one step” of the ADC corresponds to 0.02V voltage, then to convert to real volts, we need to multiply the ADC result by 0.02. If in the process of calculations we then need to divide these values ​​by 2, isn’t it easier to multiply immediately by a factor of 0.01V?!

Let's outline the algorithm of our program. In general terms it will be like this:

  1. Obtain N ADC samples at regular intervals during one period of the measured voltage.
  2. Square the results and sum.
  3. Take the square root of the resulting sum.
  4. Multiply the result by the scaling factor and display the result on the indicator.

In order for our voltmeter to show the value continuously, this algorithm must be performed cyclically.

Now let's get into the details. First of all, let's decide on the number of samples N. It would seem that everything is simple: the larger it is, the more accurate the result. And this is true, but we should not forget that we do not have a supercomputer at our disposal, but only an AVR microcontroller, the capabilities of which are very limited.

First of all, there is a limitation on the speed of the ADC. Atmel recommends using an ADC when running at clock speed no more than 200 kHz, otherwise the error in the results will increase. One ADC measurement cycle lasts (in steady state) 13 cycles, i.e. with any tricks, we will not be able to use the ADC more often than 15384 times per second if we want to get all 10 bits of the result correctly. Let's figure out what we get as a result. The duration of the mains voltage period is 20 ms. With the above-mentioned sampling frequency, we simply will not have time to get more than 307 samples in one period. Of course, if you sacrifice a little accuracy, you can increase the speed of the ADC and, accordingly, the number of samples per period.

Another important limitation is the speed of mathematical operations. Squaring is a very expensive procedure in terms of the number of microcontroller cycles, and if you perform integration “on the fly”, i.e. As the results from the ADC arrive, a sampling rate of 15K will be unattainable even in theory. There is only one way out - to quickly accumulate the required amount of data in an array, and then slowly process it. And here we come across a third limitation - the amount of RAM. Theoretically, the maximum number of samples from 307 and 10-bit numbers will require 614 bytes of RAM for storage, which is already more than the entire available memory in many MKs, and for, for example, Atmega8 it is more than half. But to work, we still need space for the stack, for other intermediate variables... So the number of samples N=307 can be considered absolutely maximum for all MKs with RAM capacity of 1K or less.

To fill the array of samples, we use an interrupt at the end of the ADC cycle. That is, we will define an index variable pointing to the next element of our array, and in the interrupt handler we will save the ADC result in the array at this index and increase the index. Since, according to our calculations, 20 milliseconds should pass from the moment of the first sample to the last (307th), we can assume that we have solved the problem of obtaining instantaneous voltage values ​​over a period. However, it is necessary to control whether the index goes beyond the permissible value, i.e. check to see if we made more than 307 samples? Naturally, you need to be sure that the time of all additional calculations will not increase the frequency of receipt of samples, otherwise large errors will be inevitable.

Suppose we finally received our array of samples, and now we need to process it. Can you imagine squaring in assembly language? What about extracting square roots? Of course, everything can be solved, but it is much easier to use the built-in functions of the C language square And sqrt. From here there are 2 inevitable conclusions: we are making the program in C and all previous arguments require adjustments... This stunning conclusion should be understood as follows: C is a high-level language, and therefore significantly slower than assembler. This means that interrupt handling procedures may require more time than we expected, i.e. disrupt the harmonious calculations of the number and frequency of samples. This means that it is imperative to control the execution time of critical sections of our program (for example, in the same AVR Studio), and if it turns out that the sampling period is significantly longer than the calculated one, make adjustments to all calculations - from the number of samples to the ADC frequency. But let's forget about that for a moment.

So, the measurements and calculations are over. It remains to organize the output of the results. Here, as they say, the scope is wide: from seven-segment indicators with dynamic display to LCD character displays or transmitting results via UART to a computer. Just remember that dynamic display also works via interrupts, i.e. may distort the time intervals for obtaining samples.

I hope the principle is clear. Now a few words about the problems not touched upon. First of all, all our thoughts related to the measurement network voltage, i.e. voltage with frequency 50 Hz. At other frequencies, our program will give results with an error. The magnitude of this error will be minimal if it falls within 20 ms integer number of periods voltage (for symmetrical waveforms - half cycles). If the number of whole periods (half-cycles) is not an integer, the error will be maximum, and the nature of the voltmeter readings will have the form of “beats”. Since it is in vain to expect high accuracy from numerical integration with a number of samples over a period of less than several tens, the upper frequency value for the measured voltage in reality will be no more than 200 Hz. In short, we will still make a device only at 50 Hz. Although at 25 it will work quite well. Of course, the device will show the correct value for any form of alternating voltage 50 Hz, as well as for direct current.

Schematic diagram of the Proteus project

To confirm all the above calculations (and to verify them), I give a specific example of the implementation of a voltmeter. I did not assemble a real circuit, I limited myself to a project in proteus. However, the results obtained during the simulation fully confirmed the above and allow us to assert that the real circuit with minimal modifications (power supply and protective circuits) will work. The proposed firmware for MK is fully functional - modify the circuit, make a printed circuit board and use it. However, I did it in my own way, i.e. a little different than I just told you. The most important thing that is wrong in my program is the number of samples in the array: I have them 256 . Because of this, I had to abandon the “natural” frequency of the samples and tie them to a timer, this in turn required raising the operating frequency of the ADC to 250 kHz (with a clock frequency of the MK of 8 MHz). By the way, getting 250 kHz for the ADC from the built-in RC generator of the mega is much easier than 200, so it’s possible that when writing your own program you will also be forced to follow my path...

Project for Proteus 7.1 Pro SP2 and the firmware file can be downloaded in . In the project, the part that is the voltmeter itself is circled with a dash-dotted line. And to the left is the source of the test signal. The input bridge and voltage divider must be designed with a reserve for the input voltage; it is better to choose 1000-volt diodes, they will certainly withstand it. It is better to make the divider exactly as shown in the diagram - from three resistors, because one resistor of the appropriate value may not withstand high voltages. It’s even better to take more resistors; by the way, it will be easier to select the division coefficient. The diagram does not show many nuances, for example, a protective stabilizer at the ADC input, but these are just nuances. My firmware provides measurement of voltages up to 710V, with an error of no more than 2V for a sinusoidal voltage waveform. For other voltage forms, the error may increase, but not much. I think it will definitely fit within 5%. For a simple device with a scale of 10-700V, it’s not bad, isn’t it? The firmware has a feature: if a voltage with an amplitude value of more than 1000V (approximately) is applied to the input, the device will display the symbol “ E" - overload. This will happen even if the effective value is significantly less than 700V.

Only registered users can leave comments.
Please register or login to your account.