# Removing Noise : The Versatile Complementary Filter

After playing around with DC electronics for almost a year now, I thought it was finally time to start mucking about in the world of Alternating Current. To begin, I decided to experiment with the ACS712 Current Sensor.

This current sensing module uses the Hall Effect to sense current flowing through its terminals and provides a DC voltage output between 0 to 5 V depending on the magnitude and direction of the current flow across its terminals.

In my project, I use two ACS712 sensors (one 5A version and one 20A version) to try and sense AC current flowing through a load such as refrigerator/ water heater/ home theatre etc etc. The idea was to be able to record and analyse how our household appliances consume electricity, how much vampire power we haemorrhage, and finally use this data  to design an efficient solar station that could power our needs.

The basic layout of my project is shown below:-

As part of my early experiments with this setup, I connected the output of the 5A version of the ACS712 sensor to my oscilloscope. As you can see from the picture below, the output voltage had plenty of noise superimposed on it. As a first step, I soldered a 100 nF capacitor directly across C2 to suppress some of the noise.

For the next layer of noise reduction, I used a Complementary Filter. I had earlier used this filter to smooth data coming from an MPU6050 accelerometer/gyroscope.  The formula I used this time is:-

Current Now = alpha * Current Now + (1 – alpha) * Last Current Reading

alpha is a constant and must be between 0 and 1. Its value determines the degree of smoothing to be applied to the incoming data. Its easy to see from the formula that an alpha value close to 1 means very little smoothing is applied.

To test out the validity of this filter, I wrote some simple Octave code and ran a few simulations with various values for alpha. For those who don’t know, Octave is very similar to MATLAB but doesn’t cost a ton of money to download and use.

```
clear all
figure(1);close;
waveAmp = 7; % amplitude of sinusoidal signal
noiseSD = 5; % standard deviation of noise
%generate a signal.........
base = ones(200,1) * 512;
theta = (linspace(0, 4*pi, 200))';
wave = waveAmp .* sin(theta) + base;
%generate and superimpose random noise
noise = randn(200,1);
noise = noise .* noiseSD;
inputSig = wave + noise;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%remove the noise with a complementary filter
outSig = zeros(200,1);
alpha = 0.2; %filter coefficient alpha = 0.2
outSig(1) = inputSig(1);
for i=2:size(outSig,1)
outSig(i) = alpha * inputSig(i) + (1-alpha) * outSig(i-1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

hold on;
plot(theta, inputSig, 'r');
plot(theta, wave, 'b-');
plot(theta, outSig,'k-');
axis([0 14 495 530]);
title('Noise Removal with Complementary Filter');
legend('Noisy Input','True Signal','Filter Output');