//Reading in analog voltages from sensors can be quit noisy. Thats why you may want to filter your
//signal before processing it. The easiest way to do so is by using a simple RC-Lowpass-Filter.
//Only downside: Changing the filter-characteristic afterwards is not easy. Here I want to show you how
//you can use digital filters to clean up your signals. Its a simple way to get into digital signal processing.
//I highly recommend this Video on YouTube: https://youtu.be/HJ-C4Incgpw?si=5qnccmFfe0ztaFDK by Curio Res
float fc = 0.1; //Define the cut-off-frequency in Hz
float fn = 100.0; //Define the sampling-frequency of the Uno in Hz(1)
float wc = fc*2*3.14; //Calculate the angular cutoff frequency
float T = 1/fn; //Calculate the sampling time
float x[] = {0,0}; //Here the current- and the previous-input value is saved
float y[] = {0,0}; //Here the current- and the previous-output is saved
float a1 = -(1-(2/(T*wc)))/(1+(2/(T*wc))); //calculate all the coefficients (2)
float b1 = 1/(1+(2/(T*wc)));
float b0 = b1;
void setup() {
Serial.begin(115200); //start the serial communication
//Serial.println(a1);
//Serial.println(b1);
//Serial.println(b0);
//delay(2000);
}
void loop() {
x[0] = analogRead(A0)+random(-50,50); //read in the analog signal and add some random noise as an example
y[0] = b0*x[0] + b1*x[1] + a1*y[1]; //this formula calculates the current output value by given previous output, the previous input and the current input
delay(T*1000.0); //wait for T seconds
x[1] = x[0]; //set the current in- and output values the previous values
y[1] = y[0];
Serial.println(y[0]); //print out the filtered signal, use the serial plotter down right
//Serial.println(x[0]); //uncomment to see the unfiltered signal
}
//(1) - The sampling-frequnecy depends on the time it takes the Arduino the run through the loop().
// We use a delay() to make sure the sampling-frequncy is about right. In reality it is lower.
//(2) - For first order Butterworth-Lowpass-Filter calculating the coefficients can be done with the
// given Formulas. If you want to use higher order filters the formulas get quite large.