Home Learning Paths ECU Lab Assessments Interview Preparation Arena Pricing Log In Sign Up

Closed-Loop Calibration Architecture

Closed-Loop Calibration Control Loop
  MATLAB Optimizer
  ├── Reads ECU MEASUREMENT via CANape COM API
  │     actual_rpm, lambda, HC_ppm, NOx_ppm
  │
  ├── Evaluates objective function:
  │     J = w1×NOx_error^2 + w2×HC_error^2 + w3×fuel_error^2
  │
  ├── Computes new CHARACTERISTIC values
  │     (gradient descent / Bayesian / genetic algorithm step)
  │
  └── Writes updated parameters via CANape COM API
        SetValue("EGR_MAP[rpm_idx][load_idx]", new_val)
        → XCP DOWNLOAD to ECU RAM working page
        → ECU responds within 10ms (next task cycle)

  Loop until: objective function J < tolerance
           or max iterations reached
           or constraint violation detected

MATLAB COM API Integration with CANape

MATLABautomated_cal.m
% MATLAB + CANape COM API: automated calibration with fmincon optimizer

% Connect to CANape
canape = actxserver('CANape.Application');
device = canape.Devices.Item('ECU_Engine');
device.Open();

% Objective function: minimise HC_ppm at operating point
% x = [egr_pct, inj_timing_offset_deg]
function J = objective(x, canape, device)
    % Write parameters to ECU
    device.Variables.Item('EGR_MAX_PCT').SetValue(x(1));
    device.Variables.Item('IGN_TIMING_OFFSET').SetValue(x(2));
    
    pause(3.0);  % wait for ECU to reach steady state
    
    % Measure response
    HC  = device.Variables.Item('HC_ppm').GetValue();
    NOx = device.Variables.Item('NOx_ppm').GetValue();
    fuel = device.Variables.Item('fuel_cons_l100km').GetValue();
    
    % Weighted objective (minimise)
    J = 0.5*HC/150 + 0.3*NOx/60 + 0.2*fuel/5.0;
end

% Run optimisation
x0     = [25.0, 0.0];   % initial: EGR=25%, timing offset=0
lb     = [0.0, -5.0];   % lower bounds
ub     = [40.0, 5.0];   % upper bounds
options = optimoptions('fmincon','Display','iter','MaxIter',50);
x_opt  = fmincon(@(x) objective(x, canape, device), x0, [],[],[],[],lb,ub,[],options);

fprintf('Optimal: EGR=%.1f%%, timing_offset=%.1f deg\n', x_opt(1), x_opt(2));
device.Close();

Residual Gas Fraction Optimisation Example

Optimisation StepParameterMEASUREMENTResult
Initial stateEVC_offset = 0 CADHC_ppm = 285, idle_roughness_rms = 0.3 NmHC too high
Sweep +5 CADEVC_offset = 5HC_ppm = 240, roughness = 0.35 NmImproving
Sweep +10 CADEVC_offset = 10HC_ppm = 198, roughness = 0.42 NmBetter, still within constraint
Sweep +15 CADEVC_offset = 15HC_ppm = 195, roughness = 0.51 NmRoughness constraint violated (> 0.5)
Optimal (constraint boundary)EVC_offset = 12HC_ppm = 196, roughness = 0.48 NmMinimum HC within stability limit
Pythonevc_optimizer.py
# Automated EVC offset sweep with stability constraint
import canape_com as canape, time, numpy as np

device = canape.OpenDevice("ECU_Engine")
device.Connect()

best_hc = float('inf'); best_evc = 0
for evc in range(0, 20, 2):  # sweep 0 to 18 CAD in 2-step increments
    device.SetValue("EVC_offset", float(evc))
    time.sleep(5.0)  # settle
    hc = device.MeasureAverage("HC_ppm", seconds=3)
    roughness = device.MeasureStdDev("engine_torque_Nm", seconds=3)
    print(f"EVC={evc:2d} CAD: HC={hc:.0f} ppm, roughness={roughness:.3f} Nm")
    if roughness < 0.50 and hc < best_hc:  # constraint check
        best_hc = hc; best_evc = evc

print(f"Optimal EVC_offset = {best_evc} CAD → HC = {best_hc:.0f} ppm")
device.SetValue("EVC_offset", float(best_evc))
device.CopyCalPage(src=0, dst=1)  # save to Flash

OBD-Cycle Overnight Automation

Pythonovernight_obd_cycle.py
#!/usr/bin/env python3
# Overnight OBD-cycle automated calibration: unattended WLTP run + map update

import inca_automation as inca_auto, time, json, datetime

def run_wltp_cycle(inca_auto):
    # Send WLTP speed profile to dyno controller
    inca_auto.dyno.LoadCycle("WLTP_Class3.csv")
    inca_auto.inca.StartRecording(f"wltp_run_{datetime.datetime.now():%Y%m%d_%H%M}.mf4")
    inca_auto.dyno.StartCycle()
    inca_auto.dyno.WaitForCycleComplete(timeout_s=2000)
    inca_auto.inca.StopRecording()
    return inca_auto.inca.GetLastRecordingPath()

def evaluate_emissions(mf4_path):
    rec = inca_auto.mda.Load(mf4_path)
    return {
        "NOx_mg_km": rec.IntegrateOverCycle("NOx_ppm") / 1000,
        "HC_mg_km":  rec.IntegrateOverCycle("HC_ppm") / 1000,
        "fuel_l100": rec.CalculateFuelConsumption(),
    }

# Main overnight loop
inca_auto.inca.Connect()
for iteration in range(20):  # max 20 iterations
    mf4 = run_wltp_cycle(inca_auto)
    results = evaluate_emissions(mf4)
    print(f"Iter {iteration}: NOx={results['NOx_mg_km']:.1f} mg/km, "
          f"HC={results['HC_mg_km']:.1f} mg/km, fuel={results['fuel_l100']:.2f} L/100km")

    if results['NOx_mg_km'] < 60 and results['HC_mg_km'] < 100:
        print("OBD targets met — stopping optimisation")
        break

    # Update injection timing map (gradient step toward lower NOx)
    inca_auto.inca.optimizer.StepGradient("injection_timing_MAP",
                                          objective="NOx_mg_km",
                                          step_size=0.5)  # 0.5 degree per iteration

inca_auto.inca.Disconnect()

Summary

Automated closed-loop calibration reduces manual dyno time from days to hours. The MATLAB+CANape COM API pattern is the industry standard for scripted sweeps. The EVC offset example demonstrates constraint-aware optimisation — the automated loop finds the true optimum at the constraint boundary faster than any manual sweep. Overnight OBD-cycle automation enables unattended emissions-targeted calibration iteration, with the engineer reviewing results the next morning rather than operating the dyno manually.

🔬 Deep Dive — Core Concepts Expanded

This section builds on the foundational concepts covered above with additional technical depth, edge cases, and configuration nuances that separate competent engineers from experts. When working on production ECU projects, the details covered here are the ones most commonly responsible for integration delays and late-phase defects.

Key principles to reinforce:

  • Configuration over coding: In AUTOSAR and automotive middleware environments, correctness is largely determined by ARXML configuration, not application code. A correctly implemented algorithm can produce wrong results due to a single misconfigured parameter.
  • Traceability as a first-class concern: Every configuration decision should be traceable to a requirement, safety goal, or architecture decision. Undocumented configuration choices are a common source of regression defects when ECUs are updated.
  • Cross-module dependencies: In tightly integrated automotive software stacks, changing one module's configuration often requires corresponding updates in dependent modules. Always perform a dependency impact analysis before submitting configuration changes.

🏭 How This Topic Appears in Production Projects

  • Project integration phase: The concepts covered in this lesson are most commonly encountered during ECU integration testing — when multiple software components from different teams are combined for the first time. Issues that were invisible in unit tests frequently surface at this stage.
  • Supplier/OEM interface: This is a topic that frequently appears in technical discussions between Tier-1 ECU suppliers and OEM system integrators. Engineers who can speak fluently about these details earn credibility and are often brought into critical design review meetings.
  • Automotive tool ecosystem: Vector CANoe/CANalyzer, dSPACE tools, and ETAS INCA are the standard tools used to validate and measure the correct behaviour of the systems described in this lesson. Familiarity with these tools alongside the conceptual knowledge dramatically accelerates debugging in real projects.

⚠️ Common Mistakes and How to Avoid Them

  1. Assuming default configuration is correct: Automotive software tools ship with default configurations that are designed to compile and link, not to meet project-specific requirements. Every configuration parameter needs to be consciously set. 'It compiled' is not the same as 'it is correctly configured'.
  2. Skipping documentation of configuration rationale: In a 3-year ECU project with team turnover, undocumented configuration choices become tribal knowledge that disappears when engineers leave. Document why a parameter is set to a specific value, not just what it is set to.
  3. Testing only the happy path: Automotive ECUs must behave correctly under fault conditions, voltage variations, and communication errors. Always test the error handling paths as rigorously as the nominal operation. Many production escapes originate in untested error branches.
  4. Version mismatches between teams: In a multi-team project, the BSW team, SWC team, and system integration team may use different versions of the same ARXML file. Version management of all ARXML files in a shared repository is mandatory, not optional.

📊 Industry Note

Engineers who master both the theoretical concepts and the practical toolchain skills covered in this course are among the most sought-after professionals in the automotive software industry. The combination of AUTOSAR standards knowledge, safety engineering understanding, and hands-on configuration experience commands premium salaries at OEMs and Tier-1 suppliers globally.

← PreviousDoE (Design of Experiments) for CalibrationNext →Calibration for ADAS Systems