Chapters

23 Sensor Calibration: Math and Validation

sensing
lab
calibration
wokwi

23.1 Start With the Decision

A calibration equation is only a claim until fresh readings test it. Compute the corrected value, residual error, and pass limit.

23.2 Route Overview

This is part 3 of 3. Review Sensor Calibration: Two-Point Lab for the preceding evidence.

23.3 Learning Objectives

  • Apply a calibration equation to raw sensor readings.
  • Validate corrected results with error and quality metrics.

23.4 Chapter Roadmap

  • Putting Numbers to It
  • Checkpoint: Calibration Math
  • Part 5: Challenge Exercises
  • Challenge 1: Three-Point Calibration
  • Challenge 2: EEPROM Calibration Storage
  • Automatic Drift Compensation
  • Key Calibration Concepts Summary
  • Best Practices for Sensor Calibration
  • Checkpoint: Production Calibration
  • Calibration Formulas
  • Span Validation
  • Next Calibration Practice
  • Summary
  • Knowledge Check
  • See Also
  • What’s Next
Putting Numbers to It

Two-Point Calibration Calculation: A load cell for beehive monitoring reads 410 raw ADC counts at 0 kg and 3685 counts at 50 kg (using a 12-bit ADC with 0-4095 range). Calculate gain and offset to convert raw ADC to kilograms.

Given reference points:

  • Low: (410 counts,0 kg)(410\text{ counts}, 0\text{ kg})
  • High: (3685 counts,50 kg)(3685\text{ counts}, 50\text{ kg})

Step 1: Calculate gain (slope of the line):

Gain=y2y1x2x1=50 kg0 kg3685410=503275=0.01527 kg/count\text{Gain} = \frac{y_2 - y_1}{x_2 - x_1} = \frac{50\text{ kg} - 0\text{ kg}}{3685 - 410} = \frac{50}{3275} = 0.01527\text{ kg/count}

Step 2: Calculate offset (y-intercept):

Offset=y1(x1×Gain)=0(410×0.01527)=6.26 kg\text{Offset} = y_1 - (x_1 \times \text{Gain}) = 0 - (410 \times 0.01527) = -6.26\text{ kg}

Step 3: Calibration equation:

Weight (kg)=(Raw ADC counts×0.01527)6.26\text{Weight (kg)} = (\text{Raw ADC counts} \times 0.01527) - 6.26

Verification:

  • At 410 counts: (410×0.01527)6.26=6.266.26=0 kg(410 \times 0.01527) - 6.26 = 6.26 - 6.26 = 0\text{ kg}
  • At 3685 counts: (3685×0.01527)6.26=56.276.26=50.01 kg50 kg(3685 \times 0.01527) - 6.26 = 56.27 - 6.26 = 50.01\text{ kg} \approx 50\text{ kg}

Resolution calculation:

Resolution=Gain=0.01527 kg/count15 grams/count\text{Resolution} = \text{Gain} = 0.01527\text{ kg/count} \approx 15\text{ grams/count}

With a 12-bit ADC (4096 levels) spanning the full 50 kg range, theoretical resolution would be 50/4096 = 12.2 g. Our actual resolution of 15 g is slightly worse because the load cell does not use the full ADC range (3275 out of 4096 counts, or about 80%). Adjusting amplification to use more of the ADC range would improve resolution.

Physics PhoebeCheckpoint: Calibration Math

You now know:

  • Two reference points define the line: gain equals (actual_high - actual_low) / (raw_high - raw_low).
  • The load-cell example maps 410 counts to 0 kg and 3685 counts to 50 kg, giving a gain of 0.01527 kg/count and an offset of -6.26 kg.
  • A 12-bit ADC has 4096 levels, but usable resolution depends on how much of that range the sensor actually spans.

23.4.1 Interactive ADC Resolution Calculator

Explore how ADC bit depth and measurement range affect the smallest detectable change (resolution per count).



23.4.2 Knowledge Check: Calibration Math

23.4.3 Moving Average Filter Explorer

A moving average filter smooths noisy data by averaging a window of recent samples. The window size (N) controls the tradeoff between smoothing and responsiveness. Larger windows produce smoother output but react more slowly to real changes.



The math and filter sections answer “what coefficients should I calculate?” The challenges below ask the production question: how do you keep those coefficients trustworthy after the first successful run?

23.5 Part 5: Challenge Exercises

23.6 Challenge 1: Three-Point Calibration

Run it: Before you code the three-point version, compare the methods in the reference animation below. Select 2-point and then Multi-point on the same sensor type and watch how a straight two-point line leaves error in a bending response while multi-point interpolation follows the curve. Use it to predict how much accuracy the added midpoint should buy you before you measure it in the simulator.

Goal: Extend the calibration to use three reference points for improved accuracy across the range.

Tasks:

  1. Add a third reference point at 50% (midpoint)
  2. Capture three points: low (10%), mid (50%), high (90%)
  3. Use piecewise linear interpolation:
    • For values < 50%: use low-to-mid segment
    • For values >= 50%: use mid-to-high segment
  4. Compare accuracy against two-point calibration

Hint: Store two sets of gain/offset coefficients and select based on input value.

23.7 Challenge 2: EEPROM Calibration Storage

Goal: Persist calibration coefficients so they survive power cycles.

Tasks:

Start by add EEPROM library and save calibration after calculation. Then load calibration automatically at startup. Next add validity check (magic number) to detect uncalibrated state. Finally add a ‘w’ command to write calibration and ‘e’ command to erase.

#include <EEPROM.h>

// EEPROM addresses
const int EEPROM_MAGIC_ADDR = 0;
const int EEPROM_GAIN_ADDR = 4;
const int EEPROM_OFFSET_ADDR = 8;
const int EEPROM_MAGIC_VALUE = 0xCAFE;

void saveCalibrationToEEPROM() {
    EEPROM.begin(64);
    EEPROM.put(EEPROM_MAGIC_ADDR, EEPROM_MAGIC_VALUE);
    EEPROM.put(EEPROM_GAIN_ADDR, calGain);
    EEPROM.put(EEPROM_OFFSET_ADDR, calOffset);
    EEPROM.commit();
    Serial.println("Calibration saved to EEPROM!");
}

void loadCalibrationFromEEPROM() {
    EEPROM.begin(64);
    int magic;
    EEPROM.get(EEPROM_MAGIC_ADDR, magic);

    if (magic == EEPROM_MAGIC_VALUE) {
        EEPROM.get(EEPROM_GAIN_ADDR, calGain);
        EEPROM.get(EEPROM_OFFSET_ADDR, calOffset);
        Serial.println("Calibration loaded from EEPROM");
    } else {
        Serial.println("No valid calibration found, using defaults");
        calGain = 1.0;
        calOffset = 0.0;
    }
}

23.8 Automatic Drift Compensation

Goal: Implement automatic baseline drift correction for long-term deployments.

Background: Sensors drift over time due to aging, temperature changes, and contamination. Automatic Baseline Correction (ABC) can compensate by assuming the sensor occasionally sees a known reference (e.g., CO2 sensors assume 400ppm outdoor air).

Tasks:

  1. Track the minimum reading over a 24-hour window
  2. Assume this minimum represents the “baseline” reference value
  3. Automatically adjust offset to correct drift
  4. Add drift alarm if correction exceeds threshold

23.9 Key Calibration Concepts Summary

To consolidate the lab into a repeatable workflow, inspect Figure 23.1 before moving from calculation to field use. The map connects error types, calibration methods, validation, and maintenance so none is mistaken for the whole job.

Sensor calibration proceeds through Diagnose, Fit, Validate and Maintain. Gain and offset need reference conditions, residual error and a recorded recalibration trigger.
Figure 23.1: Mind map of key sensor calibration concepts covered in this lab

Read Figure 23.1, begin with the error branch, then follow the method and validation branches before finishing at maintenance. That order shows why a fitted gain and offset are only useful when their reference conditions, residual error, and recalibration trigger remain recorded.

ConceptDescriptionWhen to Use
Offset ErrorSensor reads non-zero when true value is zeroAlways needs correction
Gain ErrorSensor’s sensitivity differs from specificationWhen readings scale incorrectly
Two-Point CalibrationUses two reference points to calculate offset and gainLinear sensors (most common)
Multi-Point CalibrationUses 3+ reference points with interpolationNon-linear sensors (thermistors, pH)
Moving Average FilterAverages N recent readings to reduce noiseNoisy environments, slow-changing signals
EEPROM StoragePersists calibration across power cyclesProduction deployments

Best Practices for Sensor Calibration

Start with Use reference standards that bracket your expected measurement range. Then Allow sensor warm-up time before calibration (typically 5-30 minutes). Next Document environmental conditions during calibration (temperature, humidity). After that Recalibrate periodically based on manufacturer recommendations. Continue by Store calibration metadata including date, conditions, and number of points. Finally Validate calibration by checking known reference values after applying coefficients.

Physics PhoebeCheckpoint: Production Calibration

You now know:

  • Multi-point calibration adds 3 or more reference points when a sensor curve is not linear.
  • EEPROM storage needs a validity marker such as 0xCAFE so startup code can reject uninitialized memory.
  • Automatic Baseline Correction tracks a 24-hour minimum only when the sensor is expected to see a known baseline condition.
Calibration Formulas

Two-Point Calibration Formula:

StepFormulaDescription
1gain = (actual_high - actual_low) / (raw_high - raw_low)Calculate slope
2offset = actual_low - (raw_low × gain)Calculate y-intercept
3calibrated = raw × gain + offsetApply correction

See the Two-Point Calibration Calculator above for a hands-on tool. The worked load-cell example in Part 4 shows the same calculation with real numbers.

23.9.1 Production Considerations

23.10 Span Validation

The core lab above shows how to build and store a two-point calibration. The companion page focuses on the failure modes that determine whether those coefficients are trustworthy in production.

Next Calibration Practice

Continue with Calibration Span Error and Validation to test reference-point spacing, residual checks, range guards, and release evidence for calibrated sensors.

23.11 Summary

This lab provided hands-on experience with essential sensor calibration techniques used in production IoT systems.

23.11.1 Key Takeaways

ConceptWhat You LearnedWhen to Apply
Two-Point CalibrationCalculate gain and offset from two known reference pointsAll linear sensors (temperature, pressure, light)
Moving Average FilterSmooth noisy readings by averaging N recent samplesNoisy environments, before capturing calibration references
State Machine DesignGuide users through multi-step processesAny interactive calibration or configuration procedure
Calibration Formulacalibrated = raw * gain + offsetApply correction to every raw sensor reading
EEPROM PersistenceStore calibration across power cycles with magic number validationProduction deployments, field-calibrated devices
Automatic Drift CompensationTrack minimum over time window to correct sensor driftLong-term deployments, sensors prone to aging

23.11.2 Skills You Practiced

Start with Circuit building: Connecting potentiometer and LED to ESP32. Then Serial communication: Interactive command interface for calibration. Next Mathematical modeling: Applying linear algebra to sensor correction. After that Firmware architecture: State machine design for multi-step workflows. Finally Data persistence: Using EEPROM for non-volatile storage.

23.11.3 Common Pitfalls to Avoid

Before treating a calibration run as complete, inspect Figure 23.2 to see how seemingly sensible shortcuts can invalidate the correction. The visual turns four recurring mistakes into checks that can be applied before measurements are accepted.

Diagram showing four common calibration pitfalls: reference points too close together, no sensor warm-up time, not filtering before capture, and assuming calibration lasts forever, with fixes for each
Figure 23.2: Common calibration pitfalls to avoid

Read Figure 23.2, read each pitfall together with its remedy: widen poorly separated reference points, allow warm-up, stabilise samples before capture, and schedule recalibration rather than assuming permanence. Those checks carry the lab from calculating coefficients to maintaining trustworthy measurements.

PitfallWhy It’s BadSolution
Reference points too close togetherSmall errors in reference measurement cause large errors in calculated gainUse 10% and 90%, not 45% and 55%
Forgetting sensor warm-up timeSensors drift significantly in first few minutes after power-onAllow 5-30 minutes before calibration
Not filtering before captureSingle noisy sample can corrupt entire calibrationApply moving average filter before capturing reference
Assuming calibration lasts foreverSensors drift over time due to aging and environmentRecalibrate periodically based on manufacturer guidance

23.12 Knowledge Check

23.12.1 Quiz: Sensor Calibration

Before applying the specification, inspect the real sensor calibration laboratory below: its package, terminals, scale, and installation context are part of the engineering evidence.

Real photograph of sensor calibration laboratory
This real example (SOAR staff working on the Calibration Wavefront Sensor assembly (20210624152355-IMG-6439-1-CC2)) shows a physical form of sensor calibration laboratory. Use the visible package, interfaces, scale, mounting, and surrounding context as evidence; a catalogue label alone does not establish deployment fit. Photo: CTIO/NOIRLab/SOAR/NSF/AURA; CC BY 4.0

Carry those visible constraints into the surrounding analysis; the abstract symbol or capability name does not capture mounting, wiring, protection, or service access.

Match each calibration concept with its correct definition:

Arrange the two-point calibration procedure steps in the correct order:

23.13 See Also

For the full list of related chapters, see the “Related Chapters” section at the top of this page. Additional resources:

23.14 What’s Next

If you want to…Read this
Understand the theory behind filtering and calibrationSensor Data Processing
Learn I2C and SPI sensor communication protocolsSensor Communication Protocols
Apply calibration to specific sensor types in depthSensor Types: Calibration
Practice more sensor labs on ESP32 with WokwiSensor Labs: Implementation and Review

23.15 Continue Your Route

This final part closes the route from Putting Numbers to It through What’s Next. Return to Sensor Calibration: Two-Point Lab or continue from the sensors module index.