Try It: Kalman Filter Tuning in Wokwi

Try It: Kalman Filter Tuning in Wokwi

animation
sensors

Try It: Kalman Filter Tuning in Wokwi

Change the noise settings and watch the tradeoff between a smooth trace and a quick response. Compare each result with the raw reading.

Tip

Run this ESP32 sketch in Wokwi. It generates a synthetic noisy temperature rather than reading a sensor. Adjust Q and R, then change the step in the code to compare smoothing with response time.

What to try:

  • Start the simulation and observe the raw vs filtered temperature readings.
  • Increase R in SimpleKalman kf(0.1, 1.0) to 2.0 → Watch the output become smoother but slower to respond.
  • Decrease R to 0.1 → Output tracks faster but is noisier.
  • Try Q = 0.5, R = 0.1 for fast tracking (good for rapidly changing signals).
  • Try Q = 0.01, R = 1.0 for slow averaging (good for stable measurements).

Open Wokwi ESP32 Simulator

Starter code for Kalman filter on ESP32:

// Kalman filter for noisy sensor smoothing
// Try changing Q and R to see different behaviors!

class SimpleKalman {
public:
  float q;  // Process noise - increase for faster response
  float r;  // Measurement noise - increase for smoother output
  float x;  // State estimate
  float p;  // Estimate uncertainty

  SimpleKalman(float q_val = 0.1, float r_val = 1.0) {
    q = q_val;
    r = r_val;
    x = 0;
    p = 1;
  }

  float update(float measurement) {
    // Predict
    p = p + q;

    // Update
    float k = p / (p + r);  // Kalman gain
    x = x + k * (measurement - x);
    p = (1 - k) * p;

    return x;
  }
};

// Create filter with tunable parameters
SimpleKalman kf(0.1, 1.0);  // Try: (0.5, 0.1) or (0.01, 2.0)

void setup() {
  Serial.begin(115200);
}

unsigned long sampleCount = 0;
const float stepC = 5.0; // Change this to set the temperature step.

void loop() {
  // Step after 100 samples, then add synthetic noise.
  float trueTemp = 25.0 + (sampleCount >= 100 ? stepC : 0.0);
  sampleCount++;
  float noisyTemp = trueTemp + random(-100, 100) / 50.0;

  // Apply Kalman filter
  float smoothTemp = kf.update(noisyTemp);

  // Print both for comparison
  Serial.print("Raw: ");
  Serial.print(noisyTemp);
  Serial.print(" | Filtered: ");
  Serial.println(smoothTemp);

  delay(100);
}

Observation guide:

Start by with R=1.0: Filtered values change slowly, lag behind sudden changes. Then with R=0.1: Filtered values track quickly but show more noise. The Kalman gain K (shown as k in code) follows the modeled uncertainty and the chosen noise values.

Back to the chapter