Demo 43: How to apply Kalman Filter to ESP to make sensor measurement more accurate - IoT Sharing

## Saturday, June 15, 2019

1. Introduction
Kalman filtering is an algorithm that uses a series of measurements (including statistical noise and other inaccuracies) observed over time to make estimates of unknown variables more accurate than just use a single measurement.
Figure: Blue line is sensor data from ADC with noise and Brown line is sensor data after applying Kalman Filter
In order to understand more about the equations and calculations, please refer this.
This post will make a simple demo of applying Kalman Filter to ESP to make sensor measurement from a LDR (Light Dependent Resistor) more accurate.
Figure: LDR sensor
Figure: ESP32 module
2. Hardware
ESP32 3.3V connect LDR Vcc
ESP32 GND connect LDR GND
ESP32 G34(ADC pin) connect LDR A0
3. Software
I will use the Kalman Filter here (download as zip file). The calculation of this library is similar to the reference.
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38``` ```#include //the ADC pin of esp32 #define ADC_PIN 34 // update Serial Ploter every 100ms #define UPDATE_TIME 100 long current; //init Kalman with params, you can modify params to make better result SimpleKalmanFilter kalman(2, 2, 0.01); void setup() { Serial.begin(115200); Serial.print(0); // To freeze the lower limit Serial.print(" "); Serial.print(3.3); // To freeze the upper limit Serial.print(" "); } void loop() { //to make demo interesting we add random noise to measurement float rand_noise = random(-100,100)/100.0; // Reading LDR value, ADC of esp32 0-4095 according to 0-3.3V float measured_value = analogRead(ADC_PIN)/4095.0 * 3.3 + rand_noise; //Kalman update estimate float estimated_value = kalman.updateEstimate(measured_value); //update plotter if (millis() > current) { Serial.print(measured_value); Serial.print(","); Serial.print(estimated_value); Serial.println(); current = millis() + UPDATE_TIME; } } ```