Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build-unit-tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ jobs:

- name: Run Tests
working-directory: ./unit_tests/
#run: ASAN_OPTIONS=detect_stack_use_after_return=1 build/fome_test
run: build/fome_test
#run: ASAN_OPTIONS=detect_stack_use_after_return=1 make -j4 test COVERAGE=yes
run: make -j4 test COVERAGE=yes

- name: Set FTP variables
env:
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ Outputs are placed in `firmware/deliver/`:

```bash
cd unit_tests
make -j12
./build/fome_test
make -j12 test

# Run a specific test
./build/fome_test --gtest_filter=TestName
```

The `test` target builds and runs the engine suite and both ADC lifecycle suites.
Unit tests use Google Test and run on amd64/aarch64, not on the ECU.

### Code Generation
Expand Down
2 changes: 2 additions & 0 deletions firmware/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ or
## Unreleased

### Added
- Add `adc_stats` console diagnostics for fast ADC and software knock: conversion starts, completed buffers, skipped starts by reason, and ADC errors.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not user facing, it doesn't belong here

@gdiciocco gdiciocco Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed

- Fahrenheit temperature support: pick "Fahrenheit" under Settings > Temperature Units in TunerStudio and all temperature gauges, datalogs, sensor adjustments, and thermistor calibration points display in °F. The stored tune is unchanged (always Celsius internally), so switching units never resets your configuration and works on every supported board.
- Add mode for "true" wasted spark on odd fire engines (Viper V10) where companion cylinders are not exactly 360 degrees apart. Requires cam sync.
- New `CPU usage` output channel showing approximate firmware CPU load
Expand All @@ -52,6 +53,7 @@ or
- Instant RPM is now used automatically on triggers with 24 or more teeth per engine cycle (a 12 tooth crank wheel or better), instead of only when "Always use instant RPM" was enabled. RPM, and everything derived from it, now responds within a fraction of an engine cycle instead of once per cycle. The setting remains, and now forces instant RPM on triggers with fewer teeth than that.

### Fixed
- Prevent an ADC panic when fast ADC or software knock sampling overlaps the previous conversion's completion callback.
- Changing or clearing the MAP 2, MAF, MAF 2 or fuel level sensor input no longer leaves the sensor reading its old pin (and the pin claimed) until the ECU is rebooted. MAF and fuel level input changes now take effect immediately, like other analog sensors
- STM32F7 dual-bank ECUs no longer stall (potentially stopping the engine) when burning configuration with the engine running - configuration is now committed to flash when the engine is stopped #776
- SD card log field names now include their category prefix (e.g. `Boost: Target` instead of just `Target`), matching the names shown in TunerStudio
Expand Down
11 changes: 9 additions & 2 deletions firmware/controllers/sensors/impl/software_knock.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

#if EFI_SOFTWARE_KNOCK

#include "adc_diagnostics.h"

#include "knock_config.h"
#include "ch.hpp"

Expand Down Expand Up @@ -35,16 +37,19 @@ void onKnockSamplingComplete() {

void onStartKnockSampling(uint8_t cylinderNumber, float samplingSeconds, uint8_t channelIdx) {
if (!engineConfiguration->enableSoftwareKnock) {
knockAdcDiagnostics.skippedDisabled++;
return;
}

// Cancel if ADC isn't ready
if (!((KNOCK_ADC.state == ADC_READY) || (KNOCK_ADC.state == ADC_COMPLETE) || (KNOCK_ADC.state == ADC_ERROR))) {
// ADC_COMPLETE belongs to the completion callback; the HAL is not ready yet.
if (!((KNOCK_ADC.state == ADC_READY) || (KNOCK_ADC.state == ADC_ERROR))) {
recordAdcSkippedState(knockAdcDiagnostics, KNOCK_ADC.state);
return;
}

// If there's pending processing, skip this event
if (knockNeedsProcess) {
knockAdcDiagnostics.skippedPending++;
return;
}

Expand All @@ -61,6 +66,7 @@ void onStartKnockSampling(uint8_t cylinderNumber, float samplingSeconds, uint8_t
currentChannelIdx = channelIdx;

adcStartConversionI(&KNOCK_ADC, conversionGroup, knockSampleBuffer, sampleCount);
knockAdcDiagnostics.started++;
lastKnockSampleTime = getTimeNowNt();
knockSnifferPin.setHigh();
}
Expand Down Expand Up @@ -159,6 +165,7 @@ static void processLastKnockEvent() {

engine->module<KnockController>()->onKnockSenseCompleted(
currentCylinderNumber, currentChannelIdx, db, lastKnockTime);
knockAdcDiagnostics.processed++;
}

void KnockThread::ThreadTask() {
Expand Down
63 changes: 63 additions & 0 deletions firmware/hw_layer/adc/adc_diagnostics.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#include "pch.h"

#if HAL_USE_ADC
#include "adc_diagnostics.h"

AdcDiagnostics fastAdcDiagnostics;
AdcDiagnostics knockAdcDiagnostics;
static bool fastIsCircular;

AdcDiagnosticsSnapshot getAdcDiagnostics() {
// Timer/scheduler updates are already locked. ADC/DMA callbacks use
// EFI_IRQ_ADC_PRIORITY, which this system lock masks; it also prevents
// the knock processing thread from running during the copy.
chibios_rt::CriticalSectionLocker lock;
return {fastAdcDiagnostics, knockAdcDiagnostics};
}

static void printCounters(const char* name, const AdcDiagnostics& counters) {
efiPrintf(
"adc %s started=%lu completed=%lu errors=%lu last_error=%lu processed=%lu",
name,
static_cast<unsigned long>(counters.started),
static_cast<unsigned long>(counters.completed),
static_cast<unsigned long>(counters.errors),
static_cast<unsigned long>(counters.lastError),
static_cast<unsigned long>(counters.processed));
efiPrintf(
"adc %s skip_active=%lu skip_complete=%lu skip_not_ready=%lu",
name,
static_cast<unsigned long>(counters.skippedActive),
static_cast<unsigned long>(counters.skippedComplete),
static_cast<unsigned long>(counters.skippedNotReady));
efiPrintf(
"adc %s skip_no_channels=%lu skip_invalid_channels=%lu skip_disabled=%lu skip_pending=%lu",
name,
static_cast<unsigned long>(counters.skippedNoChannels),
static_cast<unsigned long>(counters.skippedInvalidChannels),
static_cast<unsigned long>(counters.skippedDisabled),
static_cast<unsigned long>(counters.skippedPending));
}

static void printAdcDiagnostics() {
const auto snapshot = getAdcDiagnostics();
// Formatting and console I/O must stay outside the critical section.
efiPrintf(
"adc mode=%s started_unit=%s completed_unit=buffer counters=uint32_since_boot knock_compiled=%d",
fastIsCircular ? "circular" : "timer",
fastIsCircular ? "stream" : "conversion",
#if EFI_SOFTWARE_KNOCK
1
#else
0
#endif
);
printCounters("fast", snapshot.fast);
printCounters("knock", snapshot.knock);
}

void initAdcDiagnostics(bool circular) {
fastIsCircular = circular;
addConsoleAction("adc_stats", printAdcDiagnostics);
}
#endif // HAL_USE_ADC
43 changes: 43 additions & 0 deletions firmware/hw_layer/adc/adc_diagnostics.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#pragma once

#include <cstdint>
#include "hal.h"

// Counts since boot, wrapping modulo 2^32 (about 5 days at 10 kHz). No runtime reset:
// each field has one serialized writer, and console readers use a locked snapshot.
struct AdcDiagnostics {
uint32_t started = 0;
uint32_t completed = 0;
uint32_t errors = 0;
uint32_t lastError = 0;
uint32_t skippedActive = 0;
uint32_t skippedComplete = 0;
uint32_t skippedNotReady = 0;
uint32_t skippedNoChannels = 0;
uint32_t skippedInvalidChannels = 0;
uint32_t skippedDisabled = 0;
uint32_t skippedPending = 0;
uint32_t processed = 0;
};

extern AdcDiagnostics fastAdcDiagnostics;
extern AdcDiagnostics knockAdcDiagnostics;

// Called only after the caller's existing readiness guard has rejected a start.
inline void recordAdcSkippedState(AdcDiagnostics& counters, adcstate_t state) {
if (state == ADC_ACTIVE) {
counters.skippedActive++;
} else if (state == ADC_COMPLETE) {
counters.skippedComplete++;
} else {
counters.skippedNotReady++;
}
}

struct AdcDiagnosticsSnapshot {
AdcDiagnostics fast;
AdcDiagnostics knock;
};

AdcDiagnosticsSnapshot getAdcDiagnostics();
void initAdcDiagnostics(bool fastIsCircular);
1 change: 1 addition & 0 deletions firmware/hw_layer/hw_layer.mk
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ HW_LAYER_EMS_CPP = \
$(PROJECT_DIR)/hw_layer/mmc_card_attach.cpp \
$(PROJECT_DIR)/hw_layer/mmc_card_mount.cpp \
$(PROJECT_DIR)/hw_layer/adc/adc_inputs.cpp \
$(PROJECT_DIR)/hw_layer/adc/adc_diagnostics.cpp \
$(PROJECT_DIR)/hw_layer/adc/adc_provider.cpp \
$(PROJECT_DIR)/hw_layer/adc/adc_subscription.cpp \
$(PROJECT_DIR)/hw_layer/adc/ads1015.cpp \
Expand Down
32 changes: 26 additions & 6 deletions firmware/hw_layer/ports/stm32/stm32_adc_v2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

#if HAL_USE_ADC

#include "adc_diagnostics.h"

/* Depth of the conversion buffer, channels are sampled X times each.*/
#define SLOW_ADC_OVERSAMPLE 8

Expand All @@ -23,6 +25,7 @@ static const GPTConfig fast_adc_timer_config = {GPT_FREQ_FAST, fast_adc_timer_ca
#endif

void portInitAdc() {
initAdcDiagnostics(false);
// Init slow ADC
adcStart(&ADCD1, NULL);

Expand Down Expand Up @@ -234,18 +237,24 @@ static Stm32AdcV2Provider provider;

static void adc_callback_fast(ADCDriver* adcp) {
// State may not be complete if we get a callback for "half done"
if (adcp->state == ADC_COMPLETE) {
if (adcIsBufferComplete(adcp)) {
fastAdcDiagnostics.completed++;
onFastAdcComplete(adcp->samples);
}

assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY);
}

static void fastAdcErrorCallback(ADCDriver*, adcerror_t error) {
fastAdcDiagnostics.errors++;
fastAdcDiagnostics.lastError = error;
}

ADCConversionGroup adcgrpcfgFast = {
.circular = FALSE,
.num_channels = 0,
.end_cb = adc_callback_fast,
.error_cb = nullptr,
.error_cb = fastAdcErrorCallback,
/* HW dependent part.*/
.cr1 = 0,
.cr2 = ADC_CR2_SWSTART,
Expand Down Expand Up @@ -320,18 +329,25 @@ auto& ADC_FAST_DEVICE = ADCD2;
static void fast_adc_timer_callback(GPTDriver*) {
chibios_rt::CriticalSectionLocker csl;

if (ADC_FAST_DEVICE.state != ADC_READY && ADC_FAST_DEVICE.state != ADC_COMPLETE &&
ADC_FAST_DEVICE.state != ADC_ERROR) {
// ADC_COMPLETE belongs to the completion callback; the HAL is not ready yet.
if (ADC_FAST_DEVICE.state != ADC_READY && ADC_FAST_DEVICE.state != ADC_ERROR) {
recordAdcSkippedState(fastAdcDiagnostics, ADC_FAST_DEVICE.state);
return;
}

if (adcgrpcfgFast.num_channels == 0 || adcgrpcfgFast.num_channels > maxFastChannels) {
// No channels configured (yet), don't attempt to sample
// with an invalid configuration
if (adcgrpcfgFast.num_channels == 0) {
fastAdcDiagnostics.skippedNoChannels++;
} else {
fastAdcDiagnostics.skippedInvalidChannels++;
}
return;
}

adcStartConversionI(&ADC_FAST_DEVICE, &adcgrpcfgFast, fastAdcSampleBuf, ADC_BUF_DEPTH_FAST);
fastAdcDiagnostics.started++;

assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY);
}
Expand All @@ -342,14 +358,18 @@ static void fast_adc_timer_callback(GPTDriver*) {
#include "knock_config.h"

static void knockCompletionCallback(ADCDriver* adcp) {
if (adcp->state == ADC_COMPLETE) {
if (adcIsBufferComplete(adcp)) {
knockAdcDiagnostics.completed++;
onKnockSamplingComplete();
}

assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY);
}

static void knockErrorCallback(ADCDriver*, adcerror_t) {}
static void knockErrorCallback(ADCDriver*, adcerror_t error) {
knockAdcDiagnostics.errors++;
knockAdcDiagnostics.lastError = error;
}

static const uint32_t smpr1 = ADC_SMPR1_SMP_AN10(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN11(KNOCK_SAMPLE_TIME) |
ADC_SMPR1_SMP_AN12(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN13(KNOCK_SAMPLE_TIME) |
Expand Down
27 changes: 22 additions & 5 deletions firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

#if HAL_USE_ADC

#include "adc_diagnostics.h"

#include "mpu_util.h"

// All ADCs should be running at 40MHz
Expand Down Expand Up @@ -47,9 +49,13 @@ static constexpr int H7_ADC_SHIFT_BITS = log2_int(H7_ADC_OVERSAMPLE);

// ADC3 is in the AHB4 domain, which is only accessible by the BDMA controller
// BDMA can only access AHB4, which means we have to put the buffers in SRAM4
__attribute__((section(".ram4"))) __attribute__((aligned(8192))) adcsample_t knockSampleBuffer[2048];
#if EFI_PROD_CODE
__attribute__((section(".ram4")))
#endif
__attribute__((aligned(8192))) adcsample_t knockSampleBuffer[2048];

void portInitAdc() {
initAdcDiagnostics(true);
{
void* base = &knockSampleBuffer;
static_assert(sizeof(knockSampleBuffer) == 8192);
Expand Down Expand Up @@ -84,13 +90,19 @@ float getMcuTemperature() {

static void adc_callback(ADCDriver* adcp) {
// State may not be complete if we get a callback for "half done"
if (adcp->state == ADC_COMPLETE) {
if (adcIsBufferComplete(adcp)) {
fastAdcDiagnostics.completed++;
onFastAdcComplete(adcp->samples);
}

assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY);
}

static void fastAdcErrorCallback(ADCDriver*, adcerror_t error) {
fastAdcDiagnostics.errors++;
fastAdcDiagnostics.lastError = error;
}

// ADC Clock is 25MHz
// 16.5 sampling + 7.5 conversion = 24 cycles per sample total
// 16 channels * 4x oversample = 64 samples per batch
Expand All @@ -107,7 +119,7 @@ static constexpr ADCConversionGroup convGroupSlow = {
.circular = true, // Continuous mode means we will auto re-trigger on every timer event
.num_channels = slowChannelCount,
.end_cb = adc_callback,
.error_cb = nullptr,
.error_cb = fastAdcErrorCallback,
.cfgr = ADC_CFGR_EXTEN_0 | (4 << ADC_CFGR_EXTSEL_Pos) | // External trigger ch4, rising edge: TIM3 TRGO
ADC_CFGR_OVRMOD, // OVRMOD=1 is required by H7 errata: ES0392 section 2.9.6. If OVRMOD is not set, it is
// possible for the secondary ADC's data to be shifted from where it was supposed to
Expand Down Expand Up @@ -214,6 +226,7 @@ bool readSlowAnalogInputs() {
// Oversampling and right-shift happen in hardware, so we can sample directly to the output buffer
// Pass the 32-bit view to the HAL - it will receive slowChannelCount/2 32-bit samples in dual mode
adcStartConversionI(&ADCD1, &convGroupSlow, sampleBuffer.samples32, 1);
fastAdcDiagnostics.started++;
}

constexpr uint32_t samplingRate = H7_ADC_SPEED;
Expand Down Expand Up @@ -295,14 +308,18 @@ static_assert((H7_KNOCK_OVERSAMPLE & (H7_KNOCK_OVERSAMPLE - 1)) == 0, "H7_KNOCK_
static constexpr int H7_KNOCK_ADC_SHIFT_BITS = log2_int(H7_KNOCK_OVERSAMPLE);

static void knockCompletionCallback(ADCDriver* adcp) {
if (adcp->state == ADC_COMPLETE) {
if (adcIsBufferComplete(adcp)) {
knockAdcDiagnostics.completed++;
onKnockSamplingComplete();
}

assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY);
}

static void knockErrorCallback(ADCDriver*, adcerror_t) {}
static void knockErrorCallback(ADCDriver*, adcerror_t error) {
knockAdcDiagnostics.errors++;
knockAdcDiagnostics.lastError = error;
}

static const uint32_t smpr1 = ADC_SMPR1_SMP_AN0(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN1(KNOCK_SAMPLE_TIME) |
ADC_SMPR1_SMP_AN2(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN3(KNOCK_SAMPLE_TIME) |
Expand Down
10 changes: 10 additions & 0 deletions unit_tests/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,13 @@ INCDIR += \


include $(UNIT_TESTS_DIR)/unit_test_rules.mk

include $(UNIT_TESTS_DIR)/adc_lifecycle/adc_lifecycle.mk

all: $(ADC_LIFECYCLE_BINS)

.PHONY: test
test: all
./$(BINARY_OUTPUT)
./build/adc_lifecycle_test
./build/adc_lifecycle_v4_test
Loading
Loading