Marcio Cunha

Reading Synchronization in I2C and SPI Buses under Electromagnetic Noise Using Kalman Filters in Firmware

Learn how to mitigate communication failures in I2C and SPI buses within noisy industrial environments by using Kalman filter mathematical estimation in firmware to ensure perfectly synchronized sensor readings.

Marcio Cunha•6 min
Also available in:PortuguêsEspañol
Summary
  • Kalman filters reduce noise variance in communication buses without introducing the phase lag typical of moving averages.
  • The I2C protocol suffers from parasitic capacitance and voltage spikes that corrupt clock transitions in electromagnetically hostile environments.
  • SPI communication exhibits high immunity at high frequencies but requires strict shielding and debouncing on long cables.
  • Fixed-point implementation in 32-bit microcontrollers enables execution of complex estimation algorithms without stalling cycle time.
  • Asynchronous sampling combined with state prediction eliminates false readings caused by electromagnetic transients in motors and inverters.

The Challenge of Electromagnetic Noise in Embedded Systems

When designing printed circuit boards that operate near industrial motors, relays, or switching power supplies, the physical environment ceases to be a predictable space. In these scenarios, electromagnetic noise induces stray currents into copper traces, corrupting digital signals traveling across communication buses. In practice, this means a high logic level can be incorrectly read as a low level, causing bus lockups and corrupting data from critical sensors. To mitigate this issue, engineers traditionally rely on decoupling capacitors and shielded cables, but physical shielding is not always sufficient to eliminate high-frequency transients that penetrate directly into microcontroller pins.

The physical vulnerability of industry-standard buses demands an approach that goes beyond pure hardware. While analog electronics attempt to contain the problem at the source, firmware steps in as the last line of defense, interpreting corrupted data before it destroys application logic. This is where mathematical estimation algorithms come into play, capable of looking at an unstable data stream and extracting the hidden physical truth beneath layers of interference. The core challenge lies in the fact that firmware must make real-time decisions, operating with limited computational resources without sacrificing the system's response speed.

Understanding the Physical Vulnerabilities of I2C and SPI

The I2C bus uses a data line called SDA and a clock line called SCL, both operating with external pull-up resistors that pull the voltage high. In practice, this means signal rise transitions are naturally slow, depending on the time constant formed by the resistor and the parasitic capacitance of the cables. When an electromagnetic pulse strikes this line, it generates spurious oscillations that the receiving chip mistakes for legitimate clock pulses, completely desynchronizing the bus state machine. This structural fragility makes I2C unsuitable for long distances without specialized differential buffers.

On the other hand, the SPI protocol uses dedicated lines for data transmission, reception, clock, and chip select, operating at much higher frequencies. Since the clock is actively generated by the master rather than relying on slow pull-up resistors, SPI withstands short buses under moderate noise much better. However, SPI's Achilles' heel is signal integrity on long cables, where mutual inductance causes wave reflections and severe clock distortion. In practice, this results in lost or shifted bits, requiring firmware to implement robust integrity verification mechanisms, such as checksums or redundant header packets, before accepting any data as valid.

The Working Principle of Kalman Filters in Resource-Constrained Systems

The Kalman filter is a recursive mathematical algorithm that estimates the true state of a physical system from a series of noisy and uncertain measurements. In practice, it acts as an intelligent mediator that weighs what the physical system model says should happen against what the raw sensor reading is showing. If the sensor suffers a sudden noise spike, the filter evaluates the system's inertia and discards the anomalous reading rather than reacting blindly to it. This behavior drastically differentiates it from traditional moving average filters, which smooth out noise but introduce unacceptable time lag in critical control loops.

The major barrier to using Kalman filters in low-cost microcontrollers was the intensive use of floating-point operations, which consume many CPU clock cycles. However, with the proliferation of ARM Cortex-M based processors equipped with hardware floating-point units, or through optimizations using fixed-point arithmetic, this barrier has fallen. In practical terms, a one-dimensional Kalman filter for a single sensor line can be executed in just a few microseconds, enabling its application in high-speed control loops where every clock cycle matters for the thermal and mechanical stability of the equipment.

Practical Implementation of State Estimation in Firmware

Structuring a Kalman filter in code requires defining two fundamental steps: prediction and update. In the prediction phase, the firmware uses the mathematical model of the system to estimate the current value based on the previous state and known control inputs. In the update phase, this prediction is corrected using the new reading coming from the I2C or SPI bus. The code below demonstrates a simplified and optimized C language implementation to calculate a filtered state in an embedded microcontroller.

typedef struct {
float x; // Estimated state
float P; // Estimation error covariance
float Q; // Process noise
float R; // Measurement noise
float K; // Kalman gain
} KalmanFilter;

void Kalman_Init(KalmanFilter *kf, float process_noise, float measurement_noise, float initial_value) {
kf->x = initial_value;
kf->P = 1.0f;
kf->Q = process_noise;
kf->R = measurement_noise;
}

float Kalman_Update(KalmanFilter *kf, float measurement) {
// Prediction
kf->P = kf->P + kf->Q;

// Calculate Kalman Gain
kf->K = kf->P / (kf->P + kf->R);

// Update state with noisy measurement
kf->x = kf->x + kf->K * (measurement - kf->x);

// Update error covariance
kf->P = (1.0f - kf->K) * kf->P;

return kf->x;
}

By integrating this function into the main sensor data acquisition loop, any isolated electromagnetic spike causing a sudden jump in bus reading is intelligently dampened. The Kalman gain adapts dynamically, trusting the predictive model more when noise exceeds expected physical limits. In practice, this eliminates the need to discard entire data packets due to a single spurious oscillation on the clock line, dramatically elevating operational availability in harsh environments.

Strategies for Temporal Synchronization of Multiple Sensors

In complex systems utilizing multiple sensors spread across I2C and SPI buses, ensuring that all readings belong to the exact same time instance is a monumental challenge. When electromagnetic noise intermittently interferes with communication, readings suffer variable delays, breaking data collection consistency. To solve this, firmware must implement time stamping based on high-resolution microcontroller timers, associating each raw data packet with its exact timestamp before submitting it to the filtering algorithm.

When sampling occurs asynchronously due to retransmissions forced by bus errors, the Kalman filter acts as a natural temporal synchronizer. It is capable of interpolating intermediate states, projecting what the exact variable value would be at the moment of the global system clock, even if the actual reading arrived a few milliseconds late. In practice, this prevents the control system from making decisions based on outdated information, maintaining mathematical coherence across the entire feedback loop and preventing destructive oscillations in the industrial plant.

Final Considerations on Reliability and Performance

Integrating advanced mathematical filters into firmware transforms inherently fragile communication channels into resilient data pathways capable of operating in severe industrial environments. While hardware remains the first line of defense against interference, embedded intelligence ensures transient faults are handled without compromising operational stability. By combining the physical robustness of shielded SPI and I2C with the predictive capability of the Kalman filter, engineers can design electronic systems that maintain precision and reliability even under constant electromagnetic bombardment.

The success of this approach lies in the careful balance between sampling rate, filter tuning parameters, and the processing power of the chosen microcontroller. Validating these choices on the workbench with surge generators and frequency inverters is the final step to ensuring firmware delivers the robustness promised in theory. With these guidelines, developing high-reliability embedded systems ceases to be a game of luck against noise and becomes an exact science of estimation and control.