Marcio Cunha

How to calibrate analog sensors on ESP32 properly

Learn how to correct voltage distortions and eliminate electrical noise on ESP32 analog-to-digital converter readings using software calibration and filters.

Marcio Cunha•4 min
Also available in:PortuguêsEspañol
Summary
  • The analog conversion of the ESP32 suffers from non-linear curves that require correction lookup tables or polynomials.
  • Electromagnetic bench noise can be attenuated by combining moving average software filters with a physical capacitor.
  • Unstable measurements occur due to internal reference voltage fluctuations inside the microcontroller chip.
  • Reference-point calibration eliminates systematic drift between code measurements and multimeter readouts.
  • Implementing consistent sampling routines ensures reliable data before transmitting signals to MQTT brokers.

Why do ESP32 analog readings behave erratically?

Anyone starting with microcontrollers soon notices that connecting a temperature sensor or potentiometer to the analog input of an ESP32 produces numbers that fluctuate endlessly. In practice, this happens because the analog-to-digital converter, known as the ADC, translates continuous physical voltage into a discrete digital number, but suffers from manufacturing imperfections and environmental interference. The internal circuitry of the chip picks up magnetic or electrical stray radiation around it, turning ordinary wires into small noise antennas. Solving this problem requires going beyond direct pin reading to understand real hardware behavior and apply signal processing techniques.

Another decisive factor is the inherent non-linearity of the ESP32 converter near the operational range boundaries, both close to zero and near three and a half volts. This means the relationship between the applied voltage and the number returned by the code does not follow a perfect straight line, causing errors that increase as we move away from the center. If you need precision, such as monitoring critical voltages or checking component values like when testing electronic hardware using diagnostic tools, accepting the raw port value will introduce severe distortions into automation and robotics projects.

How software voltage calibration works

Calibrating a sensor means aligning the physical reality of the circuit with the microcontroller's numerical interpretation through mathematical adjustments. The first practical step involves collecting known voltage points using a reliable multimeter as a bench standard reference, comparing the instrument's display value with the raw number delivered by the analogRead function. With at least two or three data pairs, we can calculate a linear correction line applying the famous line equation where slope and offset compensate for converter manufacturing errors.

When circuits demand even higher accuracy, we can implement a lookup table or a higher-order polynomial to correct steep curves in specific operating ranges. In C++ code for the ESP-IDF or Arduino architecture, we apply this formula right after receiving the raw port reading, transforming the raw data into real millivolts before any other system logic. This simple care ensures telemetry sent to supervision platforms and local servers via lightweight IoT communication protocols accurately reflects the physical phenomenon monitored in the field.

Eliminating electrical noise with efficient digital filters

Even with good mathematical calibration, high-frequency electrical noise still causes sudden, unwanted jumps in instantaneous converter readings. The most elegant and cost-effective way to solve this without altering the printed circuit board is implementing a moving average filter directly in the microcontroller code. This algorithm stores a short history of recent collected readings, calculates the arithmetic mean, and discards isolated peaks caused by transient electromagnetic interference in power lines or nearby motors.

For industrial scenarios or environments with high incidence of interference generated by frequency inverters and switching power supplies, reinforcing physical cabling protection before feeding the signal to the microcontroller is worthwhile. As discussed when analyzing advanced shielding techniques against electromagnetic noise in factory floors, using shielded cables and proper mesh grounding prevents corrupted analog signals from reaching input pins. Combining a physical RC filter on the board with an intelligent software sampling routine yields stability comparable to professional instrumentation equipment.

Implementing filtered readings in ESP32 code

To put theory into practice, let's structure an efficient analog reading routine that applies both linearity correction and moving average smoothing. The code below uses the standard Arduino environment library to configure the pin, take multiple samples in a short time span, and return a stable value clean of spurious noise. Using proper data types avoids memory overflows and ensures internal processing occurs at high execution speeds, ideal for control loops demanding immediate responses.

const int sensorPin = 34; // ESP32 ADC1 pin
const int numSamples = 10; // Number of samples for the filter

void setup() {
  Serial.begin(115200);
  analogSetAttenuation(ADC_11db); // Set reading range up to ~3.3V
}

int readFilteredSensor() {
  long sum = 0;
  for (int i = 0; i < numSamples; i++) {
    sum += analogRead(sensorPin);
    delay(2);
  }
  return sum / numSamples;
}

void loop() {
  int rawValue = readFilteredSensor();
  float estimatedVoltage = (rawValue / 4095.0) * 3300.0; // Conversion to millivolts
  Serial.print("Filtered Value: ");
  Serial.print(rawValue);
  Serial.print(" | Voltage: ");
  Serial.print(estimatedVoltage);
  Serial.println(" mV");
  delay(1000);
}

Final considerations on analog signal acquisition

Mastering analog signal reading on the ESP32 requires understanding that hardware project success depends not only on buying expensive components, but on properly addressing the physical limitations of silicon. By combining a calibration stage based on real reference points with intelligent digital filtering algorithms, we transform a noisy and unstable converter into a reliable measurement tool. This technical rigor protects your system against false alarms and ensures collected data has genuine utility for engineering analysis.

Maintaining discipline in physical circuit assembly and source code structure creates a solid foundation for any home or industrial automation application. Whether monitoring electrical quantities or complex environmental sensors, investing time in fine-tuning the analog-to-digital converter saves hours of future debugging. With the concepts presented here, you have the complete pathway to extract maximum performance from your microcontroller's analog inputs.