Introduction: Grid Tie Inverter

About: Did Physics for my undergraduate, absolutely love building things particularly electronics projects

This is a meaty project so buckle up!

Grid tie inverters enable you to push power into a mains socket which is an awesome ability. I find the power electronics and control systems involved in their design interesting so I built my own. This report shares what I learnt and documents how I did things. I’d be interested in any comments you had (apart from the ones about not messing with mains electricity).

All the concepts are scalable but this setup had a maximum output of 40 watts before the filter inductors began saturating. The output current was sinusoidal with THD < 5%.

See the software on my GitHub

Supplies

  • I used the STM32F407 development board. It runs at 168MHz and has 3 built-in ADCs capable of 12bit resolution at over 2.4MSPS (Million Samples Per Second) each. That’s insane!
  • I used the DRV8301 development board. This houses a 60v H-Bridge along with the necessary gate drivers, current shunts and current shunt amplifiers. Super nice!
  • I used a 230-25v toroidal transformer with 2 output taps. This meant I didn’t have to directly produce mains voltage but could work with peak voltages of 40 volts instead. Much safer!
  • I connected a load of inductors and capacitors together to get the L and C values I wanted for the filter.
  • An oscilloscope and differential probe is key for a project like this. I have a Picoscope

Step 1: What Is Mains Power?

What you get at a power outlet (in the UK) is a 50Hz 230v RMS sinusoidal signal with a very low impedance. A few things to say about that:

50Hz - Mains frequency is very precisely maintained at 50Hz. It does vary slightly but 90% of the time it’s between 49.9-50.1Hz. See here. You can imagine all the enormous generators in power stations up and down the country spinning in unison. They rotate synchronously producing for us a 50Hz sinusoidal signal. Their combined massive rotational inertia takes time to slow down or speed up.

In theory, if a HUGE load was attached to the grid it’d begin to slow down the country's generators. However, in response, the guys in the National Grid’s control office would request power stations to stoke their boilers, crank up the heat and force those generators harder to keep up with the demand. Thus supply and demand are in a continuous dance with one another.

One more thing to say about the 50Hz signal. Although it varies very slightly about 50Hz, the guys up top make sure that the average frequency over the day is exactly 50Hz. So if the grid is at 49.95Hz for 10 minutes, they’ll ensure it runs at 50.05Hz later to bring the exact number of cycles to 50Hz x 60seconds x 60minutes x 24hours = 4,320,000/day. They do this precisely using International Atomic Time. Household, office and industrial appliances can therefore use the grid frequency to keep time. This is commonly done with mechanical socket timers for example.

230v - This is the RMS (Root Mean Square) voltage of the 50Hz signal. The actual signal swings up to a 325v peak. This is important to know because if you’re building an inverter you need to produce voltages this high if you are going to get any current to flow into the plugs.

In reality, the voltages seen at a plug in your house are quite variable. That’s due to voltage drop across the resistance in wires, connectors, fuses, transformers etc. There’s resistance everywhere. If you turn on an electric shower pulling 11 kilowatts (that’s ~50Amps) then even 0.2ohms of resistance is going to drop you 10volts. You may see this as the lights dimming ever so slightly. Big motors, such as those in hoovers draw huge currents whilst the motor gets up to speed. So you often see a slight flicker of the lights when you turn them on.

My point is, mains voltage is much more variable. Here in the UK it’s supposed to be 230v with a +10%/-6% tolerance. You can expect to see sudden changes and fluctuations as large loads nearby turn on/off. Think tumble driers, kettles, ovens, hoovers etc.

Sinusoidal - The signal should be a nice clean sine wave but in reality some non-linear appliances suck their power from certain points in the sine wave cycle. This introduces distortion and that’s why the signal is not a perfect sine wave. Non linear loads typically include computer power supplies, fluorescent lights, chargers, TVs, etc.

Total harmonic distortion (THD) quantifies this in the waveform. There are regulations for how clean an inverter’s output has to be. If it’s unable to produce a clean enough signal then it won’t be approved for sale. This is important because harmonic content in the grid reduces the efficiency of some devices connected to it (especially odd harmonics). I believe the max allowable THD is 8%

Low impedance - When thinking about a grid tie inverter this will be important to consider. There are all sorts of loads attached to the mains including inductive, resistive and occasionally capacitive loads. So the impedance is unknown and changeable. The resistance is very small meaning if you connect a high current load, the voltage won’t drop much at all.

Step 2: How to Push Power Into the Grid

To push power into the grid we need to synthesise a signal that exactly matches the frequency and phase of the mains but with a voltage ever so slightly higher.

Because of the grid’s low resistance it’s difficult to know exactly how much higher to make that voltage. And as the RMS voltage fluctuates we need to ensure we fluctuate with it. Just producing a fixed 50Hz voltage signal slightly higher than the mains voltage isn’t going to work!

PI Control of the output current

What we need is a control loop whereby we measure the instantaneous current we’re pushing into the grid and automatically adjust our output voltage to drive the current we want. This will effectively transform our output into a current source (rather than a voltage source) which is more appropriate for driving low impedances. We can achieve this by using a PI (Proportional Integral) control loop:

PI control loops are fantastic! There are 3 parts to them:

  • The measured value - The current we’re putting into the mains
  • The setpoint - The current we want to be pushing into the mains
  • The output - The signal voltage to generate

Each time we call the PID algorithm, we pass the most recent current measurement and the setpoint we want. It’ll return an arbitrary number (proportional to the output voltage to generate).

Our PID control algorithm allows us to choose the output current we want at any given moment. To produce a 50Hz sinusoidal output current we need to continuously change our requested current in a sinusoidal fashion.

The PID algorithm is called every 100us (equating to 200 times per 50Hz cycle). Each time it is called it is able to make direct adjustments to the output voltage and hence indirectly adjust the output current. As a result we produce a stepped current output similar to that shown in the picture with each step occurring every 100us. That provides enough resolution.

Feedforward control

We can massively reduce the workload of the PI controller by adding a feedforward controller as well. This is easy! We know the approximate output voltage we’ll need to generate (same as the instantaneous grid voltage). The PI controller can then be left to add the tiny extra voltage needed to drive an output current.

By itself the feedforward controller matches the inverter’s output voltage to the grid’s voltage. No current should flow if we match well enough. The feedforward control is therefore doing 99% of the output control.

Due to the grid’s low resistance, any difference in our FF output voltage and the grid voltage would result in a large current. I therefore added a 1ohm buffer resistance between the inverter and the grid. This does introduce losses, but they’re quite small in the grand scheme.

Step 3: Producing the Output Voltage Using PWM

Although we are indirectly controlling the output current, it is an output voltage that we are generating at any given moment. We use PWM (Pulse Width Modulation) to produce our output voltage. PWM signals can easily be produced by microcontrollers and they can be amplified using an H-Bridge. They’re simple waveforms characterised by 2 parameters, the frequency F, and the duty cycle D.

A PWM waveform switches between 2 voltages, in our case 0v and Vsupply

  • With D = 1.0 the PWM waveform is simply DC at Vsupply
  • With D = 0.5, we get a square wave with an average voltage of 0.5 x Vsupply, (ie D x Vsupply)
  • With D = 0.1, we get a pulsed waveform with a period average of 0.1 x Vsupply
  • With D = 0.0, the output is a flatline (DC at 0v)

The average voltage is what’s key. With a low-pass filter we can remove everything but the DC average component. So by varying the PWM duty cycle D, we are able to make any DC voltage desired. Sweet!

Employing an H-Bridge

An H-Bridge is made up of 4 switching elements. These can be BJTs, MOSFETs or IGBTs. To produce the first half (0 - 180 degrees) of the sine wave, we set phase B low by turning Q3 off and Q4 on (ie. applying PWM with D = 0). We then perform our PWMing on phase A. For the second half, where VAB is negative we set Phase A low and apply our PWM to phase B. This is known as bipolar switching.

The MOSFETs in the H-bridge must be driven by a gate driver. This is a topic of its own but a simple chip can take care of it. The DRV8301 dev board conveniently houses the H-Bridge, gate drivers and current shunts for us making this project a hell of a lot easier.

Step 4: Measuring Current

Each leg of the H-Bridge has a shunt resistor and a differential amplifier. Our shunts are 0.01ohms and our amplifiers are set for a gain of 40. Hence 1 Amp develops 10mV across the shunt which is subsequently amplified to 400mV.

The outputs from the shunt amplifiers are read by the 12bit ADCs on the STM32F407 running in continuous conversion mode. The ADCs are set to sample each shunt at 110KSPS and the DMA controller automatically writes the conversions into an 11 word circular buffer in RAM. When a current measurement is wanted we call a function which returns the median value of this 11 word buffer.

Since we’re requesting current measurements every PID iteration (at 10KHz) but filling our 11 word ADC buffers at a rate of 110KHz, we should get completely fresh data each PID iteration. The reason for using a median filter, is because PWM switching can introduce spikes into the mix and median filters eradicate spurious ADC samples very effectively.

An important point to make here: Which leg of the H-Bridge do we use for current measurements? Well it depends on which leg we’re currently PWMing and which is just held low. The leg held low is the one we want to measure our current from since current is always flowing through the shunt resistor on that side. In comparison, on the side being PWMed, when the high-side MOSFET is on and the low-side is off no current is flowing through the low-side shunt. So, we change which leg we measure current on based on the output polarity of the inverter. You can see this clearly in the picture, showing the output from one of the shunt amplifiers over a period. Obviously we want to take readings during the smooth bit.

To help debug our current readings. I set up the Digital-to-analogue converter on the STM32F407. I wrote the current readings I was getting and scoped the output. You can see this in the final image, the blue is the voltage across the output buffer resistor (ie. the output current/1.1ohms) and the red signal is our DAC output.

Step 5: Filtering the Output

The output filter is a key part to the design. We need these characteristics from it:

  1. Block all high frequency switching but pass a 50Hz signal
  2. Low losses
  3. Not to resonate!
  4. To cope with the currents and voltages involved

The fourier transform of a PWM signal of frequency F, Duty cycle D, between 0 - Vsupply volts is:
(D x Vsupply) + Sine waves at the fundamental frequency F, and harmonics thereafter

This is brilliant! It means if we put our PWM signal through a low pass filter which blocks the PWM fundamental and everything above. We’re just left with the DC voltage term. By varying the duty cycle we can easily produce any voltage we want between 0 - Vsupply as explained.

Based on the desired characteristics mentioned above we can design the output filter. We need a low pass filter made with minimal resistance to avoid losses. Hence we just use inductors and capacitors. If we choose a resonant frequency between 1 - 2KHz we will avoid resonance since we’re not injecting any signals near that frequency. Here’s our filter design. We take our output as the voltage across C1.

By choosing L1 = L2 = 440uH, C1 = 8.4uF we calculate a resonant frequency of 1.85KHz. These are realistic component values too.

It’s vital to ensure our inductors don’t start saturating at the currents we’re expecting. The inductors I’ve used have a 3A saturation current. This will be the limiting factor on our circuit’s output power. The capacitor voltage rating is also important to consider. I’m using some 450v ceramics which is very overkill in this case!

The bode plot (for slightly different L/C values) has been generated using LTspice. It shows us the attenuation inflicted on different input frequencies. We can clearly see the resonant frequency at 1.8KHz. It shows that a 50Hz signal is almost entirely unadulterated whereas I can tell you a 45 KHz signal is attenuated by 54dB!

So let’s choose our PWM carrier frequency to be ~45KHz. By choosing higher PWM carrier frequencies, the filter frequency can be made higher. That’s good because it makes the L and C values smaller. That means smaller and cheaper components. The downside is, higher PWM switching frequencies introduces greater losses in the transistor switches.

Step 6: Synchronising Phase and Frequency

Synchronising to the mains phase and frequency is what makes a grid tie inverter. We use a digital implementation of a PLL (Phase Locked Loop) to achieve accurate phase tracking of the mains signal. We do this by:

  1. Sampling the mains voltage
  2. Producing a local 50Hz sinusoidal signal of our own
  3. Comparing the phase between our local signal and the mains signal
  4. Adjusting the frequency of the local signal until the phase difference between the 2 signals is zero

1) Sampling the mains voltage

We configure a 3rd ADC channel to read the line voltage. This we get by voltage dividing a transformer tap as shown. This provides a scaled voltage varying about 1.65v that exactly represents the grid voltage.

2) Producing a local 50Hz sinusoidal signal
Producing our own local 50Hz sine wave is easy. We store a lookup table of 256 sine values. Our simulated sine value is easily obtained using a lookup index that rotates incrementally through the table.

We must increment our index at exactly the right rate in order to get a 50Hz signal. Namely 256 x 50Hz = 12,800/s. We do this by using timer9 clocked at 168MHz. By waiting 168MHz/12800 = 13125 clock ticks we’ll step our index at the right rate.

3) Comparing the phase between our local signal and the mains signal
This is the cool part! If you integrate the product of cos(wt) x sin(wt) over 1 period the result is zero. If the phase difference is anything other than 90 degrees you get a nonzero number. Mathematically:

Integral[Asin(t) x Bsin(t + φ)] = Ccos(φ)

This is great! It allows us to compare the mains signal, sin(ωt) with our local signal, sin(⍵t + φ) and get a value.

There is however an issue that needs to be addressed: If we want to have our signals to remain in phase we need to adjust our local frequency to keep the Ccos(φ) term maximal. This won’t work very well and we’ll get poor phase tracking. This is because the d/dφ of ɑcos(φ) is 0 at φ = 0. This means the Ccos(φ) term won’t vary very much with changes in phase. Does that make sense?

It’d be far better to phase shift the sampled mains signal by 90 degrees so that it becomes cos(ωt + φ). Then we have this:

Integral[Asin(t) Bcos(t + φ)] = Csin(φ)

Introducing a 90 degree phase shift is easy, we just insert our mains ADC voltage samples into one end of a buffer and take them out a number of samples later, corresponding to a phase shift of 90 degrees. Since the grid frequency hardly varies from 50Hz a simple time delay technique works brilliantly.

We now multiply our 90 degree phase shifted mains signal with our local signal and keep a running integral of the product over the last period (ie. over the last 256 values).

The result we know will be zero if the 2 signals are precisely maintained 90 degrees apart. This is fantastic because it undoes the phase shift we just applied to the mains signal. Just to clarify, instead of maximising the integral term we are attempting to keep it zero and we are phase shifting our mains signal. The 90 degree phase shifts introduced by these 2 changes cancel each other out.

So If Integral_Result < 0 we know we must increase our local oscillator frequency to bring it back in phase with the mains, and vice versa.

4) Adjusting the frequency of the local signal
This bit is easy. We simply adjust the period between incrementing through our index. We constrain how fast we can correct the phase difference essentially filtering out spurious whatevers. We do this using a PI controller with a very small I term.

And that’s it. We’ve locked our local sine wave oscillator (which sets the output current setpoint) to be in phase with the mains voltage. We’ve implemented a PLL algorithm and it works like a dream!

Increasing the frequency of our local oscillator also reduces the phase shift put on the mains signal. Since we’re constraining the frequency adjustment to +/-131 ticks (+/- ~1%) we’ll affect the phase shift by +/- 1° at most. This isn’t going to matter at all whilst the phases synchronise.

Theoretically if the mains frequency deviated by more than 0.5Hz we’d lose our phase lock. This is because of our above constraint on how much we can adjust our local oscillator frequency. However that isn’t going to happen unless the grid is about to fail. Our anti-islanding protection will kick in at this point anyway.

We do perform a zero crossing detection at start up to try our best at starting the signals inphase from the offset.

Step 7: Anti-islanding

Wikipedia has an awesome article all about islanding and anti-islanding techniques. It also implies that people hiss and flap more than necessary when it comes to this topic. “Oh, you can’t build your own grid tie inverter, you will kill someone etc etc.”

As explained better by the wikipedia article we employ a couple of safety precautions that together provide adequate protection (in my opinion):

  1. Under/Over voltage
  2. Under/Over frequency

We can detect these situations by simply analysing our sampled scaled mains voltage. If anything goes out of whack, disable the H-bridge and await for things to return to normal.

Check out the figure above, you can see once the grid collapses we stop producing our output in about 80ms.

Step 8: Testing

I tuned the PID parameters to get a good control response. The images above show the output with the blue trace representing the grid voltage and the red our output current. You can see on close inspection that there is a small phase shift between the output current and voltage. This is a result of our PI controller having some lag.

It’s hard to measure the efficiency but when pumping out 38 watts the H-Bridge only felt warm. The transformer is lossy, you can see in the IR image that it was 35 degrees with it just connected to the mains and doing nothing! I measured a 85% conversion efficiency of the inverter when outputting 38 watts not including the transformer losses.

Step 9: What’s Next? What Can Be Improved?

Next I want to build 250w transformerless system! We’ll neaten up the horrible mess that was this prototype and build something more rugged.

The limiting factor on the output power is caused by the low saturation current of the filter inductors. I suppose we have a few choices:

  • Choose bigger inductors with higher saturation currents
  • Increase our filter frequency and possibly PWM carrier frequency
  • Use higher voltages and lower currents

The last 2 points here are the way to go. I used a transformer to step up the output voltage as a last step. This meant our filter was dealing with low voltages ~25v RMS and high-ish currents ~2Amps. This limits our power to about 40w.

Higher voltages are better. Our capacitors are rated for up to 450v. If we directly produced mains voltage of 230v RMS we could still use the same inductors and get nearly 500w output power. This is how most commercial inverters do it. They avoid output transformers altogether to save bulk and expense.

Using higher voltages necessitates H-bridge transistors with appropriate voltage ratings too. At low voltages, MOSFETs win by having a lower VDS when conducting. At higher voltages (450 or 600v) IGBTs start to come into their own. It’s also important to ensure the gate drivers can function at high switching voltages and to take care over properly isolating everything too. But other than that not much else changes.

Not having an output transformer introduces the issue of DC current injection. If our circuit’s output current doesn’t quite swing symmetrically then we’re pushing a small DC component into the grid. That’s bad since DC currents wreck havoc on motor efficiency and transformers etc. A non symmetrical current swing could occur if there is any offset in our current shunt amplifiers. We perform a self calibration routine at startup to measure the offsets with no current flowing. This allows the error to be compensated for. It’s possible to suppress DC current injection but not eradicate it entirely.

I think we have also been overly conservative when it comes to the filter. We could probably get away with a filter frequency more like 3-4khz which would allow for smaller inductors or ones with greater saturation currents. LCL filters are more commonly used on commercial GTIs. I believe they offer better performance but complicate the design a bit more.

This project was very much an intro into the topic. I hope it provided some insight. There is so much more to GTIs and the control systems that run in software. Proportional Resonant controllers for example. I've linked some research papers. I shall be back in a month or so hopefully with an improved implementation.

PhD Project of a grid tie inverter being designed and built - 24v into a 230v grid

Step 10:

First Time Author Contest

Participated in the
First Time Author Contest