Archive January 2023

Single phase Inverter synchronization to mains using time continuous phase angle approximation with analog components

For impatient visitors, the LTspice model download is at the bottom of this post.

In our previous post we discussed the method that uses ZCD + flip-flops to extract the phase angle (angle of synchronism) using pulses whose duty cycle is proportional to the phase angle, and with a pulsing frequency of 2*f_ac, f_ac being the working frequency of the mains (grid) and inverter. Although this method is robust in the case of voltage variations, feeding pulses to our control loop required a more agressive low pass filtering strategy, and has a low gain at minimal phases angles, Overall it makes the control loop tuning harder.

So we will propose now a time continuous analog estimation of phase angle. It closely resembles to the single multiplier phase detector in the shape of the output, but does not involve a multiplier. This method is projected to be significantly more sensitive to voltage swells/sags and transients or voltage imbalances between the mains and the inverter, as it is the case for most phase detectors used in PLL. So it will involve signal normalization as well. We will try to characterize the performance of this method compared to the classic mutiplier based phase detector. Same as in the previous post, here we are discussing of synchronized inverters, not grid tied ones. As such, these inverters, perform voltage control independently of the grid conditions, that is one of the main benefits of the double conversion (online) topology, that always supplies power coming from the inverter stage at a stable regulated voltage while the grid voltage may fluctuate. On the other hand, line interactive or offline UPS perform AVR only using an autotransformer with taps to buck or boost a voltage by fixed increments. Since we have a potentially fluctuating grid voltage due to external conditions and a UPS voltage regulated at a nominal value, (not taking into account voltage fluctuations due to regulation inertia), it is important to characterize the sensitivity to voltage imbalances of the following method to assess its viability for the purpose of inverter phase synchronization.

Principle of operation

Instead of supplying the control loop a pulse whose duty cycle is proportional to the phase angle, with a postive pulse for positive phase angles and a negative pulse for negative phase angles. We supply the control loop the differential signal of V_mains(t) and V_inverter(t). That is V_mains(t) – V_inverter(t), after scaling the source signal to a level compatible with op-amps. Although it works to extract the absolute phase angle, assuming that the two voltages are of the same amplitude, preserving the lagging/leading information, that is the sign of the phase angle, requires careful processing of that signal.

Assuming a constant phase angle different than 0° and that the amplitudes of V_mains(t) and V_inverter(t) are the same,

We can see that the V_mains(t) – V_inverter(t) changes sign when V_mains(t) = V_inverter(t), although the lagging/leading status is still the same. That is why we need to switch the V_mains(t) – V_inverter(t) signal to -(V_mains(t) – V_inverter(t)) when V_mains(t) = V_inverter(t), to preserve lagging/leading information.

To encode the instant where V_mains(t) = V_inverter (t) using a basic sine to square circuit, we will feed the scaled down sum signal, (labeled ‘sum‘ in the schematic) V_mains(t) + V_inverter(t) to a comparator to get a square wave signal. The rising edge will happen at zero crossing going upwards of V_mains(t) + V_inverter(t), The falling edge at zero crossing going downwards. The points where V_mains(t) = V_inverter(t) will sit firmly at the middle of each HIGH or LOW levels time intervals. The resulting square wave signal is labeled ‘sum_sq’ in the LTspice model.

To establish a processing logic, We will also need to convert the difference signal, labeled ‘difference’ in the schematic into its corresponding square wave signal. This resulting signal is labeled ‘difference_sq‘ in the LTspice model. Note that the difference_sq signal switches polarity, that is, goes from RISE to FALL or vice versa at the points where V_mains(t) = V_inverter(t). More precisely, it is rising at V_mains(t) = V_inverter(t) when both V_mains(t) and V_inverter(t) are positive, and falling at V_mains(t) = V_inverter(t) when both V_mains(t) and V_inverter(t) are negative.

We used the LT1716 comparators for the ZCD sine to square conversion. It also conditions the square signals to 5V logic levels. It is tolerant to an input going down to -5V in relation to negative rail, here GND, while still outputing a valid 0V output in this case. This information is available in the datasheet.

Next we will establish a truth table for the above two signals.

TRUTH TABLEdifference_sq RISEdifference_sq FALL
sum_sq HIGH10
sum_sq LOW01
D flip-flop truth table

Note that we compare an edge signal to a level signal, for this edge triggered logic, a D type flip-flop comes handy. You may also ask why we need this convoluted logic, well it is necessary in order to preserve the leading/lagging information. In order to do that, we will need an additional logic stage between the above resulting signal, labeled ‘dflop‘ in the model, and the difference_sq signal. This time both signals are levels, so to establish the following truth table we will simply use a XOR gate.

TRUTH TABLEdifference_sq HIGHdifference_sq LOW
dflop HIGH10
dflop LOW01
XOR gate

The resulting signal will condition the state of the SPDT switch IC, the ADG333A IC is suitable for this application. The silicon SPDT switch will switch the output between $$ difference $$ and $$ \overline{difference} $$ input signals.

And that’s how we get an approximation of the phase angle, preserving the leading/lagging information. Note that the logic signal coming into the silicon SPDT switch not only has the result of switching polarity of the difference signal when the phase angle goes from leading to lagging and vice versa, but also performs rectification of the difference signal.

To better illustrate the action of the whole signal conditioning logic, we provide the following screen capture :

phase angle between inverter and mains oscillates between -90° and + 90° centered around 0°
Logic of the continous phase angle approximation signal conditioning block

Now that we have our proper phase angle approximation signal, it is time to feed it to the control loop.

Remember from our previous post that, assuming same frequency and voltage for both signals, and a constant phase shift or a phase variation frequency that is negligible compared to f_ac :

$$ (1)\hspace{1cm} \left | \Delta \varphi \right | = 2arcsin(peak( \frac{\left |V_{mains}(t) – V_{inverter}(t)\right |}{2V_{max}} )) $$

with peak() defined as the function that returns the peak value as a step function over the time range of interest defined below.

Note that for : $$ (2)\hspace{1cm} \left | \Delta \varphi \right | \ll \pi $$

$$ (3)\hspace{1cm} \left | \Delta \varphi \right | \approx peak( \frac{\left |V_{mains}(t) – V_{inverter}(t)\right |}{V_{max}} ) $$

Being sinusoidal in nature, it follows that for a time interval $$ (4)\hspace{1cm} \left [ t_{1} , t_{1} + \frac{1}{2f_{ac}} \right ] $$ or multiple thereof,

(3) is a linear relationship because $$ (5)\hspace{1cm} peak(k\times a(t)) = k\times peak(a(t)) $$ provided that (2) is true. Note that for the ZCD discrete phase angle method of our previous post, there is a linear relationship over the whole [ -pi , pi ] domain.

The main difference then lies into the LP stage filtering response of our control loop between a variable duty cycle bipolar square wave signal with 2*f_ac frequency and a bipolar sinusoidal signal with rectified sine harmonics at 2*f_ac frequency.

Phase angle control loop

We reused at first the phase control loop from our earlier post design :

https://www.skynext.tech/index.php/2023/01/16/single-phase-inverter-synchronization-to-mains-phase-using-the-zero-crossing-method-and-proportional-derivative-control-with-analog-components/

Since this post, it has been updated with an additional integral term to get a PID control loop.

This loop already gave relatively good results (phase angle < 0.75° for most disturbances in our simulation bench). We used it too gather data in the new phase continuous model as a reference for improvement.

Then, we optimized the loop design to get a better phase response. For this, we got rid of the butterworth filters after the integral and derivative stages, as well as a tuning of the integral cutoff frequency and the derivative peak response frequency. We will post both results here as well as the Bode plot of the new control loop.

Voltage imbalance sensitivity

Voltage amplitude imbalance between mains_scaled and inverter_scaled has effects on the diff_out signal that are mostly characterized by a reduced sensitivity to small phase angles. The signal shows a larger DC bias, which swamps the response to angle variations.

The leading/lagging transition response seems less affected, the system being able to detect the transition in small phase angle oscillations, even in the presence of a moderate voltage imbalance.

Let’s discuss the possible mitigation strategies of the voltage imbalance sensitivity.

For the purpose of phase synchronization outlined above, the inputs of the control system are :

  • Inverter voltage sensing coming from an isolation transformer on the output of the inverter.
  • Mains/grid voltage sensing coming from another isolation transformer

Both of these inputs could also be used for voltage (amplitude) sensing. Inverter voltage sensing is already used for inverter voltage (feedback) regulation. If we wish to compensate the voltage imbalance for phase synchronization, we may need to sense both.

Voltage amplitude sensing methods usually implement peak detection using smoothing capacitors and a full bridge rectifier.

Inverter voltage is dictated by the inner voltage/current control loop and possibly an outer control loop. It is subject to a certain amount of inertia. Moreover, set/regulated voltage may well be different than the nominal 240V AC.

Mains/grid voltage is dictated by the grid. We also have to take into account the serial impendance of the transmission line and that of the 10kV/240V utility transformer. These will produce a voltage drop dependent on the load, and account for a large portion of voltage variation during the day.

If, for whatever reason we wish to implement the proposed method above we would need to get rid of the voltage amplitude difference.

  • Either we establish the mains voltage as a reference, and make the inverter follow it, by controlling the amplitude of the independently generated sine wave reference of the SPWM modulator. In that case, it defeats one of the main purpose of an inverter, specially for online (double-conversion) UPS, which is voltage stability independently of the grid.
  • We could also use the mains voltage as a reference to the full extent, after scaling it down, by using the mains voltage waveform as the sine wave reference used in the SPWM generation, in that case, the inverter also follows frequency and phase of the grid as a bonus, which render the whole synchronization issue of the present article moot. The downside is that the inverter output is now subject to all disturbances of the grid, including transients, noise, etc… if adequate filtering is not provided. The inverter now works as a class-D amplifier.
  • Third option, we establish inverter voltage as a reference, and make the mains (scaled down voltage input) follow the inverter voltage in terms of amplitude. Since we have no control on the voltage from the grid, the only method that seem plausible would be to perform AGC (automatic gain control) on the sensed mains voltage to make it follow the sensed inverter voltage.

The later is not without problems though. We predict that there may be quite a high amount of crossover interaction between the phase/frequency control loop and the voltage/current control loop, making tuning of both difficult. Let’s try nevertheless.

Implementing AGC on mains voltage sensing

Since an inverter voltage control loop usually implements voltage sensing for its output using a peak detector (with attack/release control), And that doing the same for the mains voltage is also usually a requirement, for instance, to detect voltage sags/swell that go beyond the AVR capability, or simply for mains blackout detection, it seems that it would not cost much to at least try to implement an AGC for the goal of phase angle synchronization using the peak detectors outputs as differential inputs to generate a voltage control signal based on the voltage error that will be subsequently applied to a VCA. The VCA will perform AGC on the scaled mains voltage signal to keep it at the same amplitude that of the scaled inverter voltage. Then phase angle measurement can be performed without worry about the effect of amplitude imbalance.

The VCA would not need to have fancy requirements. It does not need high bandwidth, since it will work on a 50 Hz signal. It does not need high dynamic range, since it will operate on a mains voltage plus/minus 20% (worst case scenario) deviation from the nominal 240V AC. (Mains voltage is required in Europe to stay in the plus/minus 10% range from the nominal 240V AC.)

However, It would preferably use linear voltage control of the gain. That is to ease the loop design and tuning.

Voltage transient filtering (or what remains of it after the TVS upstream) could be achieved by tuning the attack potentiometer of the peak detector stage. However a compromise should be found between a good transient response and a good voltage following response so as not to introduce too much delay. This is not an easy task.

Given the requirements, a TI VCA824 IC seems a good choice. Other options although not tested would be to use an OTA like the LM13700, Finally we could also use an audio VCA like the THAT 2180x series, but it also OTA-like since it sources/sink current at the output, so either a resistor or better a current to voltage op-amp block is needed at the output. However the THAT 2180x is an exponential (dB/V) voltage controlled device, Whereas the VCA824 IC is linear (V/V). An advantage of the THAT 2180x is that it features a 0dB gain at 0V center point. It is not the case for the VCA824, Where the unity gain is closest to 0V gain control for a 2V/V max gain setup (dictated by the Rf/Rg feedback resistor setup). Even with a 2V/V gain setup the unity gain point is not exactly at 0V (at least in our setup). But this is not that much of a problem since there is a control loop for amplitude that takes care of it. Other issue encountered with the VCA824 IC is that we had to correct input and output offset voltages using voltage dividers at the signal input and output as shown in the datasheet. Using AC coupling for that purpose is a big no no since it would introduce delay. Finally, there is the cost issue. VCA824 is expensive and its features underutilized since it is tailored for HF/VHF use. But it works well for VLF like 50 Hz too. Finally, there is the issue of dynamic range. VCA824 can’t take much more than ± 1.6V at input, and goes sensibly lower than ± Vs for the output. Here Vs is ±5V (rail to rail) and this is the max for safe operation. To get some operational margin for voltage sags and swells, we setup max gain at 3V/V, and the whole setup works so as to obtain a normalized 1V amplitude mains signal, whatever the voltage sag/swell condition is. We expect the setup to be more sensitive to noise because of the reduced signal amplitude that is fed to the continuous phase angle measurement logic.

Amplitude control loop to get a normalized mains signal

Amplitude disturbance

For now, we only considered single tone FM disturbance of mains grid voltage. We still have to tackle amplitude disturbance like fast voltage transients with a clamped profile (from the TVS action), temporary overvoltages/undervoltages (from load rejection / load connection events in a generator setup), and slow voltage daily/hourly variations due to load profile change across several utility subscribers sharing a 11kV/230kV transformer.

First we will test the performance with a static voltage deviation from nominal 230V and see how the AGC performs, and how the whole loop behaves.

<to be continued>

Harmonics Disturbance

This is the hard part. It is expected that with a good voltage following characteristic, the whole loop would also somewhat track harmonics from the grid. Our goal would be to track the phase and frequency of the fundamental, not the harmonics ladden signal. We could think that filtering the mains signal would be a good idea, However we would need a really flat phase response (like those of Bessel filters), and even with that, we would need to compensate the delay with something like an all pass filter tuned to bring the 50Hz signal to a 360 phase or multiple thereof. That would introduce phase problems for frequencies other than 50Hz. Moreover, Bessel response is inadequate to filter the third harmonic sufficiently since it is so close to the fundamental. We could use a Butterworth LP filter but phase response issues would be even worse with each increasing order. We could think of a really good rejection of harmonics with a resonant filter, but that would be the absolute worse of the worse in terms of phase issues. Harmonics rejection is at the current state of analog filter technology an intractable issue in our opinion and would be better tackled in the Z-domain. Comment if you disagree.

Nevertheless, we added a harmonics disturbance setup in our model with 3rd,5th,7th,9th and 11th harmonics setup with amplitude (in % of fundamental amplitude) and phase (for each harmonic) to characterize the performance. At this point, the equation (3) is unsuitable, unless we compare the output sine reference to the fundamental of the harmonics disturbed signal.

Simulation Model

The simulation model includes the ASC Ltspice file with all packages dependencies (asy,sub,lib) in the same folder. There should be no need to tweak inside the file for absolute paths as they have been removed. No non-standard diodes, fet, bjt are used so there should be no need to add lines in the respective files (such as standard.dio or standard.bjt)

This model only models the PLL, not the full inverter. It’s goal is to generate a synchronized sine reference from mains voltage, and be tolerant to voltage sags/swells, frequency variation as well as harmonics. Harmonics should be rejected in the sine reference as much as possible.

Recently I added a block to simulate ADC operation with with sample time quantization and amplitude quantization to more accurately simulate an AD7366 ADC.

It includes a test bench block to simulate :

  • Amplitude disturbance
  • Frequency disturbance
  • Harmonics disturbance
  • Initial phase angle

It also includes the PLT files for plotting.

More information available in ____README____.txt inside the zip archive.

Have a nice day !

Single phase Inverter synchronization to mains using the zero crossing method and proportional / derivative control with analog components.

This is an introduction on inverter phase synchronization. The simulation files are included at the end of this post.

There are several digital and analog control methods to meet this goal.

In no particular order, we have DFT, KF, WLSE, ANF, KALMAN, PLL,FLL and ZCD. Most of them are documented in the digital (z-domain). A few only are easily implemented in analog.

We will discuss the easiest method, which is the zero crossing detection method, (ZCD) and assume that the inverter is not grid tied, simply synchronized.

Grid tie operation designs are diverse and fall into the grid following, grid forming, or grid supporting designs. This design is not intended for grid tie operation. These designs will be the object of another post.

The application goal, here, is mostly to have the inverter supply a voltage that is synchronized with the mains phase to enable seamless switching with an ATS that is external to the UPS, or inside the UPS unit independent of the technology used (offline,line-interactive or double conversion)

We will provide a hybrid analog/digital LTSpice model for phase synchronisation using the ZCD method.

It is “hybrid” in the sense that the inverter reference sine used in the modulation is phase modulated through a behavioural voltage source, that is more or less equal to what a DDS IC would do, but in a ideal manner since it comes without any quantization noise in LTSpice.

This model will be further updated. Note that phase synchronization using the ZCD method is performed using fully digital means in commercial ASICs. Providing a partially analog method is useful however for teaching analog control and for certain niche cases where the inverter SPWM generation and control feedback cannot be fully automated in the digital domain. (like using an Arduino instead of a fully capable DDS platform), In these cases, offloading part of the control loop to analog components is an option. Generally, fully analog control is less and less used except for simple feedback like in SMPS.

But there are still niche uses, for instance, an environment subject to ionizing radiation where hardening the ASIC is not possible, would be more robust in analog but that would require a fully analog control loop.

How to get phase difference between mains phase and inverter phase using ZCD the analog way ?

The analog ZCD method translates a sine wave (here, the output of the inverter or that of the mains power) into a square wave signal. the rising edge of the square wave signal happens at the upward zero crossing of the phase, and the falling edge at the downward crossing of the phase.

ZC sine to square wave conversion is done both for the mains and inverter phases. This is done using an op-amp comparator without feedback for each phase. The output signal is a square wave with rail to rail voltage levels.

Then, the two square signals are compared using two D type flip-flops, giving outputs pulses widths that are equal to the absolute phase difference information. (it outputs time information, not an angle value)

The method is explained in “Phase measuring circuit with leadlag indication” by Forrest P. Clay Jr. a 1992 electrical engineering paper.

https://sci-hub.ru/10.1119/1.16908

This method preserves the phase lag/lead information. One flip-flop provides HIGH output in leading conditions, While the other provides HIGH output in lagging conditions. Fundamental pulse frequency is the same as the mains and inverter frequency (assuming that both have a frequency deviation that is negligible compared to the nominal frequency) that is, 50 Hz in the model.

Phase difference detector circuit used in the simulation

Then, the output from the flip-flops is given to an op-amp substractor that generates a bipolar signal of the phase difference. Positive pulses mean leading while negative pulses mean lagging. Care must be given to the resistors tolerances (1% or better) in a substractor to minimize common mode interference, and a suitable OpAmp for this kind of use is prefered.

This signal is then low pass filtered to remove edge induced discontinuities. Note that usually the mains frequency slew rate is really slow because of the huge rotational inertia of all generators creating the mains distribution network and all regulation mechanisms in place. So it is not a problem to have a filter with a very low cutoff frequency. On the other hand, if the inverter were to synchronize to an islanded generator, that would be a whole different scenario. It is outside the scope of the current article. For these scenarios, other synchronization methods exists, and we named a few at the beginning of the article.

The filter used is an analog 3rd order butterworth LP filter, to get a sharp rolloff. The first stage has a quite high corner frequency, in order to minimize filter phase effects at low frequencies. Its goal is to minimize rising and falling edges coming from the ZCD and flip-flops well enough for the differentiator stage not to complain.

We then get a smoothed phase shift signal $$ \Delta \varphi $$ . This is fed to a differentiator op-amp setup. Its role is to generate the $$ \frac{d(\Delta \varphi )}{dt} $$ signal used further in the control loop. Note that because of processing this signal has a delay, so our notation is a little it abusive.

This signal is further processed using a second 3rd order butterworth LP filter, with a corner frequency way lower than the first butterworth filter. This gets rid of the spikes in the signal. The corner frequency is around 1Hz.

This concludes the generation of the $$ \frac{d(\Delta \varphi )}{dt} $$ processed signal that will be fed to the control loop of the inverter, for the derivative term.

In parallel, we need to get the proportional term. This will use a single butterworth 3rd order LP filter that branches just after the substractor. This will generate the proportional term also fed to the control loop of the inverter. This filter has a lower corner frequency compared to the first LP filter stage used for the differentiator branch.

Note that the final butterworth filter of the derivative signal branch has been slightly tuned out from its canonical form to get an appropriate control loop frequency/phase response.

Other than that, the remaining filters are quite the same. The differentiator has an added C2 capacitor to filter high frequency terms and provide less oscillation.

These two signals (proportional and derivative) are then factored with their respective gains (both are the same in the simulation) and fed as a sum to the behavioural voltage source of the inverter using the phase term of its function.

Note that this is a simplified model of the inverter stage. A more realistic but computationally intensive model would control the sinusoidal reference of the SPWM stage of the inverter, and inverter output would be fed to one leg of the phase difference detector. This would integrate the whole SPWM inverter model to this simulation. Note that this simulation do not include RLC loading of any of the phases. Also, this model supposes that the mains and inverter AC voltages are the same and stable at AC RMS = 230V.

One advantage is that the ZCD method is quite tolerant to voltage variations, compared to methods that are sensitive to it like PLL, So It is not critical to have it factored in this simulation.

Control loop. Not shown the final mixing stage that happens in the BV sine source of the inverter

AC Analysis of the control loop

An open loop AC analysis starting from the input to the first LP butterworth filter up to the output of the sum of the derivative and proportional terms with their respective gains has been performed.

Content of the control loop AC simulation file
Bode plot of the control loop. Plain line is Gain, Dotted line is phase

The range of frequency analysis for our first inspection is 0.001 Hz to 100 Hz

The cutoff frequency is approximately 0.66 Hz

The DC Gain is approximately 43.2 dB with a flat response.

Gain margin is -3.5 dB (at f_GM = 48.1 Hz) This could be improved for stability, knowing that this frequency is quite critical being close to the 50 Hz component in the phase difference pulse signal.

Phase Margin is 9.8° degrees (at f_PM = 38.6 Hz). Phase margin could also be boosted. Phase margin stays positive below f_pm.

There is a pole around 0.66 Hz and another close to 1 Hz, barely visible in the plot.

The control loop will be further optimized when I have time. I am no guru of control loops and filters so if you manage to get an optimized model, please chime in using the contact form…

Mains Disturbance simulation

Frequency disturbance

The first goal is to characterize how tightly the inverters locks on the mains frequency that is, $$ min(\Delta \varphi) $$ and $$ max(\Delta \varphi) $$ for a given mains frequency disturbance scenario. We also used a simple function to get an idea of the magnitude of the absolute phase difference by plotting $$ \left | V_{inverter} – V_{mains} \right | $$ and look at the local maxima. note that this plot does not suffer from the delays coming from the LP filters.

Simple FM disturbance

The disturbance scenario modeled this far is a mains frequency oscillation with a parametrized slew rate and oscillation amplitude, using a simple FM modulation scheme. The peak instantaneous frequency deviation will be restricted first to ±0.2 Hz to get in line with the ENTSOE ordinary and contigency frequency deviations, that is, an oscillation between 49.8 and 50.2 Hz

Frequency Stability Evaluation Criteria for the Synchronous Zone of Continental Europe

(section 3, Evaluation Criteria)

https://eepublicdownloads.entsoe.eu/clean-documents/SOC%20documents/RGCE_SPD_frequency_stability_criteria_v10.pdf

There is also this small study from Twente University from 2005 about stability of mains tied clocks.

Accuracy and stability of the 50 Hz mains frequency

https://wwwhome.ewi.utwente.nl/~ptdeboer/misc/mains.html

Since time keeping by these clocks rely on the number of cycles of the mains period, it makes sense to calculate the phase error. This study precisely do this, measuring phase deviations and not only frequency deviations. Phase errors in a power distribution grid come from frequency instability. To compensate for phase errors, an utility company would have to precisely manage frequency compensation at regular intervals to “get back” to the theoretical number of cycles expected. The priority is frequency, not phase, and mains tied clocks are superseded by GPS. However, this anecdotal study is however of special interest since we are dealing with both frequency and phase adjustments in grid synchronization. Note also that an abrupt phase adjustment in a rotational generator such as synchronous machines used in power plants would come from disastrous events such as pole slipping and/or sudden uncompensated load rejection. It should never happen on the scale of an utility grid.

As for the frequency, the slew rate for mains frequency is extremely low in ordinary and even contingency modes, So a rate of 1 Hz is already an extreme worst case scenario. Higher slew rates however happen with islanded generators, but this is outside the goal of this simulation. Given the response of the control loop, low slew rates should not pose a stability problem. However, this depends on the detection threshold of the flip-flop stage. A minimal instantaneous frequency deviation would not be catched until it reaches this threshold.

Note also that frequency deviations include stochastic noise but also predictable deviations according to load consumption and power generation imbalances. Periods of high demand typically introduces a negative frequency deviation until the power generated matches the load power.

As said before, the ZCD method is sensitive to harmonic disturbances typically introduced in non-inverter type islanded generators with low power handling capability relative to load. Thus, further characterizing the control loop for worst case scenarios would need to introduce this kind of disturbance, if one were to use ZCD with generators nonetheless.

Amplitude disturbance

<to_be_continued>

Phase synchronization from arbitrary initial phase difference

The other goal of the simulation is obviously to track the performance of phase locking from an initial arbitrary phase difference. The inverter has to lock its phase at 0° degrees phase difference from any starting phase difference ranging from -180° to +180° degrees. The performance of this locking process, that is how fast the phases converge to 0° and if the inverter experiences excessive harmonic disturbances during this process will have to be characterized.

Assuming both mains and inverter voltages are of the same amplitude, perfectly sinusoidal, and that the inverters track frequency change instantly or that the simulation is performed at fixed AC mains frequency, performance of phase synchronism can be measured through the following formula, giving the the absolute value of voltage phase difference.

$$ (1)\hspace{1cm} \left | \Delta \varphi \right | = 2arcsin(peak( \frac{\left |V_{mains}(t) – V_{inverter}(t)\right |}{2V_{max}} )) $$

Note that for $$ \left | \Delta \varphi \right | \ll \pi $$

$$ (1a)\hspace{1cm} \left | \Delta \varphi \right | \approx peak( \frac{\left |V_{mains}(t) – V_{inverter}(t)\right |}{V_{max}} ) $$

with peak() defined as the function that returns the peak value as a step function over the time range of interest defined below and

$$ (2)\hspace{1cm} V_{max} $$

the mains and inverter voltage amplitude.

$$ (3)\hspace{1cm} \left [ t_{1} , t_{2} \right ] $$

Since the ‘periodicity’ (the periodicity of the mains frequency induced harmonic component) of the function above is $$ \frac{1}{2f_{mains}} $$, that gives the optimal sample time to extract the maxima when sampling the above function (1)

The above function (1) can be simply plotted. If you need to extract maxima at sampled intervals use these LTspice directives and loop them with subsequent time intervals of $$ \frac{1}{2f_{mains}} $$ and put them into a .MEAS file, although it would need a long simulation time to make sense. For complex data analysis it is better to make a LTspice export of the data and process it with Python for instance.

.meas TRAN Vdiff_abs_norm_max MAX (abs((V(vl) -V(vn)) - V(mains))/(2*1.414*{V_ac}) ) FROM 0ms TO 10ms
.meas TRAN delta_phi_abs_max PARAM 2*asin(Vdiff_abs_norm_max)

measuring the minimum phase difference (best performance at steady state) is less trivial because of zeros in the function when the sine waveforms cross each other, therefore it would require sampling the phase difference with the above method and then analyze the resulting data for local minimums. Overall, another useful metric is simply done by averaging the sampled maximum phase difference (CTRL+click) for function (1) over a long interval, preferably equal to a full oscillatory cycle that arises from the control loop, if one is found.

Finally, performance in phase locking has to be demonstrated in conjunction with a FM disturbed mains frequency.

Note that phase locking is preferably done while keeping the waveform sinusoidal in nature during the process. Phase locking in figure 2 happens too quickly, and has the effect of producing severe distortion. The inverter should have adequate protection to not supply power during this event, only after proper phase locking is done. In a mains synchronized double conversion UPS, this could happen if the input is switched between two phases (120°shift) or after the powering on and transfer to a generator. Since a double conversion UPS always provides power through the Inverter stage with no possible downtime except a minimal one for switching to and from bypass mode, the control loop has to be tuned to take that into account. A modification of the phase control term in the sine wave DDS generator could be done and would take effect only during these initialization/switching events, for instance, using

$$ 1-\exp\left(-a\cdot t\right) $$

as a factor of the control term, ‘a’ controlling how fast the control loop locks into the mains phase.

Simulation results

Fig. 1 initial phase difference +90° , frequency disturbance : modulator freq. fm = 1Hz, modulator Amplitude Am = 0.3V
Fig. 2 Initial phase difference +180°, fm disturbance unchanged. Note the large disturbance of inverter phase during the lock process. Locking happens in less than a period
Fig. 3 frequency disturbance : modulator freq. fm = 1Hz, modulator Amplitude Am = 1V
Fig. 4 frequency disturbance : modulator freq. fm = 1Hz, modulator Amplitude Am = 1V At this slew rate of mains frequency and high frequency deviation, performance is degraded.
Fig. 5 frequency disturbance : modulator freq. fm = 1Hz, modulator Amplitude Am = 0.3

Using the ZCD method, sampling time is limited at two times the mains AC frequency. That limits accuracy of the algorithm for fast and ample disturbances. But a heavily distorted power source would not lead to any application requiring syncing into it, rendering that issue moot.

On the other hand, ZCD is quite tolerant to voltage fluctuations.

Conclusion

Although this controller is simple to implement, it suffers from steady state error due to the limited gain at DC. One option to mitigate this is to add an integral component. However, it would still suffer from delayed response to oscillations due to the butterworth filters, and cannot track fast oscillations. The ZCD+Flip Flop stage also samples phase at 1/2*f_ac, which is a limiting factor. The non linear behaviour introduced by the discrete function of the flip flops, who encode phase difference as a pulse further make the tuning of the control loop harder, with the need to analyze the impulse response of the system. However the discrete ZCD phase difference method is more robust when it comes to voltage imbalance between the two measured phases.

In a next post, we will propose a time continuous control of phase difference without flip-flops in the control loop signal path (although one is still needed in the circuit).

To get back to the conclusion on this model : Its performance level is unacceptable for grid tie operations, nor it provides the required functions and behaviour of GFL,GFM,GS grid tie topologies. That is why we limit it to synchronization for inverter standby/autonomous operation to alleviate source switching transients. But it is a good introduction on the subject. For an idea, it is closer to the state of the art for the start of the 90s or so, when digital control was not yet so widespread.

We will discuss grid tie inverters in a later post and slowly but surely move into the more state of the art technologies. It will also serve as an introduction into fully closed loop control systems, as with grid tie inverters, voltage,current quantities are intimately tied, and reactive power effects have to be taken into account.

Beware, the learning curve will be steep.

Simulation files

EGMicro EGS005 board review

The goal of this post is to analyze in detail the advertised features of the EGS005 board, and show possible modding hacks.

The EGS005 board is the newest board provided by EGMicro for single phase and multiphase inverter designs.

It is based on the EG8025 ASIC that features integrated MOSFET drivers for a full bridge configuration.

Most if not all all of the EGS005 information is also provided in the EG8025 datasheet, plus many more details! We will use the EG8025 datasheet as the reference material, but also compare them to the EGS005 board features, to see what features are restricted by the board.

The EG8025 datasheet is available on the EGMicro website, chip center section.

Probable IC orientation

Pinout analysis and IC orientation.

Based on the application schematic and components names and indexes placement, and after boosting trace contrast, it seems pretty evident that this is the ASIC orientation on the EGS005. The D4, D5 diodes and the C17 capacitor with its traces clearly shown going up to the pin, plus the 3 NC pins at the bottom and at the right side make it the only possible configuration. This setup would make the pin1 orientation dot in the product image misleading.

Differences between EGS002 boards and EGS005 boards

We will focus our attention first to the differences in features between these two boards. This takes into account only the features exposed through these two boards, not the overall feature differenciation between EG8010 and EG8025.

EGS005 has these additional features compared to EGS002 :

  • integrated MOSFET drivers
  • Test mode for SPWM output bench testing without any control loop feedback
  • overload protection (not only overcurrent hard limit)
  • Two over temperature control zones (IGBT/MOSFET and PCB)
  • SPWM signals routing swap on/off between left bridge and right bridge MOSFETs
  • AC output enable/disable through pin (basically a soft shutdown)
  • Exposed Serial interface (RX and TX), but configuration settings registers besides switching in and out of “Test mode” are either unavailable or undocumented.
  • Exposed pins for firmware update

EGS005 features that are discontinued compared to EGS002 :

  • Variable frequency output mode up to 100Hz or up to 400Hz. This includes variable frequency mode and fixed ratio V/F mode.
  • Choosing between unipolar and bipolar SPWM. Note that EG8025 supports phase synchronisation/phase shift for 3 phase mode, so the modulation scheme had to be made unique for interoperability.

EG8025 features not exposed in EGS005 :

  • Phase shift mode for AC sensing from another unit – Phase_SEL pin 12
  • AC input for phase synchronization/shift from another unit – VZC_IN pin 17
  • AC output for phase synchronization to another unit – AC_Fout pin 13
  • Multi inverter pin for parallel operation or master/slave select for three phase operation – Multi_INV pin 15

Inverter phase synchronization and phase shifting

Inverter phase synchronization is required for the following operation modes.

  • Parallel mode of operation of two or more inverters sharing a single phase for load sharing / redundancy.
  • Parallel mode of operation between one or more inverters and the AC grid, These inverters are known as Grid tie inverters. They are ubiquitous in renewable energy systems for residential or industrial use.
  • Parallel mode of operation between inverters or between inverters and AC grid, who do not share the load for redundancy (active/standby system). The phase is kept synchronized between the sources for seamless operation of an ATS (Automatic Transfer Switch). This is to limit potentially high dV/dt (and/or high dI/dt) that happen during switching when the phases are not synchronized.
  • Multiphase mode and inverter daisy chaining (cascade) of phase synchronization across usually three units, for three phase power applications, In a (master)/(slave/master)/(slave) configuration. Parentheses correspond to the three inverters.

There are several digital algorithms and analog tehcniques to implement phase synchronization.

One well known and ubiquitous method used in various electronics designs not limited to inverters is PLL (Phase locked loop). There are however other methods. This paper discusses them in detail :

Recent advances in synchronization techniques for grid-tied PV system: A review

https://www.sciencedirect.com/science/article/pii/S2352484721008118

EG8025 Phase synchronization

The EG8025 ASIC uses the Zero Crossing method. It is simple and straightforward.

It uses 2 pins for configuration. Multi_INV pin 15 and Phase_SEL pin 12 and 2 pins for synchronization data. One is an output pin, AC_Fout pin 13 the other is an input pin VZC_In pin 17.

Parallel operation mode

We’ll assume that we use two inverters.

In this mode both inverters share the load on the same phase. One unit is designed as master and has Multi_INV pin 15 pulled log to GND, The other is designed as slave and has Multi_INV pin 15 pulled high to 5V.

The master unit also has VZC_In pin 17 and Phase_Sel pin 12 pulled to GND. Since the master is the start of the synchronization chain, it won’t use an input ZC signal, nor it should shift the phase 120° for parallel operation. Applying phase shift in this mode of operation could destroy both inverters output stages !

The master outputs its phase information through the AC_Fout pin 13. This is a zero-crossing signal. It probably converts upward going zero-crossings of the AC phase to logical HIGH, and downward going zero-crossings of the AC phase to logical LOW. Rising/Falling edges should happen at the time of the zero crossings. Checking precisely the logical levels correspondence is required if this board is to work with another unit of another manufacturer supporting ZC synchronization, to prevent a 180° out of phase condition. Level shifting may be required to accomodate the slave unit.

The slave in turns gets its ZC information on the VZC_In pin 17. The path between AC_Fout pin 13 of the master and VZC_In pin 17 is isolated with the use of an optocoupler. Check figure 10.a of the 8025 ASIC Datasheet. On the slave unit Phase_Sel pin 12 is also pulled to ground while AC_Fout pin 13 is floating.

Since AC_Fout is a low impedance pin current source, it should never get pulled to GND.

Modding for parallel operation.

We should investigate the board and the EGS005 application schematic to look at the trace routing of VZC_In, AC_Fout, and Multi_INV.

Modding fo the slave unit :

  • VZC_In is pulled to GND through the R45 1k resistor. Making the VZC_In as an input as shown in figure 10.a would require soldering out the R45 resistor and supplying the signal to the exposed pad of R45 connected to the pin. This signal comes from the optocoupler voltage follower.
  • AC_Fout and Phase_Sel do not need any mod on the slave unit.
  • Multi_INV trace to GND should be cut and a patch wire soldered and connected to 5V HIGH level

Modding fo the master unit :

  • AC_Fout is floating on the EGS005 so a simple wire patch to the pin would do the trick. This wire would be routed to the optocoupler diode anode.
  • Multi_INV and Phase_Sel do not need any mod on the master unit.

For a tutorial on how to perform SMD pcb wire hooking look at :

EGMicro EGS002 board review

The goal of this post is to analyze in detail the advertised features of the EGS002 board, and show possible modding hacks.

The EGS002 board is the oldest provided by the EGMicro supplier still distributed on common Chinese reseller platforms. It superseded the even older EGS001.

It is based on the EG8010 ASIC and also features either two IR2110S half bridge drivers, or two EG2113, an EGMicro driver. Whether you get one or the other depends on the reseller. Check for comments and reviews on marketplace product page to see who’s getting what.

Most if not all all of the EGS002 information is also provided in the EG8010 datasheet, plus many more details! We will use the EG8010 datasheet as the reference material, but also compare them to the EGS002 board features, to see what features are restricted by the board.

EG8010 ASIC Features

Input DC Voltage. The EGS002 can drive high voltage MOSFETs easily. no restrictive voltage limitations on the high side MOSFETs, and it is at least ok for 400V DC input to the MOSFET bridge. Supplied design schematics show power coming through a 400V DC link PFC output.

Inverter output frequency. EG8010 can be used for fixed 50Hz,60Hz or frequency adjustable 0~100Hz or 0~400Hz output.

The EGS002 on the other hand restricts this feature to fixed frequency operation : either 50Hz or 60Hz, through jumpers.

These jumpers are exposed on the bottom plane of the board and are set with solder bridges over two pads. They do not appear to be through hole, so it would be difficult to insert header pins and use a real jumper there.

the backside exposes the configuration jumpers. top left of image

JP1 and JP5 on the board control FREQSEL0 pin 18 level (either HIGH=JP1 short for 60Hz or LOW=JP5 short for 50Hz). They can’t be short or open at the same time !!

Is the board moddable for further frequency control ? let’s see.

There seems to be two methods to apply mods. Either through hardware or through software (by serial commands). Let’s explore the hardware method first.

Variable Frequency mode modification

Up to 100Hz or up to 400Hz variable frequency operation mode selection is controlled by FREQSEL1. It seems however that the EGS002 has the FREQSEL1 pin 19 grounded in the EGS002 schematic. So it depends on the suppliers of EGS002 to create derivative boards that expose FREQSEL1.

As far as I searched on Chinese marketplaces that doesn’t seem to be the case.

PIN 19 and PIN 20 Traces Merge. right around the center of R33. Processed image to better expose the traces

FREQSEL1 pin 19 and MODSEL pin 20. seem both connected to ground in most boards available on the market through merging traces. This is in conformity with the EGS002 datasheet.

That restricts the unmodded board to 50/60 Hz Operation and Unipolar switching

Modding for tests to enable VVVF to 100 Hz or to 400 Hz would require cutting the FREQSEL1 pin trace and patching the pin with maybe AWG30 hookup wires and connect it to HIGH level. MODSEL would be still kept to GND.

JP1 and JP5 would allow to control max frequency to 100Hz or 400Hz.

Note that variable frequency with constant voltage mode and variable frequency with variable voltage both require Unipolar switching. That is why you don’t have to bother with MODSEL in this mod

Once FREQSEL1 is set to HIGH, Variable frequency mode type is enabled through VVVF pin 32. In EGS002 again, it is connected to ground. This mode would give EGS002 the variable frequency constant voltage mode by default. (without further mods)

To enable VVVF variable freq/variable voltage (albeit with constant V/F ratio) for single phase VFD applications, bring VVVF to HIGH

Pin 32 VVVF. For variable frequency mode in unipolar switching

Again, the trace after the pin may be cut if other pins do not depend on the cut trace, which may be difficult to check since some trace may hide under the IC.

Note that there are several test points / open vias on the board that can be used to patch the board with additional connections.

Then you have to expose FRQADJ/VFB2 pin to set the desired frequency in variable frequency mode through an external potentiometer in figure 8.6a of the datasheet. Voltage regulation is still performed through R23 and VFB1

In constant voltage/frequency ratio mode, you use R23 to set the nominal voltage at 50Hz through VFB1 Frequency ratio control goes through FRQADJ/VFB2 in this mode. It is a bit unclear in the datasheet.

Bipolar SPWM enable modification

Remember that you cannot use VVVF features in this mode.

The mod would require :

  • cutting MODSEL pin 20 trace to disconnect from ground and patch it logic HIGH.
  • cutting FRQADJ/VFB2 pin 16 trace/pad to disconnect it from ground and use it to supply voltage feedback as shown in the EG8010 bipolar switching application schematic. In this mode VFB pin 13 and FRQADJ/VFB2 pin 16 are supplied a differential voltage feedback. It is required in bipolar switching. .

However, all boards found on the market seem to implement the application schematic “Figure 6‐2. EG8010+IR2110S+cross‐conduction prevention logic sinusoid inverter(unipolar modulation)”

The cross conduction prevention logic is inserted between the ASIC logic outputs and the Gate drivers logic inputs. It consists of resistors and BJTs

I think that would prevent the bipolar SPWM mode from working. So you need further modding.

  • You need to unsolder Q2 Q3 Q4 Q5 and solder bridge collector and emitter pads.
  • Remove resistors R30 to R37

Using the UART to set the operation modes

The ASIC also exposes an USART interface (RX pin 4 and TX pin 5)

The data inteface looks powerful, exposing all configuration options usually set by the jumpers. Whether the override of the jumpers is properly done by the USART remains to be seen.

Note than enabling bipolar SPWM would still require the removal of the cross conduction prevention components.

It also allows for monitoring the same parameters than in the LCD Output, that is frequency, current, temperature, and voltage.

The EGS002 has the RX pin to GND and the TX pin floating, Again cutting the trace to GND could allow to access to the USART. The data interface is fortunately documented in the datasheet. it uses 2400,8,N,1 serial settings.

Dead Time Control

EGS002 implement dead time control through solder bridges at the bottom layer of the board. These are JP3, JP4, JP7 and JP8.

The EG8010 has a fixed switching frequency of 23400 Hz that makes a pulse at 50% duty cycle time duration of roughly 21µs.

That makes the ratio of dead time to pulse length quite important at 1.0 and 1.5 µs, and may impact scaling up for higher output power. The default is 300µs. That is still quite conservative.

Check your MOSFET specifications for minimum dead time requirements.

Soft start

EGS002 has a soft start 3 second feature enabled by default through JP2. I do not recommend disabling this feature.

Voltage feedback & regulation.

It doesn’t look like there are any rectification on the voltage feedback network, nor on the EGS board or outside. and the RC filter made with R4 and C4 has a small time constant of 1ms. The voltage regulation uses a peak detector and measures error in relation to a 3V reference as per datasheet.

In any case the voltage nominal setpoint is performed through the lower leg of the voltage divider using R23 (a 10K potentiometer). A slow acting external voltage control could be done by replacing R23 with a current DAC.

Bipolar switching voltage regulation

You will see in the EG8010 datasheet that the voltage divider network is more complex (it is outside the ASIC board) than for unipolar, with a ganged potentiometer R23. I also suspect missing connection dots in the schematic between R19 and R21 and also R26 and R27 and also at R27 low leg and GND.I will test it on my LTSpice model, so take that info with a grain of salt. Here is the relevant section of the schematic with the proper corrections

bipolar switching voltage divider

Overcurrent protection.

The method employed is a hard current limiter. It cuts the SPWM input to all MOSFET drivers if the output current goes above the setpoint for more than 600ms. The unit is shutdown for 16s, then it will turn on for 100 ms, check for current status and repeat that 100ms on time every 16s if the issue persists for a maximum number of 5 cycles. if the issues persists it powers off and a hard reset is required. If the issue is cleared for more than 1 minute, the state machine resets overcurrent status to nominal.

The board also uses a LM393 OpAmp to process the IFB feedback to shutdown the Gate drivers directly through their SD pins, it is much faster and failsafe than doing this only through the ASIC.

There does not seem to be any soft limiter for light or moderate overcurrent protection (that would lower load voltage for resistive and inductive loads)

A soft limiter would not help for Active loads such as AC/DC PSUs because they change their apparent impedance to compensate for voltage loss.

Monitoring and UI

The monitoring is done through a LCD interface using I2C LCD compatible modules specified in the datasheet to display basic information. Or it can be done through the serial link if you expose the pins properly.

400V DC to 230V AC pure sine wave inverter model using LTSpice.

Ltspice inverter model

Note : the above model has been updated for frequency/phase synchronization. please check :

output voltage and current waveform, 80 ohms resistive load
Disclaimer : This design uses dangerous AC and DC voltages. If you get out of the simulation domain and start prototyping be sure to use all safety precautions required when working with high voltages. You have to know what you are doing.

Besides the simulation this post is an introduction on pure sine inverter technology targeted at electronics engineers that have little or moderate experience in power electronics and inverter design.

The goal is to design, implement and prototype your own pure sine wave inverter from scratch as an educational project to get into inverter technology, this will be the object of a series of posts in the future.

For a faster design approach see the bottom of this post on how to use off the shelf inverter modules such as EGS002 or EGS005 available on BangGood and AliExpress.

To get straight into the model simulation go to the running the simulation section.

Introduction

Inverters use MOSFETS to switch a DC source with a variable duty cycle PWM signal.

The duty cycle variation in the time domain is performed at the frequency of the required output fundamental frequency of the inverter.
Usually mains frequency, that is 50hz or 60hz.

The frequency of switching, that is the frequency of the PWM signal is called the switching frequency. it is usually in the 2.5khz to 100khz range.

So, the goal is to have a PWM signal at high frequency (2.5 khz to 100khz) with a variable duty cycle whose frequency is at mains frequency.

However, The variable duty cycle frequency may be lower or higher, or can be adjusted in real time.

Applications that require this duty cycle modulation at fixed but non standard 50Hz or 60hz are mainly for the aerospatial industry.

Airplanes use 400hz. The advantage of 400hz is that power transformers are less bulky than in 50Hz.

There is also an industry need to adjust the inverter output frequency in real time. This is the market segment of VFDs (Variable Frequency Drive) inverters.

This allows to set the rotation speed of induction motors, and allow for a soft-start that does not damage the motor.

In VFD applications, not only the the frequency output of the inverter is managed, but also the output voltage, and sometimes they implement a fixed voltage to frequency ratio mode so the motor stays happy.

So, now comes the question, How to modulate the duty cycle of a PWM signal ?

This is usually done by comparing a triangle signal at the switching frequency with a reference sinusoidal signal at the desired mains frequency.

This can be done in two ways :

1) Using analog components : a sine generator IC (like the XR-2206 or MAX038) that outputs a triangle wave and another one (also XR-2206 or MAX038) that outputs the sine wave. Then, a schmitt trigger is used to compare these two signals to output a PWM signal.

2) Using digital components : the sine modulated variable duty cycle PWM output is generated by code running on MCUs, PIC, DDS IC. Arduino can do this, however Arduino has a limitation that hinders its use for this purpose, and that is dead time control. More on this later.

If you nonetheless want to experiment with SPWM generation with an Arduino, check this code to get an idea of how it works.

I recommend you read resources on Fast PWM for Arduino. It is not straightforward if you have no experience with hardware counters/timers. Check https://www.arxterra.com/tutorial-on-fast-pulse-width-modulation/ and https://docs.arduino.cc/tutorials/generic/secrets-of-arduino-pwm
for starters. You may have to browser for other resources because I could not find one comprehensive documentation for ALL modes, except maybe in AtMel datasheets, but these are very terse and quite hard to understand.

Here is the first code sample :
#include <Arduino.h>

uint16_t freq = 50; // inverter output frequency
uint32_t counter = 0;
uint16_t mod_index = 0.9; // modulation index. you will have to update this in real time for precise voltage control.
float sin_val;
const uint16_t samples_per_period = 100; 
// higher samples per period give a better looking output sine wave, less harmonics from digital aliasing
uint16_t micros_interval;

uint16_t sin_table[samples_per_period];

void populate_sin_table() 
{

  uint16_t i;
  for(i=0;i<samples_per_period;i++)
  {
      sin_val = 512*(1 + mod_index*sin(2*PI*float(i)/samples_per_period));
      sin_table[i] = round(sin_val);
      //Serial.println(int(sin_val));
  }

}

// FAST PWM PHASE-CORRECT MODE 3

void setup(){ 
   
  // Wave Form Generator: phase correct PWM mode 3, Top = OCR1A and OCR1B
  // We will output two signals, complementary, using two pins ~9 and ~10 so we need to specify
  // (0<<COM1A0) + (1<<COM1A1) + (1<<COM1B0) + (1<<COM1B1)
  // (0<<CS10) + (1<<CS11) + (0<<CS12) this is the prescaler and will dictate the switching frequency.
  // (1<<WGM11) + (1<<WGM10); and (0<<WGM13) + (0<<WGM12) are used to set the Fast PWM mode, here we use mode 3.
  // it allows a 10 bit amplitude resolution for the sine wave signal
  // check this link for a table of available modes.



  TCCR1A = (0<<COM1A0) + (1<<COM1A1) + (1<<COM1B0) + (1<<COM1B1) + (1<<WGM11) + (1<<WGM10);
  TCCR1B = (0<<WGM13) + (0<<WGM12) + (0<<CS10) + (1<<CS11) + (0<<CS12); 
  
  OCR1A = 0x3FF; // top compare value initialization. it will be varied using the sine table in the loop.
  OCR1B = 0x3FF; // same for the second PWM signal
  
  //DDRB |= (1<<PB1);

  //Serial.begin(9600);
  populate_sin_table(); // create a sine table. better use PGM write and store it in flash for a more robust approach
  micros_interval = int(float(1E6)/(float(freq)*float(samples_per_period))); // the loop wait delay between two bit bangings
  // of OCR1A and OCR1B.

  //Serial.println(micros_interval);
  
} 



void loop() { 
 delayMicroseconds(micros_interval);
 OCR1A =  sin_table[counter%samples_per_period]; // iterate on the sine table, use modulo to loop the table
 OCR1B =  sin_table[counter%samples_per_period]; // same for the second SPWM
 
 //Serial.println(sin_table[counter%samples_per_period]);
 //Serial.flush();
 counter++; // overflow not managed !!!!!
} 

There is also this wonderful code https://forum.arduino.cc/t/dead-time-between-pwm-signals/937405 for a three phase system. I did not test it but it looks serious and legit. It has the advantage of using ISR and not a loop to update the TOP value with the sine wave, generates 6 signals (so it is for bipolar spwm) but it suffers from the same dead time insertion problem however, and that is the object of the guy’s post. But it is possible with analog post processing, check the DTI section.

That is why STM32 based boards are better for an all digital SPWM generation purpose, but they are more expensive and you'll need to watch quite a bunch of tutorials to master Nucleo (the STMicroelectronics MCU IDE). It will be easier if you already master Arduino FastPWM generation, but it will require time nevertheless.

Now is a good time to learn about the specifics on how that sine modulated variable duty cycle PWM signal allows the inverter to generate a 50hz, 60hz or higher frequency mains power phase voltage.

The "sine modulated variable duty cycle PWM signal" will be now referred by its usual name in the power electronics technology as SPWM (sine PWM)

The power core : the MOSFET H-bridge

The power core of an inverter uses an H-bridge configuration because the setup of its components ressembles to the letter H.
It is one of the most common designs in the industry.

MOSFETs switch repeateadly a DC source with low source impedance (the power source) according to the input gate signal that comes from the SPWM.

That is not all. high VDS high current MOSFETS usually need gate voltages that are higher than what an MCU or an analog oscillator can generate.
The high side MOSFET gates  of the H-bridge also need voltages with reference to DC ground that are way above the levels of the logic/analog controllers.

For that reason, there is a specific family of ICs that exists and they are called "MOSFET Gate Drivers". Their goal is to bridge the gap between the logic SPWM signals and the required voltage levels (and current requirements) of the MOSFET gates.

Moreover, an H-bridge inverter has at least 4 mosfets. These MOSFETS need to be activated by gate signals at a precise fashion, like a fine tuned choregraphy.

The activation pattern is usually diagonal in the schematics. This has the effect of reversing the polarity with reference to DC GND seen by the load with each pwm pulse. Since the two SPWM signals are complementary in this design, when one diagonal set of MOSFETs has a high duty cycle it will be on and conduct a longer time than the reciprocal diagonal set of MOSFET, when this happens the output sine wave of the inverter is at a +Vo_peak. Then there is a time when the duty cycle 0.5 for both diagonal pairs, at this point the sinusoidal output of the inverter crosses 0V. then the cycle goes in the reverse direction and outout reaches -Vo_peak.


PWM Modulation schemes

I just described one SPWM modulation scheme. There are two schemes that are most commonly used.

- Unipolar SPWM
- Bipolar SPWM

To understand the difference between the two, please read now :

https://www.sciencedirect.com/topics/engineering/sinusoidal-pulse-width-modulation
https://www.tntech.edu/engineering/pdf/cesr/ojo/asuri/Chapter2.pdf

My guide is based on Bipolar SPWM.

As you may already guessed, for that SPWM scheme you need two complementary SPWM signals.
For analog SPWM generation, the original SPWM signal generated from the triangle to sine comparator is fed to a NOT gate to create a complementary SPWM signal.

The original signal will drive the Top Left MOSFET and Bottom Right MOSFET
While the complementary signal will drive the Top Right MSOFET and Bottom Left MOSFET.

Note that in an unipolar SPWM scheme, The complementary SPWM signal stays low the whole time the other one operates, and then starts doing SPWM modulation while the other one stays quiet. This switching happens at 2*f_mains,
I find it harder to generate these two kinds of SPWM signals using digital means, so I think that the bipolar scheme is better to start grasping the technology.

Note also that IC Gate Drivers usually manage two MOSFET for a half bridge configuration. So we need Two gate driver ICs
In the LTSpice model IR2110 is used, as it is quite common in the industry.

The routing between the SPWM signals and gate drivers is as follows in my LTSPICE schematic and simulation :

SPWM signal is provided to HIN input of Gate Driver 1 and LIN of gate Driver 2
Whereas the complementary SPWM signal is provided to LIN input of gate driver 1 and HIN input of gate driver 2

HO output of gate driver 1 drives the top left M1 Mosfet
LO output of gate driver 1 drives the bottom left M2 Mosfet
HO output of gate driver 2 driver the top right M4 Mosfet
LO output of gate driver 2 drives the bottom right M3 Mosfet.

If you connect the dots, you'll see it fits the requirements of bipolar SPWM modulation scheme.

The big issue : dead time control.

There is a factor that needs extra precautions because it can fry the MOSFETs and brick the inverter. In no case, the M1 M2 MOSFETs should conduct at the same time.
This also true for M4 M3. If that would happen, The low impedance DC source will short through these MOSFETs (from Vdc to GND). When driven to high gate voltages, these Power MOSFETs  have a ridiculously low RdsOn, This will generate currents way above the absolute ratings of the MOSFET, frying them if a DC breaker or another protection from the upstream DC link did not catch it in time.

For this reason, a security margin between the two SPWM signals (the original and complementary) has to be put in place, This is a delay between pulses where both SPWM signals remain low. This is called dead time.

a good article to read on that subject :

https://hackaday.io/project/3176-gator-quad/log/11741-pwm-control-and-dead-time-insertion

For digital SPWM generation, forget about Arduino to get SPWM plus dead time control using Phase correct PWM out of the box.
Better PICs or MCUs are required such as STM32.

It is however possible to apply analog treatment to a single SPWM arduino generated signal, to create a complementary signal with a dead time delay inserted before the rising edge and after the falling edge.

In the supplied schematic, it is done through a RC network whose time constant is matched to introduce the required dead time, plus a bunch of gates and schmitt triggers. This setup may be simplified, if you manage to use less components or update the model to use real world components instead of ideal ones, let me know through the contact form.

Output Voltage control and regulation.

Output voltage control of the power stage is performed basically by varying the triangle peak voltage, while the sine voltage remains the same.

The peak output voltage is roughly given by 
Vo_peak = V(dc)*V(sine)/V(tri)
Vo_RMS is then V(dc)*(V(sine)/V(tri))/sqrt(2)
V(sine)/V(tri) is known as the modulation index (mi) 
it is usually < 1

If V(sine) gets larger than V(tri), the inverter operates in the overmodulating region, and RMS output voltage is no longer linearly dependent on V(dc)
It appears in the simulation as a voltage saturation of the output.

overmodulation is outside the scope of this guide but it is explained in the above mentioned resources.

An open loop control is not realistic because of deviations from theory that assumes ideal components, and dependance on the load RLC parameters and the output filter parameters, as well of the transformer if an isolated output is required. 

So there is a need for a voltage feedback loop to the SPWM generating component to adjust the modulation index.

Passing the voltage information to the source controller has to be done properly.

Because of voltage shifts of the (V(l) - V(n)) voltage relative to DC GND even after passing a voltage divider in this unisolated design, galvanic isolation is required, and this is a safety requirement.
If the output is isolated using a mains frequency transformer, galvanic isolation in the feedback loop is inevitable.

There are three methods to create an insulated voltage feedback loop.  

- Using an auxilliary winding in the secondary of a mains transformer.
With a turns ratio tuned for low output voltages, usually such as 3.3V/2 (rms) or 5V/2 (rms) is obtained when the inverter output voltage is at nominal conditions. That gives ample room for the signal to go higher if the output stage encounters an overvoltage situation. 
One leg would be connected to DC GND, the other fed to a full bridge rectifier, smoothed, and then that voltage would be fed to an error amplifier op-amp (a difference amplifier) that compares it to a precise voltage reference. This difference signal is a negative feedback that is then used to adjust the modulation index if using full analog generation. That would happen by controlling the AM pin of the XR-2206 Triangle generator, for instance.

If the SPWM is generated with digital means, the error amplifier could not even be required.
A DAC may be enough to acquire the voltage output of the optocoupler and the comparison of the DAC output would be done against a digital reference. Then, a digital control method should be implemented to control the feedback loop (such as PID) and update the modulation index.

I digress. Back to the feedback isolation.

- The other way of isolation is to use a separate low power transformer, with it's primary legs in parallel with the load. That is useful if your design does not use a transformer at all for the power stage, so you need only a transformer for feedback. Also, transformers with auxiliary windings are specific and you may have one on hand without that feature.
Of course it should be designed for 50Hz, or 60Hz, or more depending on your output frequency, with a ratio adjusted the same way as for an auxiliary winding.


- The third method involves a rectifier, a smoothing capacitor/filter stage, a voltage divider, which output drives a voltage controlled current source.
In this design I am trying a modified Howland current pump.
This current source is required because it will drive an optocoupler to transmit the analog information across the insulation barrier.
Optocouplers are current driven.

Care has to be taken to operate the optocoupler in its region where the CTR (current transfer ratio) is linear, by setting properly the current source gain.
Then one has to chose the proper collector resistor on the output side of the optocoupler to obtain proper transfer characteristics.

It is advised to test the transfer characteristics of the Current source + Optocoupler in a separate circuit to tune it up before adding it to the design, it will make things faster to simulate and way easier.

The rest of signal processing is the same as with the transformer approach.
Either digital control if SPWM is generated through a MCU or analog if using an oscillator. Analog will need a compensation network (usually a R+C // C) network for the feedback control loop to be stable.

Note : I have yet to model this part in the supplied model. It will be the object of this post revision in the future.

However, the fact that we are dealing with an inverter and that we have to perform rectification and smoothing to extract the peak voltage information, introduces feedback charateristics that are a bit different than DC/DC converter feedback loops.

Since the feedback loop would be designed with non-monolithic components (By that I mean the that the feedback loop does not use complex IC whose internals are a black box if their full transfer characteristics are not provided in the datasheet, and that perform mysteriously during AC analysis), it is possible to perform an AC open loop frequency response analysis of the rectifier + smoothing capacitor + current source + optocoupler quite easily.

Then add and tune a proper compensation network to obtain stability.

Check this guide for an introduction on compensation networks. It is targeted for SMPS power supplies, but the core concepts are the same, that is the need to model the open feedback loop at steady state, introduce a perturbation, and perform an AC analysis to get the frequency and phase response. (The bode plot)

https://www.ti.com/seclit/ml/slup340/slup340.pdf


The LC output filter.

A LC filter is a second order passive filter.
It's goal is to filter the high frequency switching pulses to obtain a pure sine wave with the least amount of harmonics.
In that design, I set the fc (corner frequency) at 10 times the mains frequency, that is 500Hz, not that the lower this frequency, the larger the L and C values, and the larger the effects on voltage with changing load impedannce.

You will notice also that the sine waveform THD will change with loading, appearing less distorted at higher loads

Finally, the LC output stage has an effect on output power factor. An inverter designed for inductive loads will be tuned differently in that regard.

Loading of the filter also affects its response and hence change the output voltage.

Check this thread for a discussion on inverter LC filters :

https://www.edaboard.com/threads/true-sinewave-inverter-output-lc-filter-design-help-needed.375327/

Running the simulation.

Download the zip file in the post introduction. Check the readme.txt in the zip for important information about LTspice setup for that model. Most of the important parameters are parametrized and explained
Most of the inverter functional blocks have commentaries that complement the information given here.
On a core i5 Elitebook 8440p, using LTspice under Wine on Linux, I get around 6.5us/s simulation speed. Try to get at least two or three output sine periods.
This is a work in progress, it will be updated as I improve the model.

A faster approach.

Fortunately, you don't have to reinvent the wheel if you have no time to learn all the intricacies of inverter technology, It is however always better to have an understanding of how all the inverter components work before using a board that implements some of the inverter functions in their design.

For this, there are inverter boards, and we'll have to turn to China and EGMICRO
EGMICRO is a supplier of ASIC inverter boards and more that take care of the SPWM thing, DTI, Gate driving, frequency settings, and voltage feedback, plus they have a monitoring output. They can be used for UPS inverters and also for VFD operation. They also have 3 phase boards.

For single phase designs, there are three ASIC demo boards sold on the market :
- EGS002 is an older but still popular demo board that features the EG8010 ASIC and two IR2110S gate drivers.
I used the same gate drivers in my LTSpice model.
- EGS005 is an newer demo board that features the EG8025 ASIC. It is a monolithic design with integrated gate drivers.

- EGS003 is a board available on the market, with a EG8011 ASIC, plus a single EG2126 package housing a full bridge Gate Driver. But It was since discontinued (the EGMicro website purged the documentation about EG8011) It may have been superseded by EGS005 or it may suffering from issues. Suppliers still sell it. The EG8011 ASIC datasheet still can be found elsewhere. I do not recommend that design if the ASIC supplier made it obsolete.

We will nevertheless perform some intel gathering on these three designs to see how they differ in their reported features.

For three phase designs, There is an EGSO31 board based on the EG8030 ASIC. It uses separate EG3012 gate drivers instead of the more ubiquitous IR2110. A three phase design is necessary for VFD designs powering 3 phase induction AC motors.

To get and idea of how these devices work, you need to check the Demo board, the ASIC and the Gate driver datasheet.
Some of the PDFs are available in simplified Chinese only, but you can pass it to Google translate and have a quite precise idea of what does what after sometimes a little guessing. The quality of Google's technical translations is quite good, since these are terse statements and not litterary works.

The goal is to look precisely at the application schematic and adapt it for our needs.

We will start by investigating the EGS002.

Check that GreatScott's video on EGS002 as an introduction, it also uses a demo UPS board (not just the ASIC+driver board)
 
https://www.youtube.com/watch?v=Dn2PFebi2ww

Please keep tuned for part II. Where we will discuss EGS002 in more detail to unveil its secrets.

230V DC redundant network with a renewable energy source and AC auxiliary power input.

The goal of this design is to get rid of :

  • The inverter stage of UPS or Grid tie inverter technology
  • The rectifier and PFC stage of PSUs

And make use of a renewable power source such as solar panel array

The core of the design is a DC/DC converter with MPPT, current sharing, battery management, It uses an auxiliary AC power input to allow for operation when solar panels do not provide enough power.

Such designs already exist, but they usually contain an inverter stage to output pure sine mains voltage AC.

The hard part of these designs, whether they contain an inverter stage or not at the output is the current sharing stage.
Finely controlled current sharing requires voltage control of all the input sources. However, the output DC/DC step up/down converter stage that conditions solar panel output is dictated by the MPPT algorithm. The solution then is to perform control of the voltage output of the mains AC/DC step up converter stage.

However, by doing so, the load impedance seen by the solar DC converter changes, and upsets the MPPT algorithm that will try to compensate for that change by upseting the DC output voltage.

The current sharing algorithm is non-trivial.

A solution for fast prototyping could use a digital control algorithm to control the voltage of the mains AC/DC converter through a DAC.

A simulink model for such a device is a requirement before attempting any practical device.

It is better if the core UPS also provides battery equalizing/balancing through individual battery/cell links.

Equalizing links to the battery bank are not shown in the schematic.

The UPS has to revert the operation of the converter for battery current draw instead of charge in case of mains failure to supplement solar panel output.

Fortunately, bi-directionnal switch mode converters designs and IC exist for that design. They allow the usage of the same switching transformer for both charge and discharge.

In a 230V DC design, It is also beneficial to have battery banks operating at a voltage close to the operating voltage of other buses, to allow for a switching transformer ratio close to 1:1

The device schematic shows a standard telco 48V battery bank.

The same goes for the solar panel array, it also has the beneficial effect of reducing ohmic losses and requirements for larger cable sections.

Thus the solar DC/DC converter has to be able to accomodate with various solar panel arrays configurations. For this reason a step up/step down design is preferred.

Failure scenarios

To avoid a single point of failure, the core converter is assisted by a standby unit powering up the standby PSU of load devices.

The standby device is not connected to the solar panel array in standard operation and provides power from AC mains utility. It is connected to the battery bank but does not perform charging in nominal operation conditions.

In case of interruption of AC power to the standby unit, it powers itself and provides power to the standby PSU (that draw a very limited amount of power) through the battery bank.

In case of interruption of AC power to both units, the standby unit will perform the same way. The active unit will provide power from the solar panel array with assist from the battery bank.

Switchover operation.

Whenever the active unit encounters a fault, it is reported to the switchover controller, that chooses whether or not to transfer the load to the standby unit by remote controlling the ATS, and also performs transfer of the solar panel array source to the standby unit, if the fault requires it.

ATS should also be able to operate automatically without switchover input (it is an ATS after all) and switch to the standby or active unit in case of DC power loss from either unit.

It is recommended to use a DC/DC SSR based ATS for this operation to reduce switching time and required output capacitance that allow for long hold times of the voltage on the PSU power bus.
High voltage / High capacitance capacitors banks are expensive.

Electromechanical relays also have a limited rated number of cycles before failure compared to SSR. Note that the SSR ATS has to be rated for 230V DC, which can be harder to source than a DPDT relay for the same ratings.

A custom MOSFET based design can be implemented with either low side or high side switching or both. low side switching is prefered because of lower RDSon for NMOS devices, or the use of a voltage pump for high-side NMOS switching. This design implement both high side and low side switching to completely isolate the the active and standby core DC UPS.

Failure of the ATS to switch to the standby unit will be compensated by the standby DC PSU providing the load to the device, standby DC PSU bypass the ATS in this design.

Note that a non recoverable failure will happen in case of switchback failure of the ATS to the primary unit, if the secondary unit fails to provide power to the load through the standby PSUs

ATS operation would sense voltage on the input buses, and initiate switchover / switchback if the DC voltage falls under a specified threshold, above the UVLO threshold of the load PSUs

The switchover controller should also be operated from a separate DC source with battery backup.

Earthing considerations

Note that the core converter units have their chassis connected to the main earthing bar, through the AC power cable since they have an utility AC input.

This design shows a TT earthing arrangement, but can be adapted to other earthing schemes.

DC outputs are isolated, and the whole DC bus is floating. Devices chassis and racks should be bound to earth.

Protective devices

Adequate DC overcurrent protection devices should be present on the DC bus before and after the ATS.

Battery banks should be protected by adequate fuses

AC mains supply employs SPD, RCD and OCD

Final note

Such a design is hindered by the relative novelty of monolithic MPPT/Auxilliary mains AC input/battery chargers without an inverter stage, and also the lack of 230V DC PSUs in the market.

Most DC PSU in the market are based on the old telco standard of using 48V, which is non-optimal for ohmic loss reduction, and require larger section cables.

The 48V voltage is also not on a comparable level to the high voltage outputs of modern solar panel designs, that connect panel modules in series for optimal and less costly power transmission from the array to the MPPT unit.

DC overcurrent protection is also more costly than the AC counterparts.

We believe however that this field will show new technology advancements in the following years.

Linux to Windows backup using Cygwin and Rsync

This procedure may be helpful for backups of Linux VMs on the cloud. Some (most) service providers make it notoriously difficult to export VM images or snapshots out of the cloud.

While it is still possible to perform an image backup using Clonezilla, again, not all service providers allow boot on an ISO for a given VM. In these cases, a helper volume should be added to the VM and have Clonezilla installed on it, and selected as the boot device. The original boot volume would then be backed-up to an image locally on the helper volume and exported out of the cloud after the process completes. Although that is the theory, I have not tested this specific process myself. Keep in mind that some providers VM instances only support one volume attached. Also, this process is a one-shot operation, and is hardly automated, and creates downtime.

There are other block level device time consistent backup strategies you can try though if you use LVM and have space on the LVM group, it is possible to snapshot your volume, mount the snapshot, and have rsync transfer it over the network. Keep in mind that if the rsync process is initiated on the backup system rather than on the backed-up system, you’ll better have to use ssh or other remote command tools to perform snapshot creation and mount and then rsync, have a way to check for errors returned by these commands and then only initate rsync on the backup system. Then perform a post-backup remote execution to unmount the snapshot and destroy the snapshot. This whole process is a bit similar to the Windows VSS snapshot operation.

For more information about this process, check :

LVM snapshot Backup and restore on linux

If you don’t use LVM then you’ll have to resort to backups that are not time consistent (not frozen in time), but it is better than nothing. That is the object of this tutorial.

Setting up cygwin on Windows.

Download cygsetup and perform a full or a minimal install. For a minimal install, you’ll need SSH and Rsync as well as it’s dependencies.

Now you’ll have to choose between using rsync through a SSH encrypted channel, or through a rsync daemon running on the remote host to be backed up.

Using rsync through SSH for a full system backup requires a root login through SSH, and automating rsync with SSH will require a way to supply credentials automatically, unless using a public/private key non interactive (passphrase less) authentication scheme.

In the case of SSH plain password authentication, supplying it to rsync can be done through sshpass, which exists as a Cygwin package, but I have not tested it myself in conjunction with rsync

http://www.cygwin.com/packages/summary/sshpass.html

https://stackoverflow.com/questions/3299951/how-to-pass-password-automatically-for-rsync-ssh-command

However, allowing SSH password root authentication plus storing its password as cleartext in a file for sshpass to use it is a huge security risk.

At least, with a passphrase less public/private key pair, the problem amounts to securing the private key well on the filesystem. It will still be acessible (read only) in the user account context that runs the rsync/ssh script on Windows.

For all these reasons, I find it preferable to use the rsync daemon on the remote system. Which allows to use a backup account instead of root.

The downsides however are that you need to open the rsync TCP port on the remote system and configure your firewalls in the connection path accordingly; and also rsync daemon does not encrypt traffic. If it is an issue, then use a VPN or an IpSec tunnel.

Setting up the rsync daemon on linux Debian

apt-get install rsync

Edit the rsync daemon configuration file.

vi /etc/rsyncd.conf

Here is a sample of the rsyncd.conf

uid=root
gid=root

[share_system_backup]
	path = /
	comment = system root
	read only = true
	auth users = backup
	secrets file = /etc/rsyncd.secrets
	hosts allow = <ip_of_backup_system>

As per the rsync manpage, rsyncd runs as root, and uid and gid parameters, which can be global to all rsync shares or share specific, specify the impersonated context of the rsync access to the filesystem.

Since we’ll perform a system wide backup, we’ll use root.

auth users specify the rsync users authorized to access the share. These users are rsync specific, not system users.

read only is used since no writes will be performed on the backed up system, unless you want rsync to upload some state file on the remote system after backup, as we won’t be using SSH, that is a trick way to signal something to the backed up system, without any remote execution.

hosts_allow is useful for a cloud VM that does not have firewalling options provided by the service provider.

The user login password pair is specified in /etc/rsyncd.secrets.

vi /etc/rsyncd.secrets

backup:346qsfsgSAzet

Use a strong password.

Next start the rsync daemon, check it runs and check its socket is listening on TCP port 873.

rsync --daemon

ps-auwx | grep rsync && netstat -nlp | grep rsync

Then we’ll make rsync launch at system boot.

vi /etc/default/rsync

Change RSYNC_ENABLE to true to start the daemon at system startup through init.d

Rsync configuration on Windows

We’ll start by setting up the windows batch files that will prepare the cygwin environment and run rsync. Change <IP> with your remote system to be backed up IP or DNS name. This script assumes standard port 873

The default file is named CWRSYNC.CMD and should reside at the root of the cygwin64 base folder.

@ECHO OFF
REM *****************************************************************
REM
REM CWRSYNC.CMD - Batch file template to start your rsync command (s).
REM
REM *****************************************************************

REM Make environment variable changes local to this batch file
SETLOCAL

REM Specify where to find rsync and related files
REM Default value is the directory of this batch file
SET CWRSYNCHOME=%~dp0

REM Create a home directory for .ssh 
IF NOT EXIST %CWRSYNCHOME%\home\%USERNAME%\.ssh MKDIR %CWRSYNCHOME%\home\%USERNAME%\.ssh

REM Make cwRsync home as a part of system PATH to find required DLLs
SET CWOLDPATH=%PATH%
SET PATH=%CWRSYNCHOME%\bin;%PATH%

REM Windows paths may contain a colon (:) as a part of drive designation and 
REM backslashes (example c:\, g:\). However, in rsync syntax, a colon in a 
REM path means searching for a remote host. Solution: use absolute path 'a la unix', 
REM replace backslashes (\) with slashes (/) and put -/cygdrive/- in front of the 
REM drive letter:
REM 
REM Example : C:\WORK\* --> /cygdrive/c/work/*
REM 
REM Example 1 - rsync recursively to a unix server with an openssh server :
REM
REM       rsync -r /cygdrive/c/work/ remotehost:/home/user/work/
REM
REM Example 2 - Local rsync recursively 
REM
REM       rsync -r /cygdrive/c/work/ /cygdrive/d/work/doc/
REM
REM Example 3 - rsync to an rsync server recursively :
REM    (Double colons?? YES!!)
REM
REM       rsync -r /cygdrive/c/doc/ remotehost::module/doc
REM
REM Rsync is a very powerful tool. Please look at documentation for other options. 
REM

REM ** CUSTOMIZE ** Enter your rsync command(s) here

echo "start" >> c:\scripts\rsync_sys.log
date /t >> c:\scripts\rsync_sys.log
time /t >> c:\scripts\rsync_sys.log

rsync --no-perms --itemize-changes --password-file=rsync_p -lrvcD --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found","/root/*"} backup@<IP>::share_system_backup/ /cygdrive/d/BACKUPS_FROM_CLOUD/SYSTEM >> c:\scripts\rsync_sys.log

date /t >> c:\scripts\rsync_sys.log
time /t >> c:\scripts\rsync_sys.log
echo "stop" >> c:\scripts\rsync_sys.log

You’ll need to add a file named rsync_p in my example that contains the password specified for the backup user, matching the password defined on the rsync daemon host. This allows non interactive execution of rsync.

Place this file at the cygwin64 base folder level.

Secure that file well at the NTFS level.

itemize-changes will log in the rsync_sys.log the file operations performed on the system. It is useful for troubleshooting.

http://www.staroceans.org/e-book/understanding-the-output-of-rsync-itemize-changes.html

The -lrvc flags tells rsync to copy symbolic link information (absolute and relative). You can test that is the case by using ls -ltra through a cygwin shell, recurse directories, be verbose, and check for changes based on checksum instead of file timestamps, which could be useful if there are timestamp discrepancies because of the cygwin environment. It is worth testing it’s effect with a test run.

Also, I excluded the standard list of directories recommended to be excluded from a system backup for Debian systems using the –exclude option.

Permissions / ACL issues

Note that I use –no-perms for rsync. That is one caveat with rsync running on cygwin, since it uses POSIX to Windows ACL translation, copying perms COULD render the files unreadable by other processes on the Windows system if permissions from the source system are preserved, On the other hand, preserving source permissions could make baremetal recovery possible. It is worth experimenting with this option.

A way to circumvent this problem when using –no-perms is to back up permissions separately on the linux system using getfacl and setfacl for restore operations. keep in mind that getfacl ouput is substantial in terms of size and getfacl does not support directory exclusions. It may involve a bit of scripting.

Example of getfacl script (backupacl.sh)

cd /home/backup
getfacl -RL /bin > filesystem_acls_bin.dat
getfacl -RL /boot > filesystem_acls_boot.dat
getfacl -RL /etc > filesystem_acls_etc.dat
getfacl -RL /home > filesystem_acls_home.dat
getfacl -RL /lib > filesystem_acls_lib.dat
getfacl -RL /lib64 > filesystem_acls_lib64.dat
getfacl -RL /media > filesystem_acls_media.dat
getfacl -RL /mnt > filesystem_acls_mnt.dat
getfacl -RL /opt > filesystem_acls_opt.dat
getfacl -L /root > filesystem_acls_root.dat
getfacl -RL /sbin > filesystem_acls_sbin.dat
getfacl -RL /snap > filesystem_acls_snap.dat
getfacl -RL /srv > filesystem_acls_srv.dat
getfacl -RL /tmp > filesystem_acls_tmp.dat
getfacl -RL /usr > filesystem_acls_usr.dat
getfacl -RL /var > filesystem_acls_var.dat

tar -czvf backup_acls.tar.gz filesystem_acls_*
rm -f filesystem_acls_*

You can use xargs and a $ placeholder plus a list of folders to backup permissions from to make this script a one-liner.

the backup_acls.tar.gz will be backed up by rsync when it runs.

In this example, ACL backups and the backup script are stored in /home/backup. As said before, backup is not necessarily a linux user since rsync maintains its own authentication database, but I use this directory for convenience.

In this script backup of /root ACLs is not recursive as a dirty way to remove the .wine directory that contains symbolic links to the whole file system, and thus would make getfacl to follow them and spend a huge useless time (and filespace) for directories such as /dev, /proc /sys. So it’s possible for you to add the recurse flag if this problem does not affect your system.

Run the batch for tests and schedule it by adding it to /etc/cron.daily/ for instance. It should run in the root context.

A note about restores and symbolic links

the rsync -l options copies symbolic links, which means thar you have to use rsync too for restore operations, Don’t expect symbolic links to magically reappear if you use WinSCP or another tool to restore a folder.

More on this subject :

https://www.baeldung.com/linux/rsync-copy-symlinks

Testing the backup.

Edit the cwrsync.cmd to add the dry-run option, run the cwrsync.cmd through a cmd shell and examine the rsync_sys.log file, If everything seems OK, then you can remove the dry-run option, and run it again. The first run will take a long time, use the start and stop markers in the logfile to check how long it takes once finished. rsync will tell you the speedup due to the delta algorithm, it should increase on subsequent runs.

Scheduling the backup.

Use Windows task scheduler to run the cwrsync.cmd script. In my case, I use a privileged account. It is advised to test with the least amount of privileges for cygwin to be happy and for filesystem operations to succeed.

It is advised the turn on scheduled tasks history. And very important, make sure that the “start in” directory for the cwrsync.cmd action is set to the base cygwin64 folder.

Test the backup run using a “run once” trigger at t+1 minute in addition to the recurrent trigger.

A final note.

This backup strategy will ensure that you have an updated state of your remote system on the Windows system. It is similar to an incremental backup that patches the destination directory. It does not store any history of files besides the last backup operation.

I don’t use the –delete option that propagates deletions of files and folders from the source to the destination, has it can be very impactful for a disaster recovery use where there is no file versioning history. Note however, that this will bloat the backed up structure on the destination and make recovery efforts more complicated in the long term.

The best option for a backup if you use LVM, albeit using more space on the destination is to use cygwin + rsync to backup a tar gz file of a LVM snapshot directory structure instead of the directory tree of “/”. If you go this way though, it is advised, as already stated above, to perform the snapshot operations synchronously from the backup system through the cwrsync.cmd using SSH, before the rsync operations. That probably means using a passphrase less public/private key pair for ssh to run these commands interactively. Don’t forget to unmount and remove the snapshot after rsync is done.