23 Sensor Calibration: Math and Validation
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
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:
- High:
Step 1: Calculate gain (slope of the line):
Step 2: Calculate offset (y-intercept):
Step 3: Calibration equation:
Verification:
- At 410 counts: ✓
- At 3685 counts: ✓
Resolution calculation:
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.
Checkpoint: 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:
- Add a third reference point at 50% (midpoint)
- Capture three points: low (10%), mid (50%), high (90%)
- Use piecewise linear interpolation:
- For values < 50%: use low-to-mid segment
- For values >= 50%: use mid-to-high segment
- 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:
- Track the minimum reading over a 24-hour window
- Assume this minimum represents the “baseline” reference value
- Automatically adjust offset to correct drift
- 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.
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.
| Concept | Description | When to Use |
|---|---|---|
| Offset Error | Sensor reads non-zero when true value is zero | Always needs correction |
| Gain Error | Sensor’s sensitivity differs from specification | When readings scale incorrectly |
| Two-Point Calibration | Uses two reference points to calculate offset and gain | Linear sensors (most common) |
| Multi-Point Calibration | Uses 3+ reference points with interpolation | Non-linear sensors (thermistors, pH) |
| Moving Average Filter | Averages N recent readings to reduce noise | Noisy environments, slow-changing signals |
| EEPROM Storage | Persists calibration across power cycles | Production deployments |
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.
Checkpoint: 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
0xCAFEso 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.
Two-Point Calibration Formula:
| Step | Formula | Description |
|---|---|---|
| 1 | gain = (actual_high - actual_low) / (raw_high - raw_low) | Calculate slope |
| 2 | offset = actual_low - (raw_low × gain) | Calculate y-intercept |
| 3 | calibrated = raw × gain + offset | Apply 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.
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
| Concept | What You Learned | When to Apply |
|---|---|---|
| Two-Point Calibration | Calculate gain and offset from two known reference points | All linear sensors (temperature, pressure, light) |
| Moving Average Filter | Smooth noisy readings by averaging N recent samples | Noisy environments, before capturing calibration references |
| State Machine Design | Guide users through multi-step processes | Any interactive calibration or configuration procedure |
| Calibration Formula | calibrated = raw * gain + offset | Apply correction to every raw sensor reading |
| EEPROM Persistence | Store calibration across power cycles with magic number validation | Production deployments, field-calibrated devices |
| Automatic Drift Compensation | Track minimum over time window to correct sensor drift | Long-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.
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.
| Pitfall | Why It’s Bad | Solution |
|---|---|---|
| Reference points too close together | Small errors in reference measurement cause large errors in calculated gain | Use 10% and 90%, not 45% and 55% |
| Forgetting sensor warm-up time | Sensors drift significantly in first few minutes after power-on | Allow 5-30 minutes before calibration |
| Not filtering before capture | Single noisy sample can corrupt entire calibration | Apply moving average filter before capturing reference |
| Assuming calibration lasts forever | Sensors drift over time due to aging and environment | Recalibrate 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.
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:
- Multi-Sensor Data Fusion - Combining calibrated data from multiple sensors
- Sensor Labs: Implementation and Review - Hardware and browser-lab workflow patterns
23.14 What’s Next
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.
