diff --git a/src/drivers/power_monitor/ina226/ina226.cpp b/src/drivers/power_monitor/ina226/ina226.cpp index b47acd84131..429495bb4da 100644 --- a/src/drivers/power_monitor/ina226/ina226.cpp +++ b/src/drivers/power_monitor/ina226/ina226.cpp @@ -43,24 +43,21 @@ INA226::INA226(const I2CSPIDriverConfig &config, int battery_index) ModuleParams(nullptr), I2CSPIDriver(config), _battery(battery_index, this, SAMPLE_INTERVAL_US, battery_status_s::SOURCE_POWER_MODULE), - _sample_perf(perf_alloc(PC_ELAPSED, "ina226_read")), - _comms_errors(perf_alloc(PC_COUNT, "ina226_com_err")), - _collection_errors(perf_alloc(PC_COUNT, "ina226_collection_err")), - _bad_register_perf(perf_alloc(PC_COUNT, "ina226_bad_register")), - _reinit_perf(perf_alloc(PC_COUNT, "ina226_reinit")) + // On NuttX, I2C::init() rejects a bus running faster than the frequency the driver was started with + _trigger_write_min_us(config.bus_frequency > 0 ? TRIGGER_WRITE_BITS * 1'000'000 / config.bus_frequency : 0) { const float max_current = _param_ina226_current.get(); const float shunt_resistance = _param_ina226_shunt.get(); _current_lsb = max_current / 32768.f; // From datasheet: current_lsb = max_current / 2^15 - // CAL is a 16-bit register. Legal INA226_CURRENT × INA226_SHUNT combos can - // overflow it; converting that float to uint16_t is undefined. + // CAL is a 15-bit field (D15 is reserved). Legal INA226_CURRENT × INA226_SHUNT combos can + // overflow it, and a value that doesn't fit would never read back as written. const float denom = _current_lsb * shunt_resistance; const float cal = (denom > 0.f) ? (CAL_K / denom) : 0.f; - if ((cal < 1.f) || (cal > 65535.f)) { - PX4_ERR("INA226 calibration %.1f out of uint16 range (INA226_CURRENT=%.4f INA226_SHUNT=%.9f)", + if ((cal < 1.f) || (cal > CALIBRATION_MAX)) { + PX4_ERR("INA226 calibration %.1f out of range (INA226_CURRENT=%.4f INA226_SHUNT=%.9f)", (double)cal, (double)max_current, (double)shunt_resistance); _current_lsb = 0.f; _calibration = 0; @@ -69,7 +66,9 @@ INA226::INA226(const I2CSPIDriverConfig &config, int battery_index) _calibration = static_cast(cal); } - _config_value = MODE_SHUNT_BUS_CONT | VSHCT_588US | VBUSCT_588US | AVERAGES_64; + // Triggered: writing this value starts one conversion. The bus voltage LSB (1.25 mV) is coarse, + // so the shunt gets the longer conversion time. + _config_value = MODE_SHUNT_BUS_TRIG | VSHCT_1100US | VBUSCT_588US | AVERAGES_4; if (_calibration != 0) { // Publish an initial disconnected status so the first instance grabs uORB instance 0 immediately. @@ -84,8 +83,6 @@ INA226::~INA226() { perf_free(_sample_perf); perf_free(_comms_errors); - perf_free(_collection_errors); - perf_free(_bad_register_perf); perf_free(_reinit_perf); } @@ -132,52 +129,98 @@ void INA226::RunImpl() } _state = State::CONFIGURE; + _failing_since = 0; ScheduleDelayed(RESET_DELAY_US); return; } case State::CONFIGURE: { + // The CONFIGURATION write also triggers the first conversion. const bool ok = (probe() == PX4_OK) && (registerWrite(Register::CALIBRATION, _calibration) == PX4_OK) && (registerWrite(Register::CONFIGURATION, _config_value) == PX4_OK); if (!ok) { - _state = State::RESET; - ScheduleDelayed(INIT_RETRY_INTERVAL_US); + // Keep retrying every tick and only report the battery as disconnected (RESET) + // after DISCONNECT_DEBOUNCE_US without a published sample. + if (_failing_since == 0) { + _failing_since = start_time; + } + + if (start_time - _failing_since >= DISCONNECT_DEBOUNCE_US) { + perf_count(_reinit_perf); + PX4_WARN("consecutive failures, resetting"); + _state = State::RESET; + ScheduleNow(); + + } else { + ScheduleDelayed(SAMPLE_INTERVAL_US); + } + return; } - // Communication success - _consecutive_failures = 0; - _next_reg_to_check = 0; + _trigger_time = hrt_absolute_time(); + _last_config_check = start_time; _state = State::MEASURE; - // Wait one full sample period + some margin - ScheduleDelayed(SAMPLE_INTERVAL_US + 5_ms); + // The first tick comes one interval later, when the first conversion is complete. + ScheduleOnInterval(SAMPLE_INTERVAL_US, SAMPLE_INTERVAL_US); return; } case State::MEASURE: { - if (collect() == PX4_OK) { - _consecutive_failures = 0; + const int ret = collect(); - } else { - perf_count(_collection_errors); + if (ret == -EAGAIN) { + // The previous conversion can't be done yet (this tick came early): read it next tick. + return; + } - if (++_consecutive_failures >= MAX_CONSECUTIVE_FAILURES) { + if (ret != PX4_OK) { + // The device may have lost power and come back with its reset configuration, and + // its result registers read zero until the first conversion after that. Write the + // configuration again before the next read instead of publishing such a sample. + if (_failing_since == 0) { + _failing_since = start_time; + } + + ScheduleClear(); + + if (start_time - _failing_since >= DISCONNECT_DEBOUNCE_US) { perf_count(_reinit_perf); - _state = State::RESET; - _consecutive_failures = 0; PX4_WARN("consecutive failures, resetting"); + _state = State::RESET; + ScheduleNow(); + + } else { + _state = State::CONFIGURE; + ScheduleDelayed(SAMPLE_INTERVAL_US); + } + + return; + } + + _failing_since = 0; + + // Checked after publishing so it doesn't add to the sample latency. A failed + // read here is only counted as a comms error; the sample reads above decide + // whether the device is gone. + if (start_time - _last_config_check >= CONFIG_CHECK_INTERVAL_US) { + _last_config_check = start_time; + + if (checkCalibration() == -EBADMSG) { + // The device lost its configuration (e.g. brown-out while plugging the battery) + // but is still responding: write it again without reporting the battery as + // disconnected, which the commander would treat as a battery failure in flight. + perf_count(_reinit_perf); + PX4_WARN("configuration lost, reconfiguring"); + ScheduleClear(); + _state = State::CONFIGURE; ScheduleNow(); - return; } } - const hrt_abstime elapsed = hrt_elapsed_time(&start_time); - const hrt_abstime scheduled_time = elapsed < SAMPLE_INTERVAL_US ? SAMPLE_INTERVAL_US - elapsed : 0; - - ScheduleDelayed(scheduled_time); return; } } @@ -185,17 +228,28 @@ void INA226::RunImpl() int INA226::collect() { + // Ticks are on a fixed hrt grid, so a tick after a late one comes early. Triggering + // before the previous conversion is done would restart it and we would read (and + // publish) the one before it again. _trigger_time is taken after the previous trigger + // write, so that conversion started before it, and the next one starts when the write + // below ends, at least _trigger_write_min_us from now. + if (hrt_elapsed_time(&_trigger_time) + _trigger_write_min_us < CONVERSION_TIME_MAX_US) { + return -EAGAIN; + } + perf_begin(_sample_perf); - // Verify one config register per cycle - const bool config_ok = checkConfigurationRotating(); - - if (!config_ok) { - perf_count(_bad_register_perf); + // Start the next conversion first. The result registers keep the previous, completed + // conversion until the new one finishes, so reading them right after the trigger returns + // the sample triggered one tick ago. This gives a fixed sample latency and the full tick + // for the conversion. + if (registerWrite(Register::CONFIGURATION, _config_value) != PX4_OK) { perf_end(_sample_perf); return PX4_ERROR; } + _trigger_time = hrt_absolute_time(); + int16_t bus_voltage = 0; int16_t current = 0; @@ -230,31 +284,27 @@ int INA226::probe() return PX4_OK; } -bool INA226::checkConfigurationRotating() +int INA226::checkCalibration() { - const struct { - Register reg; - uint16_t expected; - uint16_t mask; - } checks[] = { - // CONFIGURATION D15 (RST) self-clears; D14:D12 are reserved and D14 reads back as 1. - { Register::CONFIGURATION, _config_value, 0x0FFF }, - { Register::CALIBRATION, _calibration, 0xFFFF }, - }; - - const auto &check = checks[_next_reg_to_check]; + // CONFIGURATION is not checked: it is rewritten every tick to trigger the next conversion. uint16_t actual = 0; - if (registerRead(check.reg, actual) != PX4_OK) { - return false; + if (registerRead(Register::CALIBRATION, actual) != PX4_OK) { + return -EIO; } - if ((actual & check.mask) != (check.expected & check.mask)) { - return false; + if (actual != _calibration) { + // I2C has no CRC: confirm the mismatch with a second read before acting on it. + if (registerRead(Register::CALIBRATION, actual) != PX4_OK) { + return -EIO; + } + + if (actual != _calibration) { + return -EBADMSG; + } } - _next_reg_to_check = (_next_reg_to_check + 1) % (sizeof(checks) / sizeof(checks[0])); - return true; + return PX4_OK; } int INA226::registerRead(Register reg, uint16_t &value) @@ -319,8 +369,6 @@ void INA226::print_status() PX4_INFO("sample interval: %llu us", SAMPLE_INTERVAL_US); perf_print_counter(_sample_perf); perf_print_counter(_comms_errors); - perf_print_counter(_collection_errors); - perf_print_counter(_bad_register_perf); perf_print_counter(_reinit_perf); } @@ -365,6 +413,9 @@ Multiple instances can run simultaneously on separate buses or different I2C add If the device is not powered at startup, pass `-k` (keep_running) and the driver will retry initialization every 500 ms so the battery can be plugged in later. + +The device is sampled at 100 Hz. Every sample is triggered by the driver, so the latency +from the measurement to the publication is the same for every sample. )DESCR_STR"); PRINT_MODULE_USAGE_NAME("ina226", "driver"); diff --git a/src/drivers/power_monitor/ina226/ina226.h b/src/drivers/power_monitor/ina226/ina226.h index afe27d2dfeb..81f88ec66e6 100644 --- a/src/drivers/power_monitor/ina226/ina226.h +++ b/src/drivers/power_monitor/ina226/ina226.h @@ -54,16 +54,23 @@ static constexpr uint16_t DIEID = 0x2260; // INA226 die + revision 0 // Measurement scaling (from datasheet) static constexpr float V_LSB = 1.25e-3f; // bus voltage: V per LSB static constexpr float CAL_K = 5.12e-3f; // CALIBRATION = CAL_K / (current_lsb * R_SHUNT) +static constexpr float CALIBRATION_MAX = 0x7fff; // CALIBRATION is a 15 bit field // Sample timing -// Default ADC config produces one averaged sample every (588us + 588us) * 64 = 75.264 ms. Poll a hair slower. -static constexpr hrt_abstime SAMPLE_INTERVAL_US = 100_ms; +// Each tick triggers one conversion, (1100us shunt + 588us bus) * 4 averages = 6.752 ms, read on the next tick. +static constexpr hrt_abstime SAMPLE_INTERVAL_US = 10_ms; +// Worst case from the trigger to a completed conversion: maximum conversion times from the datasheet, +// (1210us + 646us) * 4, plus the 40us recovery from power-down. +static constexpr hrt_abstime CONVERSION_TIME_MAX_US = (1210 + 646) * 4 + 40; +// The conversion starts when the trigger write ends, at least this many bit times after the write +// starts: address, register pointer and two data bytes, not counting the ACKs. +static constexpr uint32_t TRIGGER_WRITE_BITS = 32; // Recovery / robustness timing static constexpr hrt_abstime INIT_RETRY_INTERVAL_US = 500_ms; static constexpr hrt_abstime RESET_DELAY_US = 1_ms; static constexpr hrt_abstime DISCONNECT_DEBOUNCE_US = 2_s; -static constexpr uint8_t MAX_CONSECUTIVE_FAILURES = DISCONNECT_DEBOUNCE_US / SAMPLE_INTERVAL_US; +static constexpr hrt_abstime CONFIG_CHECK_INTERVAL_US = 100_ms; // Register map (subset used by this driver) enum class Register : uint8_t { @@ -149,14 +156,14 @@ private: UNINITIALIZED, // I2C::init() not yet called successfully — retry until it does RESET, // soft-reset the device, then transition to CONFIGURE CONFIGURE, // write CALIBRATION / CONFIGURATION, then transition to MEASURE - MEASURE, // steady-state: read BUSVOLTAGE / CURRENT, publish, repeat + MEASURE, // steady-state: trigger, read BUSVOLTAGE / CURRENT, publish, repeat }; int collect(); - // Rotates through the configuration registers one per call. Returns false - // if a read fails or the value doesn't match what we wrote. - bool checkConfigurationRotating(); + // Returns PX4_OK, -EIO if the read fails, or -EBADMSG if CALIBRATION doesn't match + // what we wrote (the device has been reset behind our back). + int checkCalibration(); int registerRead(ina226::Register reg, uint16_t &value); int registerWrite(ina226::Register reg, uint16_t value); @@ -165,9 +172,11 @@ private: Battery _battery; State _state{State::UNINITIALIZED}; - uint8_t _consecutive_failures{0}; + hrt_abstime _failing_since{0}; // first failure of the current run of failures, 0 if none - uint8_t _next_reg_to_check{0}; + hrt_abstime _last_config_check{0}; + hrt_abstime _trigger_time{0}; // when the last conversion was triggered + const hrt_abstime _trigger_write_min_us; // shortest time the trigger write takes on the bus // Configuration computed from params float _current_lsb{0.f}; @@ -175,11 +184,9 @@ private: uint16_t _config_value{0}; // CONFIGURATION register value we wrote // Perf counters - perf_counter_t _sample_perf; - perf_counter_t _comms_errors; - perf_counter_t _collection_errors; - perf_counter_t _bad_register_perf; - perf_counter_t _reinit_perf; + perf_counter_t _sample_perf{perf_alloc(PC_ELAPSED, "ina226_read")}; + perf_counter_t _comms_errors{perf_alloc(PC_COUNT, "ina226_com_err")}; + perf_counter_t _reinit_perf{perf_alloc(PC_COUNT, "ina226_reinit")}; DEFINE_PARAMETERS( (ParamFloat) _param_ina226_current, diff --git a/src/drivers/power_monitor/ina228/CMakeLists.txt b/src/drivers/power_monitor/ina228/CMakeLists.txt index 1a5ba76beba..74f59783bea 100644 --- a/src/drivers/power_monitor/ina228/CMakeLists.txt +++ b/src/drivers/power_monitor/ina228/CMakeLists.txt @@ -33,10 +33,7 @@ px4_add_module( MODULE drivers__ina228 MAIN ina228 - COMPILE_FLAGS - -Wno-cast-align # TODO: fix and enable SRCS - ina228_main.cpp ina228.cpp MODULE_CONFIG ina228_params.yaml diff --git a/src/drivers/power_monitor/ina228/ina228.cpp b/src/drivers/power_monitor/ina228/ina228.cpp index 0a7b3750257..8e81389a6a5 100644 --- a/src/drivers/power_monitor/ina228/ina228.cpp +++ b/src/drivers/power_monitor/ina228/ina228.cpp @@ -1,6 +1,6 @@ /**************************************************************************** * - * Copyright (c) 2021 PX4 Development Team. All rights reserved. + * Copyright (C) 2021-2026 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -31,397 +31,513 @@ * ****************************************************************************/ -/** - * @file ina228.cpp - * @author David Sidrane - * - * Driver for the I2C attached INA228 - */ - #include "ina228.h" +#include +#include -INA228::INA228(const I2CSPIDriverConfig &config, int battery_index) : - I2C(config), - ModuleParams(nullptr), - I2CSPIDriver(config), - _sample_perf(perf_alloc(PC_ELAPSED, "ina228_read")), - _comms_errors(perf_alloc(PC_COUNT, "ina228_com_err")), - _collection_errors(perf_alloc(PC_COUNT, "ina228_collection_err")), - _measure_errors(perf_alloc(PC_COUNT, "ina228_measurement_err")), - _battery(battery_index, this, INA228_SAMPLE_INTERVAL_US, battery_status_s::SOURCE_POWER_MODULE) +using namespace ina228; + +static constexpr uint32_t BUS_CLOCK_HZ = 100'000; + +// Each tick triggers one conversion of bus voltage, shunt voltage and temperature: +// (540 + 1052 + 50) us x 4 averages = 6.568 ms, read on the next tick. The shunt gets the longer +// conversion time; the rest of the tick is margin for scheduling latency (see collect()). +static constexpr uint16_t ADC_CONFIG = MODE_TEMP_SHUNT_BUS_TRIG | VBUSCT_540US | VSHCT_1052US | VTCT_50US | AVERAGES_4; +static constexpr uint32_t CONVERSION_TIME_US = (540 + 1052 + 50) * 4; +static constexpr hrt_abstime SAMPLE_INTERVAL_US = 10_ms; + +// Worst case from the trigger to a completed conversion: the internal oscillator running +// 1 % slow, plus the wake-up from shutdown. +static constexpr hrt_abstime CONVERSION_TIME_MAX_US = (CONVERSION_TIME_US * 100 + 98) / 99 + WAKEUP_TIME_US; + +// The conversion starts when the trigger write ends, at least this many bit times after the write +// starts: address, register pointer and two data bytes, not counting the ACKs. +static constexpr uint32_t TRIGGER_WRITE_BITS = 32; + +// Recovery / robustness timing +static constexpr hrt_abstime INIT_RETRY_INTERVAL_US = 500_ms; +static constexpr hrt_abstime RESET_DELAY_US = 1_ms; // datasheet specifies 300us. Give some margin +static constexpr hrt_abstime DISCONNECT_DEBOUNCE_US = 2_s; +static constexpr hrt_abstime CONFIG_CHECK_INTERVAL_US = 100_ms; + +INA228::INA228(const I2CSPIDriverConfig &config, int battery_index) + : I2C(config), + ModuleParams(nullptr), + I2CSPIDriver(config), + _battery(battery_index, this, SAMPLE_INTERVAL_US, battery_status_s::SOURCE_POWER_MODULE), + // On NuttX, I2C::init() rejects a bus running faster than the frequency the driver was started with + _trigger_write_min_us(config.bus_frequency > 0 ? TRIGGER_WRITE_BITS * 1'000'000 / config.bus_frequency : 0) { const float max_current = _param_ina228_current.get(); - const float rshunt = _param_ina228_shunt.get(); + const float shunt_resistance = _param_ina228_shunt.get(); - // According to page 8.2.2.1, page 36/48 of the INA228 interface datasheet (Rev. A), - // the requirement is: R_SHUNT < V_SENSE_MAX / I_MAX - // therefore: R_SHUNT * I_MAX < V_SENSE_MAX - // and so if V_SENSE_MAX is bigger, we need to use the bigger ADC range to avoid - // the device from capping the measured current. + // Pick the ADC range so the device doesn't clip at the configured max current. + // Datasheet §8.2.2.1: R_SHUNT * I_MAX < V_SENSE_MAX. + const float v_sense_max = shunt_resistance * max_current; + const bool use_low_range = (v_sense_max <= ADCRANGE_LOW_V_SENSE); + _config_value = use_low_range ? RANGE_LOW : RANGE_HIGH; - const float v_sense_max = rshunt * max_current; + _current_lsb = max_current / CURRENT_LSB_DIV; + float shunt_calibration = SHUNT_CAL_K * _current_lsb * shunt_resistance; - if (v_sense_max > INA228_ADCRANGE_LOW_V_SENSE) { - _range = INA228_ADCRANGE_HIGH; - - } else { - _range = INA228_ADCRANGE_LOW; + if (use_low_range) { + shunt_calibration *= 4.f; } - param_t ph = param_find("INA228_CONFIG"); - int32_t value = INA228_ADCCONFIG; - _config = (uint16_t)value; - - if (ph != PARAM_INVALID && param_get(ph, &value) == PX4_OK) { - _config = (uint16_t)value; + if (shunt_calibration > SHUNT_CAL_MAX) { + PX4_ERR("SHUNT_CAL %.0f out of range, check INA228_CURRENT / INA228_SHUNT", (double)shunt_calibration); + shunt_calibration = SHUNT_CAL_MAX; + // keep the current scale consistent with the calibration actually written + _current_lsb = shunt_calibration / (SHUNT_CAL_K * shunt_resistance * (use_low_range ? 4.f : 1.f)); } - _mode_triggered = ((_config & INA228_MODE_MASK) >> INA228_MODE_SHIFTS) <= - ((INA228_MODE_TEMP_SHUNT_BUS_TRIG & INA228_MODE_MASK) >> - INA228_MODE_SHIFTS); + _shunt_calibration = static_cast(shunt_calibration); - _current_lsb = max_current / DN_MAX; - _power_lsb = 3.2f * _current_lsb; - - // We need to publish immediately, to guarantee that the first instance of the driver publishes to uORB instance 0 - setConnected(false); + // Publish an initial disconnected status so the first instance grabs uORB instance 0 immediately. _battery.updateAndPublishBatteryStatus(hrt_absolute_time()); + // Let the lower I2C layer absorb transient bus errors before we see them. I2C::_retries = 5; } INA228::~INA228() { - /* free perf counters */ perf_free(_sample_perf); perf_free(_comms_errors); - perf_free(_collection_errors); - perf_free(_measure_errors); + perf_free(_reinit_perf); } -int INA228::read(uint8_t address, int16_t &data) +int INA228::init() { - // read desired little-endian value via I2C - int16_t received_bytes; - const int ret = transfer(&address, 1, (uint8_t *)&received_bytes, sizeof(received_bytes)); - - if (ret == PX4_OK) { - data = swap16(received_bytes); - - } else { - perf_count(_comms_errors); - PX4_DEBUG("i2c::transfer returned %d", ret); + if (I2C::init() != PX4_OK) { + return PX4_ERROR; } - return ret; + _state = State::RESET; + return PX4_OK; } -int INA228::read(uint8_t address, int32_t &data) +void INA228::RunImpl() { - // read desired 24 bit value via I2C - int32_t received_bytes{0}; - const int ret = transfer(&address, 1, (uint8_t *)&received_bytes, sizeof(received_bytes) - 1); + const hrt_abstime now = hrt_absolute_time(); - if (ret == PX4_OK) { - data = swap32(received_bytes) >> ((32 - 24) + 4); // Convert to 20bit value + if (_parameter_update_sub.updated()) { + parameter_update_s parameter_update; + _parameter_update_sub.copy(¶meter_update); + // INA228_* are reboot-required; this is for the Battery (BATn_*) parameters. + updateParams(); + } - // Handle negative 20bit twos complement - if (data & 0x80000) { - data = -((0x000FFFFF & ~data) + 1); + switch (_state) { + case State::UNINITIALIZED: { + if (init() != PX4_OK) { + _battery.updateAndPublishBatteryStatus(now); + ScheduleDelayed(INIT_RETRY_INTERVAL_US); + return; + } + + // init() advanced us to State::RESET + ScheduleNow(); + return; } - } else { - perf_count(_comms_errors); - PX4_DEBUG("i2c::transfer returned %d", ret); + case State::RESET: { + _battery.setConnected(false); + _battery.updateVoltage(0.f); + _battery.updateCurrent(-1.f); + _battery.updateTemperature(NAN); + _battery.updateAndPublishBatteryStatus(now); + + if (registerWrite(Register::CONFIG, RST) != PX4_OK) { + ScheduleDelayed(INIT_RETRY_INTERVAL_US); + return; + } + + _state = State::CONFIGURE; + _failing_since = 0; + ScheduleDelayed(RESET_DELAY_US); + return; + } + + case State::CONFIGURE: { + // The ADCCONFIG write also triggers the first conversion. + const bool ok = (probe() == PX4_OK) && + (registerWrite(Register::SHUNT_CAL, _shunt_calibration) == PX4_OK) && + (registerWrite(Register::CONFIG, _config_value) == PX4_OK) && + (registerWrite(Register::ADCCONFIG, ADC_CONFIG) == PX4_OK); + + if (!ok) { + // Keep retrying every tick and only report the battery as disconnected (RESET) + // after DISCONNECT_DEBOUNCE_US without a published sample. + if (_failing_since == 0) { + _failing_since = now; + } + + if (now - _failing_since >= DISCONNECT_DEBOUNCE_US) { + perf_count(_reinit_perf); + PX4_WARN("consecutive failures, resetting"); + _state = State::RESET; + ScheduleNow(); + + } else { + ScheduleDelayed(SAMPLE_INTERVAL_US); + } + + return; + } + + _trigger_time = hrt_absolute_time(); + _next_reg_to_check = 0; + _last_config_check = now; + _state = State::MEASURE; + + // The first tick comes one interval later, when the first conversion is complete. + ScheduleOnInterval(SAMPLE_INTERVAL_US, SAMPLE_INTERVAL_US); + return; + } + + case State::MEASURE: { + const int ret = collect(); + + if (ret == -EAGAIN) { + // The previous conversion can't be done yet (this tick came early): read it next tick. + return; + } + + if (ret != PX4_OK) { + // The device may have lost power and come back with its reset configuration, and + // its result registers read zero until the first conversion after that. Write the + // configuration again before the next read instead of publishing such a sample. + if (_failing_since == 0) { + _failing_since = now; + } + + ScheduleClear(); + + if (now - _failing_since >= DISCONNECT_DEBOUNCE_US) { + perf_count(_reinit_perf); + PX4_WARN("consecutive failures, resetting"); + _state = State::RESET; + ScheduleNow(); + + } else { + _state = State::CONFIGURE; + ScheduleDelayed(SAMPLE_INTERVAL_US); + } + + return; + } + + _failing_since = 0; + + // Checked after publishing so it doesn't add to the sample latency. A failed + // read here is only counted as a comms error; the sample reads above decide + // whether the device is gone. + if (now - _last_config_check >= CONFIG_CHECK_INTERVAL_US) { + _last_config_check = now; + + if (checkConfigurationRotating() == -EBADMSG) { + // The device lost its configuration (e.g. brown-out while plugging the battery) + // but is still responding: write it again without reporting the battery as + // disconnected, which the commander would treat as a battery failure in flight. + perf_count(_reinit_perf); + PX4_WARN("configuration lost, reconfiguring"); + ScheduleClear(); + _state = State::CONFIGURE; + ScheduleNow(); + } + } + + return; + } + } +} + +int INA228::collect() +{ + // Ticks are on a fixed hrt grid, so a tick after a late one comes early. Triggering + // before the previous conversion is done would restart it and we would read (and + // publish) the one before it again. _trigger_time is taken after the previous trigger + // write, so that conversion started before it, and the next one starts when the write + // below ends, at least _trigger_write_min_us from now. + if (hrt_elapsed_time(&_trigger_time) + _trigger_write_min_us < CONVERSION_TIME_MAX_US) { + return -EAGAIN; } - return ret; -} + perf_begin(_sample_perf); -int INA228::read(uint8_t address, int64_t &data) -{ - // read desired 40 bit little-endian value via I2C - int64_t received_bytes{0}; - const int ret = transfer(&address, 1, (uint8_t *)&received_bytes, sizeof(received_bytes) - 3); - - if (ret == PX4_OK) { - data = swap64(received_bytes); - - } else { - perf_count(_comms_errors); - PX4_DEBUG("i2c::transfer returned %d", ret); + // Start the next conversion first. The result registers keep the previous, completed + // conversion until the new one finishes (datasheet §7.3.4), so reading them right after + // the trigger returns the sample triggered one tick ago. This gives a fixed sample latency + // and the full tick for the conversion. + if (registerWrite(Register::ADCCONFIG, ADC_CONFIG) != PX4_OK) { + perf_end(_sample_perf); + return PX4_ERROR; } - return ret; -} + _trigger_time = hrt_absolute_time(); -int INA228::read(uint8_t address, uint16_t &data) -{ - // read desired little-endian value via I2C - uint16_t received_bytes; - const int ret = transfer(&address, 1, (uint8_t *)&received_bytes, sizeof(received_bytes)); + int32_t bus_voltage = 0; + int32_t current = 0; + uint16_t temperature = 0; - if (ret == PX4_OK) { - data = swap16(received_bytes); + const bool reads_ok = (registerRead24(Register::VS_BUS, bus_voltage) == PX4_OK) + && (registerRead24(Register::CURRENT, current) == PX4_OK) + && (registerRead(Register::DIETEMP, temperature) == PX4_OK); - } else { - perf_count(_comms_errors); - PX4_DEBUG("i2c::transfer returned %d", ret); + if (reads_ok) { + _battery.setConnected(true); + _battery.updateVoltage(static_cast(bus_voltage) * V_LSB); + _battery.updateCurrent(static_cast(current) * _current_lsb); + _battery.updateTemperature(static_cast(static_cast(temperature)) * T_LSB); + _battery.updateAndPublishBatteryStatus(hrt_absolute_time()); } - return ret; + perf_end(_sample_perf); + return reads_ok ? PX4_OK : PX4_ERROR; } -int INA228::write(uint8_t address, uint16_t value) +int INA228::probe() { - uint8_t data[3] = {address, ((uint8_t)((value & 0xff00) >> 8)), (uint8_t)(value & 0xff)}; - return transfer(data, sizeof(data), nullptr, 0); -} + uint16_t value = 0; -int INA228::write(uint8_t address, int16_t value) -{ - uint8_t data[3] = {address, ((uint8_t)((value & 0xff00) >> 8)), (uint8_t)(value & 0xff)}; - return transfer(data, sizeof(data), nullptr, 0); -} - -int INA228::write(uint8_t address, int32_t value) -{ - uint8_t data[4] = {address, ((uint8_t)((value & 0xff0000) >> 16)), ((uint8_t)((value & 0xff00) >> 8)), (uint8_t)(value & 0xff)}; - return transfer(data, sizeof(data), nullptr, 0); -} - -int INA228::write(uint8_t address, int64_t value) -{ - uint8_t data[6] = {address, ((uint8_t)((value & 0xff000000) >> 32)), ((uint8_t)((value & 0xff0000) >> 24)), ((uint8_t)((value & 0xff00) >> 16)), ((uint8_t)((value & 0xff00) >> 8)), (uint8_t)(value & 0xff)}; - return transfer(data, sizeof(data), nullptr, 0); -} - -int -INA228::init() -{ - int ret = PX4_ERROR; - - /* do I2C init (and probe) first */ - if (I2C::init() != PX4_OK) { - return ret; - } - - write(INA228_REG_CONFIG, (uint16_t)(INA228_RST_RESET | _range)); - - _cal = INA228_CONST * _current_lsb * _param_ina228_shunt.get(); - - if (_range == INA228_ADCRANGE_LOW) { - _cal *= 4; - } - - if (write(INA228_REG_SHUNTCAL, _cal) < 0) { - return -3; - } - - // Set the CONFIG for max I - - write(INA228_REG_CONFIG, (uint16_t) _range); - - // If we run in continuous mode then start it here - - - if (!_mode_triggered) { - - ret = write(INA228_REG_ADCCONFIG, _config); - - } else { - ret = PX4_OK; - } - - start(); - _sensor_ok = true; - - _initialized = ret == PX4_OK; - return ret; -} - -int -INA228::force_init() -{ - int ret = init(); - - start(); - - return ret; -} - -int -INA228::probe() -{ - uint16_t value{0}; - - if (read(INA228_MANUFACTURER_ID, value) != PX4_OK || value != INA228_MFG_ID_TI) { + if (registerRead(Register::MANUFACTURER_ID, value) != PX4_OK || value != MANFID) { PX4_DEBUG("probe mfgid %d", value); - return -1; + return PX4_ERROR; } - if (read(INA228_DEVICE_ID, value) != PX4_OK || INA228_DEVICEID(value) != INA228_MFG_DIE) { + if (registerRead(Register::DEVICE_ID, value) != PX4_OK || ((value & DEVICE_ID_MASK) >> DEVICE_ID_SHIFT) != DIEID) { PX4_DEBUG("probe die id %d", value); - return -1; + return PX4_ERROR; } return PX4_OK; } -int -INA228::measure() +int INA228::checkConfigurationRotating() { - int ret = PX4_OK; + const struct { + Register reg; + uint16_t expected; + } checks[] = { + { Register::CONFIG, _config_value }, + { Register::SHUNT_CAL, _shunt_calibration }, + }; - if (_mode_triggered) { - ret = write(INA228_REG_ADCCONFIG, _config); + // ADCCONFIG is not checked: it is rewritten every tick to trigger the next conversion. + const uint8_t num_checks = sizeof(checks) / sizeof(checks[0]); - if (ret < 0) { - perf_count(_comms_errors); - PX4_DEBUG("i2c::transfer returned %d", ret); + const auto &check = checks[_next_reg_to_check]; + uint16_t actual = 0; + + if (registerRead(check.reg, actual) != PX4_OK) { + return -EIO; + } + + if (actual != check.expected) { + // I2C has no CRC: confirm the mismatch with a second read before acting on it. + if (registerRead(check.reg, actual) != PX4_OK) { + return -EIO; } + + if (actual != check.expected) { + _last_readback[_next_reg_to_check] = actual; + return -EBADMSG; + } + } + + _last_readback[_next_reg_to_check] = actual; + _next_reg_to_check = (_next_reg_to_check + 1) % num_checks; + return PX4_OK; +} + +int INA228::registerRead(Register reg, uint16_t &value) +{ + uint8_t address = static_cast(reg); + uint8_t buf[2] {}; + + const int ret = transfer(&address, 1, buf, sizeof(buf)); + + if (ret == PX4_OK) { + value = (buf[0] << 8) | buf[1]; + + } else { + perf_count(_comms_errors); } return ret; } -int -INA228::collect() +int INA228::registerRead24(Register reg, int32_t &value) { - perf_begin(_sample_perf); + uint8_t address = static_cast(reg); + uint8_t buf[3] {}; - if (_parameter_update_sub.updated()) { - // Read from topic to clear updated flag - parameter_update_s parameter_update; - _parameter_update_sub.copy(¶meter_update); + const int ret = transfer(&address, 1, buf, sizeof(buf)); - updateParams(); - } - - // read from the sensor - // Note: If the power module is connected backwards, then the values of _power, _current, and _shunt will be negative but otherwise valid. - bool success{true}; - success = success && (read(INA228_REG_VSBUS, _bus_voltage) == PX4_OK); - // success = success && (read(INA228_REG_POWER, _power) == PX4_OK); - success = success && (read(INA228_REG_CURRENT, _current) == PX4_OK); - //success = success && (read(INA228_REG_VSHUNT, _shunt) == PX4_OK); - success = success && (read(INA228_REG_DIETEMP, _temperature) == PX4_OK); - - if (setConnected(success)) { - _battery.updateVoltage(static_cast(_bus_voltage * INA228_VSCALE)); - _battery.updateCurrent(static_cast(_current * _current_lsb)); - _battery.updateTemperature(static_cast(_temperature * INA228_TSCALE)); - } - - _battery.updateAndPublishBatteryStatus(hrt_absolute_time()); - - perf_end(_sample_perf); - - if (success) { - return PX4_OK; + if (ret == PX4_OK) { + // 20 bit two's complement result in bits 23..4 + const uint32_t raw = (static_cast(buf[0]) << 24) | (static_cast(buf[1]) << 16) + | (static_cast(buf[2]) << 8); + value = static_cast(raw) >> 12; } else { - return PX4_ERROR; + perf_count(_comms_errors); } + + return ret; } -void -INA228::start() +int INA228::registerWrite(Register reg, uint16_t value) { - ScheduleClear(); + const uint8_t buf[3] = { + static_cast(reg), + static_cast((value >> 8) & 0xff), + static_cast(value & 0xff), + }; - /* reset the report ring and state machine */ - _collect_phase = false; + const int ret = transfer(buf, sizeof(buf), nullptr, 0); - _measure_interval = INA228_CONVERSION_INTERVAL; - - /* schedule a cycle to start things */ - ScheduleDelayed(5); -} - -void -INA228::RunImpl() -{ - if (_initialized) { - if (_collect_phase) { - /* perform collection */ - if (collect() != PX4_OK) { - perf_count(_collection_errors); - /* if error restart the measurement state machine */ - start(); - return; - } - - /* next phase is measurement */ - _collect_phase = !_mode_triggered; - - if (_measure_interval > INA228_CONVERSION_INTERVAL) { - /* schedule a fresh cycle call when we are ready to measure again */ - ScheduleDelayed(_measure_interval - INA228_CONVERSION_INTERVAL); - return; - } - } - - /* Measurement phase */ - - /* Perform measurement */ - if (measure() != PX4_OK) { - perf_count(_measure_errors); - } - - /* next phase is collection */ - _collect_phase = true; - - /* schedule a fresh cycle call when the measurement is done */ - ScheduleDelayed(INA228_CONVERSION_INTERVAL); - - } else { - setConnected(false); - _battery.updateAndPublishBatteryStatus(hrt_absolute_time()); - - if (init() != PX4_OK) { - ScheduleDelayed(INA228_INIT_RETRY_INTERVAL_US); - } - } -} - -bool INA228::setConnected(bool state) -{ - // Filter out brief I2C failures for 2s - if (state) { - _connected = INA228_SAMPLE_FREQUENCY_HZ * 2; - - } else if (_connected > 0) { - _connected--; + if (ret != PX4_OK) { + perf_count(_comms_errors); } - if (_connected > 0) { - _battery.setConnected(true); - - } else { - _battery.setConnected(false); - _battery.updateVoltage(0); - _battery.updateCurrent(0); - _battery.updateTemperature(0); - } - - return state; + return ret; } -void -INA228::print_status() +void INA228::print_status() { I2CSPIDriverBase::print_status(); - if (_initialized) { - perf_print_counter(_sample_perf); - perf_print_counter(_comms_errors); + const char *state_str = "?"; - printf("poll interval: %u \n", _measure_interval); + switch (_state) { + case State::UNINITIALIZED: + state_str = "UNINITIALIZED"; + break; + + case State::RESET: + state_str = "RESET"; + break; + + case State::CONFIGURE: + state_str = "CONFIGURE"; + break; + + case State::MEASURE: + state_str = "MEASURE"; + break; + } + + PX4_INFO("state: %s", state_str); + PX4_INFO("sample interval: %" PRIu64 " us, ADC_CONFIG: 0x%04X", SAMPLE_INTERVAL_US, ADC_CONFIG); + PX4_INFO("readback CONFIG: 0x%04X, SHUNT_CAL: 0x%04X", _last_readback[0], _last_readback[1]); + + perf_print_counter(_sample_perf); + perf_print_counter(_comms_errors); + perf_print_counter(_reinit_perf); +} + +I2CSPIDriverBase *INA228::instantiate(const I2CSPIDriverConfig &config, int /*runtime_instance*/) +{ + INA228 *instance = new INA228(config, config.custom1); + + if (instance == nullptr) { + PX4_ERR("alloc failed"); + return nullptr; + } + + if (instance->init() == PX4_OK) { + instance->ScheduleNow(); + + } else if (config.keep_running) { + // Driver stays alive even if the device isn't powered yet; RunImpl will retry. + PX4_INFO("ina228 init failed on bus %d, will retry every %u ms.", config.bus, + static_cast(INIT_RETRY_INTERVAL_US / 1000)); + instance->ScheduleDelayed(INIT_RETRY_INTERVAL_US); } else { - PX4_INFO("Device not initialized. Retrying every %d ms until battery is plugged in.", - INA228_INIT_RETRY_INTERVAL_US / 1000); + delete instance; + return nullptr; } + + return instance; +} + +void INA228::print_usage() +{ + PRINT_MODULE_DESCRIPTION( + R"DESCR_STR( +### Description +Driver for the Texas Instruments INA228 power monitor. + +Multiple instances can run simultaneously on separate buses or different I2C addresses. + +If the device is not powered at startup, pass `-k` (keep_running) and the driver +will retry initialization every 500 ms so the battery can be plugged in later. + +The device is sampled at 100 Hz. Every sample is triggered by the driver, so the latency +from the measurement to the publication is the same for every sample. The configuration +registers are read back periodically and rewritten if the device was reset (e.g. by a +brown-out while plugging the battery). +)DESCR_STR"); + + PRINT_MODULE_USAGE_NAME("ina228", "driver"); + PRINT_MODULE_USAGE_COMMAND("start"); + PRINT_MODULE_USAGE_PARAMS_I2C_SPI_DRIVER(true, false); + PRINT_MODULE_USAGE_PARAMS_I2C_ADDRESS(0x45); + PRINT_MODULE_USAGE_PARAMS_I2C_KEEP_RUNNING_FLAG(); + PRINT_MODULE_USAGE_PARAM_INT('t', 1, 1, 3, "battery index for calibration values (1-3)", true); + PRINT_MODULE_USAGE_DEFAULT_COMMANDS(); +} + +extern "C" int ina228_main(int argc, char *argv[]) +{ + using ThisDriver = INA228; + BusCLIArguments cli{true, false}; + cli.i2c_address = 0x45; + cli.default_i2c_frequency = BUS_CLOCK_HZ; + cli.support_keep_running = true; + cli.custom1 = 1; + + int ch; + + while ((ch = cli.getOpt(argc, argv, "t:")) != EOF) { + switch (ch) { + case 't': + cli.custom1 = static_cast(strtol(cli.optArg(), nullptr, 0)); + + if (cli.custom1 < 1 || cli.custom1 > 3) { + PX4_ERR("index must be 1-3"); + return -1; + } + + break; + } + } + + const char *verb = cli.optArg(); + + if (!verb) { + ThisDriver::print_usage(); + return -1; + } + + BusInstanceIterator iterator(MODULE_NAME, cli, DRV_POWER_DEVTYPE_INA228); + + if (!strcmp(verb, "start")) { + return ThisDriver::module_start(cli, iterator); + } + + if (!strcmp(verb, "stop")) { + return ThisDriver::module_stop(iterator); + } + + if (!strcmp(verb, "status")) { + return ThisDriver::module_status(iterator); + } + + ThisDriver::print_usage(); + return -1; } diff --git a/src/drivers/power_monitor/ina228/ina228.h b/src/drivers/power_monitor/ina228/ina228.h index e29c9f7c5ce..8ae1f0dcc37 100644 --- a/src/drivers/power_monitor/ina228/ina228.h +++ b/src/drivers/power_monitor/ina228/ina228.h @@ -1,6 +1,6 @@ /**************************************************************************** * - * Copyright (C) 2021 PX4 Development Team. All rights reserved. + * Copyright (C) 2021-2026 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -31,358 +31,136 @@ * ****************************************************************************/ -/** - * @file ina228.h - * - */ - #pragma once - -#include -#include #include -#include -#include #include -#include -#include +#include +#include #include #include +#include +#include +#include using namespace time_literals; -/* Configuration Constants */ -#define INA228_BASEADDR 0x45 /* 7-bit address. 8-bit address is 0x45 */ -// If initialization is forced (with the -f flag on the command line), but it fails, the drive will try again to -// connect to the INA228 every this many microseconds -#define INA228_INIT_RETRY_INTERVAL_US 500000 +namespace ina228 +{ -/* INA228 Registers addresses */ -#define INA228_REG_CONFIG (0x00) -#define INA228_REG_ADCCONFIG (0x01) -#define INA228_REG_SHUNTCAL (0x02) -#define INA228_REG_SHUNTTEMPCO (0x03) -#define INA228_REG_VSHUNT (0x04) -#define INA228_REG_VSBUS (0x05) -#define INA228_REG_DIETEMP (0x06) -#define INA228_REG_CURRENT (0x07) -#define INA228_REG_POWER (0x08) -#define INA228_REG_ENERGY (0x09) -#define INA228_REG_CHARGE (0x0a) -#define INA228_REG_DIAG_ALRT (0x0b) -#define INA228_REG_SOVL (0x0c) -#define INA228_REG_SUVL (0x0d) -#define INA228_REG_BOVL (0x0e) -#define INA228_REG_BUVL (0x0f) -#define INA228_REG_TEMP_LIMIT (0x10) -#define INA228_REG_TPWR_LIMIT (0x11) -#define INA228_MANUFACTURER_ID (0x3e) -#define INA228_DEVICE_ID (0x3f) +static constexpr uint16_t MANFID = 0x5449; +static constexpr uint16_t DIEID = 0x228; -#define INA228_MFG_ID_TI (0x5449) // TI -#define INA228_MFG_DIE (0x228) // INA228 +// Measurement scaling (from datasheet SLYS021A) +static constexpr float V_LSB = 195.3125e-6f; // V per LSB (VBUS, 20 bit) +static constexpr float T_LSB = 7.8125e-3f; // °C per LSB (DIETEMP) +static constexpr float CURRENT_LSB_DIV = 524288.f; // current_lsb = max_current / 2^19 +static constexpr float SHUNT_CAL_K = 13107.2e6f; // shunt-cal scaling constant +static constexpr float ADCRANGE_LOW_V_SENSE = 0.04096f; // ±40.96 mV +static constexpr uint16_t SHUNT_CAL_MAX = 0x7fff; // SHUNT_CAL is a 15 bit field -/* INA228 Configuration (CONFIG) 16-bit Register (Address = 0h) [reset = 0h] */ -#define INA228_ADCRANGE_SHIFTS (4) -#define INA228_ADCRANGE_MASK (1 << INA228_ADCRANGE_SHIFTS) -# define INA228_ADCRANGE_LOW (1 << INA228_ADCRANGE_SHIFTS) // ± 40.96 mV -# define INA228_ADCRANGE_HIGH (0 << INA228_ADCRANGE_SHIFTS) // ±163.84 mV -#define INA228_TEMPCOMP_SHIFTS (5) -#define INA228_TEMPCOMP_MASK (1 << INA228_TEMPCOMP_SHIFTS) -# define INA228_TEMPCOMP_ENABLE (1 << INA228_TEMPCOMP_SHIFTS) -# define INA228_TEMPCOMP_DISABLE (0 << INA228_TEMPCOMP_SHIFTS) +// Register map (subset used by this driver) +enum class Register : uint8_t { + CONFIG = 0x00, + ADCCONFIG = 0x01, + SHUNT_CAL = 0x02, + VS_BUS = 0x05, + DIETEMP = 0x06, + CURRENT = 0x07, + MANUFACTURER_ID = 0x3e, + DEVICE_ID = 0x3f, +}; -#define INA228_CONVDLY_SHIFTS (6) -#define INA228_CONVDLY_MASK (0xff << INA228_CONVDLY_SHIFTS) -# define INA228_CONVDLY2MS(n) ((n) << INA228_CONVDLY_SHIFTS) +// CONFIG register bits +enum CONFIG_BIT : uint16_t { + RST = (1u << 15), + RANGE_HIGH = (0u << 4), // ±163.84 mV — used when R_SHUNT * I_MAX > 40.96 mV + RANGE_LOW = (1u << 4), // ±40.96 mV +}; -#define INA228_RSTACC_SHIFTS (14) -#define INA228_RSTACC_MASK (1 << INA228_RSTACC_SHIFTS) -# define INA228_RSTACC_CLEAR (1 << INA228_RSTACC_SHIFTS) -# define INA228_RSTACC_NORMAL (0 << INA228_RSTACC_SHIFTS) +// ADCCONFIG register bits (subset used by this driver) +enum ADCCONFIG_BIT : uint16_t { + AVERAGES_4 = (1u << 0), -#define INA228_RST_SHIFTS (15) -#define INA228_RST_MASK (1 << INA228_RST_SHIFTS) -# define INA228_RST_RESET (1 << INA228_RST_SHIFTS) -# define INA228_RST_NORMAL (0 << INA228_RST_SHIFTS) + VTCT_50US = (0u << 3), + VSHCT_1052US = (5u << 6), + VBUSCT_540US = (4u << 9), -/* INA228 ADC Configuration (ADC_CONFIG) 16-bit Register (Address = 1h) [reset = FB68h] */ + MODE_TEMP_SHUNT_BUS_TRIG = (7u << 12), // triggered (single-shot) temperature, shunt and bus voltage +}; -#define INA228_MODE_SHIFTS (12) -#define INA228_MODE_MASK (0xf << INA228_MODE_SHIFTS) -#define INA228_MODE_SHUTDOWN_TRIG (0 << INA228_MODE_SHIFTS) -#define INA228_MODE_BUS_TRIG (1 << INA228_MODE_SHIFTS) -#define INA228_MODE_SHUNT_TRIG (2 << INA228_MODE_SHIFTS) -#define INA228_MODE_SHUNT_BUS_TRIG (3 << INA228_MODE_SHIFTS) -#define INA228_MODE_TEMP_TRIG (4 << INA228_MODE_SHIFTS) -#define INA228_MODE_TEMP_BUS_TRIG (5 << INA228_MODE_SHIFTS) -#define INA228_MODE_TEMP_SHUNT_TRIG (6 << INA228_MODE_SHIFTS) -#define INA228_MODE_TEMP_SHUNT_BUS_TRIG (7 << INA228_MODE_SHIFTS) +// Wake-up time from shutdown, the state the device is in between triggered conversions +static constexpr uint32_t WAKEUP_TIME_US = 60; -#define INA228_MODE_SHUTDOWN_CONT (8 << INA228_MODE_SHIFTS) -#define INA228_MODE_BUS_CONT (9 << INA228_MODE_SHIFTS) -#define INA228_MODE_SHUNT_CONT (10 << INA228_MODE_SHIFTS) -#define INA228_MODE_SHUNT_BUS_CONT (11 << INA228_MODE_SHIFTS) -#define INA228_MODE_TEMP_CONT (12 << INA228_MODE_SHIFTS) -#define INA228_MODE_TEMP_BUS_CONT (13 << INA228_MODE_SHIFTS) -#define INA228_MODE_TEMP_SHUNT_CONT (14 << INA228_MODE_SHIFTS) -#define INA228_MODE_TEMP_SHUNT_BUS_CONT (15 << INA228_MODE_SHIFTS) +// DEVICE_ID register: die ID in bits 15..4 +static constexpr uint16_t DEVICE_ID_MASK = 0xfff0u; +static constexpr uint16_t DEVICE_ID_SHIFT = 4; -#define INA228_VBUSCT_SHIFTS (9) -#define INA228_VBUSCT_MASK (7 << INA228_VBUSCT_SHIFTS) -#define INA228_VBUSCT_50US (0 << INA228_VBUSCT_SHIFTS) -#define INA228_VBUSCT_84US (1 << INA228_VBUSCT_SHIFTS) -#define INA228_VBUSCT_150US (2 << INA228_VBUSCT_SHIFTS) -#define INA228_VBUSCT_280US (3 << INA228_VBUSCT_SHIFTS) -#define INA228_VBUSCT_540US (4 << INA228_VBUSCT_SHIFTS) -#define INA228_VBUSCT_1052US (5 << INA228_VBUSCT_SHIFTS) -#define INA228_VBUSCT_2074US (6 << INA228_VBUSCT_SHIFTS) -#define INA228_VBUSCT_4170US (7 << INA228_VBUSCT_SHIFTS) +} // namespace ina228 -#define INA228_VSHCT_SHIFTS (6) -#define INA228_VSHCT_MASK (7 << INA228_VSHCT_SHIFTS) -#define INA228_VSHCT_50US (0 << INA228_VSHCT_SHIFTS) -#define INA228_VSHCT_84US (1 << INA228_VSHCT_SHIFTS) -#define INA228_VSHCT_150US (2 << INA228_VSHCT_SHIFTS) -#define INA228_VSHCT_280US (3 << INA228_VSHCT_SHIFTS) -#define INA228_VSHCT_540US (4 << INA228_VSHCT_SHIFTS) -#define INA228_VSHCT_1052US (5 << INA228_VSHCT_SHIFTS) -#define INA228_VSHCT_2074US (6 << INA228_VSHCT_SHIFTS) -#define INA228_VSHCT_4170US (7 << INA228_VSHCT_SHIFTS) - -#define INA228_VTCT_SHIFTS (3) -#define INA228_VTCT_MASK (7 << INA228_VTCT_SHIFTS) -#define INA228_VTCT_50US (0 << INA228_VTCT_SHIFTS) -#define INA228_VTCT_84US (1 << INA228_VTCT_SHIFTS) -#define INA228_VTCT_150US (2 << INA228_VTCT_SHIFTS) -#define INA228_VTCT_280US (3 << INA228_VTCT_SHIFTS) -#define INA228_VTCT_540US (4 << INA228_VTCT_SHIFTS) -#define INA228_VTCT_1052US (5 << INA228_VTCT_SHIFTS) -#define INA228_VTCT_2074US (6 << INA228_VTCT_SHIFTS) -#define INA228_VTCT_4170US (7 << INA228_VTCT_SHIFTS) - -#define INA228_AVERAGES_SHIFTS (0) -#define INA228_AVERAGES_MASK (7 << INA228_AVERAGES_SHIFTS) -#define INA228_AVERAGES_1 (0 << INA228_AVERAGES_SHIFTS) -#define INA228_AVERAGES_4 (1 << INA228_AVERAGES_SHIFTS) -#define INA228_AVERAGES_16 (2 << INA228_AVERAGES_SHIFTS) -#define INA228_AVERAGES_64 (3 << INA228_AVERAGES_SHIFTS) -#define INA228_AVERAGES_128 (4 << INA228_AVERAGES_SHIFTS) -#define INA228_AVERAGES_256 (5 << INA228_AVERAGES_SHIFTS) -#define INA228_AVERAGES_512 (6 << INA228_AVERAGES_SHIFTS) -#define INA228_AVERAGES_1024 (7 << INA228_AVERAGES_SHIFTS) - -#define INA228_ADCCONFIG (INA228_MODE_TEMP_SHUNT_BUS_CONT | INA228_VBUSCT_540US | INA228_VSHCT_540US | INA228_VTCT_540US |INA228_AVERAGES_64) - -/* INA228 Shunt Calibration (SHUNT_CAL) 16-bit Register (Address = 2h) [reset = 1000h] */ - -#define INA228_CURRLSB_SHIFTS (0) -#define INA228_CURRLSB_MASK (0x7fff << INA228_CURRLSB_SHIFTS) - -/* INA228 Shunt Temperature Coefficient (SHUNT_TEMPCO) 16-bit Register (Address = 3h) [reset = 0h] */ - -#define INA228_TEMPCO_SHIFTS (0) -#define INA228_TEMPCO_MASK (0x1fff << INA228_TEMPCO_SHIFTS) - -/* INA228 Shunt Voltage Measurement (VSHUNT) 24-bit Register (Address = 4h) [reset = 0h] */ - -#define INA228_VSHUNT_SHIFTS (4) -#define INA228_VSHUNT_MASK (UINT32_C(0xffffff) << INA228_VSHUNT_SHIFTS) - -/* INA228 Bus Voltage Measurement (VBUS) 24-bit Register (Address = 5h) [reset = 0h] */ - -#define INA228_VBUS_SHIFTS (4) -#define INA228_VBUS_MASK (UINT32_C(0xffffff) << INA228_VBUS_SHIFTS) - -/* INA228 Temperature Measurement (DIETEMP) 16-bit Register (Address = 6h) [reset = 0h] */ - -#define INA228_DIETEMP_SHIFTS (0) -#define INA228_DIETEMP_MASK (0xffff << INA228_DIETEMP_SHIFTS) - -/* INA228 Current Result (CURRENT) 24-bit Register (Address = 7h) [reset = 0h] */ - -#define INA228_CURRENT_SHIFTS (4) -#define INA228_CURRENT_MASK (UINT32_C(0xffffff) << INA228_CURRENT_SHIFTS) - -/* INA228 Power Result (POWER) 24-bit Register (Address = 8h) [reset = 0h] */ - -#define INA228_POWER_SHIFTS (0) -#define INA228_POWER_MASK (UINT32_C(0xffffff) << INA228_POWER_SHIFTS) - -/* INA228 Energy Result (ENERGY) 40-bit Register (Address = 9h) [reset = 0h] */ - -#define INA228_ENERGY_SHIFTS (0) -#define INA228_ENERGY_MASK (UINT64_C(0xffffffffff) << INA228_ENERGY_SHIFTS) - -/* INA228 Charge Result (CHARGE) 40-bit Register (Address = Ah) [reset = 0h] */ - -#define INA228_CHARGE_SHIFTS (0) -#define INA228_CHARGE_MASK (UINT64_C(0xffffffffff) << INA228_CHARGE_SHIFTS) - - -/* INA228 Diagnostic Flags and Alert (DIAG_ALRT) 16-bit Register (Address = Bh) [reset = 0001h] */ - -#define INA228_MEMSTAT (1 << 0) // This bit is set to 0 if a checksum error is detected in the device trim memory space -#define INA228_CNVRF (1 << 1) // This bit is set to 1 if the conversion is completed. When ALATCH =1 this bit is cleared by reading the register or starting a new triggered conversion. -#define INA228_POL (1 << 2) // This bit is set to 1 if the power measurement exceeds the threshold limit in the power limit register. -#define INA228_BUSUL (1 << 3) // This bit is set to 1 if the bus voltage measurement falls below the threshold limit in the bus under-limit register. -#define INA228_BUSOL (1 << 4) // This bit is set to 1 if the bus voltage measurement exceeds the threshold limit in the bus over-limit register. -#define INA228_SHNTUL (1 << 5) // This bit is set to 1 if the shunt voltage measurement falls below the threshold limit in the shunt under-limit register -#define INA228_SHNTOL (1 << 6) // This bit is set to 1 if the shunt voltage measurement exceeds the threshold limit in the shunt over-limit register. -#define INA228_TMPOL (1 << 7) // This bit is set to 1 if the temperature measurement exceeds the threshold limit in the temperature over-limit register. -#define INA228_MATHOF (1 << 9) // This bit is set to 1 if an arithmetic operation resulted in an overflow error. -#define INA228_CHARGEOF (1 << 10) // This bit indicates the health of the CHARGE register. If the 40 bit CHARGE register has overflowed this bit is set to 1. -#define INA228_ENERGYOF (1 << 11) // This bit indicates the health of the ENERGY register. If the 40 bit ENERGY register has overflowed this bit is set to 1. -#define INA228_APOL (1 << 12) // Alert Polarity bit sets the Alert pin polarity. -#define INA228_SLOWALER (1 << 13) // ALERT function is asserted on the completed averaged value. This gives the flexibility to delay the ALERT after the averaged value. -#define INA228_CNVR (1 << 14) // Setting this bit high configures the Alert pin to be asserted when the Conversion Ready Flag (bit 1) is asserted, indicating that a conversion cycle has completed -#define INA228_ALATCH (1 << 15) // When the Alert Latch Enable bit is set to Transparent mode, the Alert pin and Flag bit reset to the idle state when the fault has been -// cleared. When the Alert Latch Enable bit is set to Latch mode, the Alert pin and Alert Flag bit remain active following a fault until -// the DIAG_ALRT Register has been read. - -/* Shunt Overvoltage Threshold (SOVL) 16-bit Register (Address = Ch) [reset = 7FFFh] */ - -#define INA228_SOVL_SHIFTS (0) -#define INA228_SOVL_MASK (0xffff << INA228_SOVL_SHIFTS) - -/* Shunt Undervoltage Threshold (SUVL) 16-bit Register (Address = Dh) [reset = 8000h] */ - -#define INA228_SUVL_SHIFTS (0) -#define INA228_SUVL_MASK (0xffff << INA228_SUVL_SHIFTS) - -/* Bus Overvoltage Threshold (BOVL) 16-bit Register (Address = Eh) [reset = 7FFFh] */ - -#define INA228_BOVL_SHIFTS (0) -#define INA228_BOVL_MASK (0xffff << INA228_BOVL_SHIFTS) - -/* Bus Undervoltage Threshold (BUVL) 16-bit Register (Address = Fh) [reset = 0h] */ - -#define INA228_BUVL_SHIFTS (0) -#define INA228_BUVL_MASK (0xffff << INA228_BUVL_SHIFTS) - -/* Temperature Over-Limit Threshold (TEMP_LIMIT) 16-bit Register (Address = 10h) [reset = 7FFFh */ - -#define INA228_TEMP_LIMIT_SHIFTS (0) -#define INA228_TEMP_LIMIT_MASK (0xffff << INA228_TEMP_LIMIT_SHIFTS) - -/* Power Over-Limit Threshold (PWR_LIMIT) 16-bit Register (Address = 11h) [reset = FFFFh] */ - -#define INA228_POWER_LIMIT_SHIFTS (0) -#define INA228_POWER_LIMIT_MASK (0xffff << INA228_POWER_LIMIT_SHIFTS) - -/* Manufacturer ID (MANUFACTURER_ID) 16-bit Register (Address = 3Eh) [reset = 5449h] */ - -/* Device ID (DEVICE_ID) 16-bit Register (Address = 3Fh) [reset = 2280h] */ - -#define INA228_DEVICE_REV_ID_SHIFTS (0) -#define INA228_DEVICE_REV_ID_MASK (0xf << INA228_DEVICE_REV_ID_SHIFTS) -#define INA228_DEVICEREV_ID(v) (((v) & INA228_DEVICE_REV_ID_MASK) >> INA228_DEVICE_REV_ID_SHIFTS) -#define INA228_DEVICE_ID_SHIFTS (4) -#define INA228_DEVICE_ID_MASK (0xfff << INA228_DEVICE_ID_SHIFTS) -#define INA228_DEVICEID(v) (((v) & INA228_DEVICE_ID_MASK) >> INA228_DEVICE_ID_SHIFTS) - - - -#define INA228_SAMPLE_FREQUENCY_HZ 10 -#define INA228_SAMPLE_INTERVAL_US (1_s / INA228_SAMPLE_FREQUENCY_HZ) -#define INA228_CONVERSION_INTERVAL (INA228_SAMPLE_INTERVAL_US - 7) -#define DN_MAX 524288.0f /* 2^19 */ -#define INA228_CONST 13107.2e6f /* is an internal fixed value used to ensure scaling is maintained properly */ -#define INA228_VSCALE 1.95e-04f /* LSB of voltage is 195.3125 uV/LSB */ -#define INA228_TSCALE 7.8125e-03f /* LSB of temperature is 7.8125 mDegC/LSB */ - -#define INA228_ADCRANGE_LOW_V_SENSE 0.04096f // ± 40.96 mV - -#define swap16(w) __builtin_bswap16((w)) -#define swap32(d) __builtin_bswap32((d)) -#define swap64(q) __builtin_bswap64((q)) class INA228 : public device::I2C, public ModuleParams, public I2CSPIDriver { public: INA228(const I2CSPIDriverConfig &config, int battery_index); - virtual ~INA228(); + ~INA228() override; static I2CSPIDriverBase *instantiate(const I2CSPIDriverConfig &config, int runtime_instance); static void print_usage(); - void RunImpl(); + int init() override; + void RunImpl(); - int init() override; - - /** - * Tries to call the init() function. If it fails, then it will schedule to retry again in - * INA228_INIT_RETRY_INTERVAL_US microseconds. It will keep retrying at this interval until initialization succeeds. - * - * @return PX4_OK if initialization succeeded on the first try. Negative value otherwise. - */ - int force_init(); - - /** - * Diagnostics - print some basic information about the driver. - */ - void print_status() override; + void print_status() override; protected: - int probe() override; + int probe() override; private: - bool _sensor_ok{false}; - unsigned _measure_interval{0}; - bool _collect_phase{false}; - bool _initialized{false}; + enum class State : uint8_t { + UNINITIALIZED, // I2C::init() not yet called successfully — retry until it does + RESET, // soft-reset the device, then transition to CONFIGURE + CONFIGURE, // write SHUNT_CAL / CONFIG / ADCCONFIG, then transition to MEASURE + MEASURE, // steady-state: trigger, read VS_BUS / CURRENT / DIETEMP, publish, repeat + }; - perf_counter_t _sample_perf; - perf_counter_t _comms_errors; - perf_counter_t _collection_errors; - perf_counter_t _measure_errors; + int collect(); - int32_t _bus_voltage{0}; - int64_t _power{0}; - int32_t _current{0}; - int16_t _temperature{0}; - int32_t _shunt{0}; - int16_t _cal{0}; - int16_t _range{INA228_ADCRANGE_HIGH}; - bool _mode_triggered{false}; + // Rotates through the configuration registers, one per call. Returns PX4_OK, + // -EIO if the read fails, or -EBADMSG if the value doesn't match what we wrote + // (the device has been reset behind our back). + int checkConfigurationRotating(); - uint16_t _config{INA228_ADCCONFIG}; - float _current_lsb{0.f}; - float _power_lsb{25.0f * _current_lsb}; + int registerRead(ina228::Register reg, uint16_t &value); + int registerRead24(ina228::Register reg, int32_t &value); + int registerWrite(ina228::Register reg, uint16_t value); + + // --- State ------------------------------------------------------------- + Battery _battery; + + State _state{State::UNINITIALIZED}; + hrt_abstime _failing_since{0}; // first failure of the current run of failures, 0 if none + + uint8_t _next_reg_to_check{0}; + hrt_abstime _last_config_check{0}; + uint16_t _last_readback[2] {}; // CONFIG, SHUNT_CAL + hrt_abstime _trigger_time{0}; // when the last conversion was triggered + const hrt_abstime _trigger_write_min_us; // shortest time the trigger write takes on the bus + + // Configuration computed from params + float _current_lsb{0.f}; + uint16_t _shunt_calibration{0}; + uint16_t _config_value{0}; // CONFIG register value we wrote + + // Perf counters + perf_counter_t _sample_perf{perf_alloc(PC_ELAPSED, "ina228_read")}; + perf_counter_t _comms_errors{perf_alloc(PC_COUNT, "ina228_com_err")}; + perf_counter_t _reinit_perf{perf_alloc(PC_COUNT, "ina228_reinit")}; - Battery _battery; uORB::SubscriptionInterval _parameter_update_sub{ORB_ID(parameter_update), 1_s}; - uint8_t _connected{0}; - // returns state unchanged - bool setConnected(bool state); - - int read(uint8_t address, int16_t &data); - int write(uint8_t address, int16_t data); - - int read(uint8_t address, uint16_t &data); - int write(uint8_t address, uint16_t data); - - int read(uint8_t address, int32_t &data); - int write(uint8_t address, int32_t data); - - int read(uint8_t address, int64_t &data); - int write(uint8_t address, int64_t data); - - /** - * Initialise the automatic measurement state machine and start it. - * - * @note This function is called at open and error time. It might make sense - * to make it more aggressive about resetting the bus in case of errors. - */ - void start(); - - int measure(); - int collect(); DEFINE_PARAMETERS( (ParamFloat) _param_ina228_current, (ParamFloat) _param_ina228_shunt ); - }; diff --git a/src/drivers/power_monitor/ina228/ina228_main.cpp b/src/drivers/power_monitor/ina228/ina228_main.cpp deleted file mode 100644 index 5442ec8af60..00000000000 --- a/src/drivers/power_monitor/ina228/ina228_main.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** - * - * Copyright (C) 2021 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ -#include -#include - -#include "ina228.h" - -I2CSPIDriverBase *INA228::instantiate(const I2CSPIDriverConfig &config, int runtime_instance) -{ - INA228 *instance = new INA228(config, config.custom1); - - if (instance == nullptr) { - PX4_ERR("alloc failed"); - return nullptr; - } - - if (config.keep_running) { - if (instance->force_init() != PX4_OK) { - PX4_INFO("Failed to init INA228 on bus %d, but will try again periodically.", config.bus); - } - - } else if (instance->init() != PX4_OK) { - delete instance; - return nullptr; - } - - return instance; -} - -void -INA228::print_usage() -{ - PRINT_MODULE_DESCRIPTION( - R"DESCR_STR( -### Description -Driver for the INA228 power monitor. - -Multiple instances of this driver can run simultaneously, if each instance has a separate bus OR I2C address. - -For example, one instance can run on Bus 2, address 0x45, and one can run on Bus 2, address 0x45. - -If the INA228 module is not powered, then by default, initialization of the driver will fail. To change this, use -the -f flag. If this flag is set, then if initialization fails, the driver will keep trying to initialize again -every 0.5 seconds. With this flag set, you can plug in a battery after the driver starts, and it will work. Without -this flag set, the battery must be plugged in before starting the driver. - -)DESCR_STR"); - - PRINT_MODULE_USAGE_NAME("ina228", "driver"); - - PRINT_MODULE_USAGE_COMMAND("start"); - PRINT_MODULE_USAGE_PARAMS_I2C_SPI_DRIVER(true, false); - PRINT_MODULE_USAGE_PARAMS_I2C_ADDRESS(0x45); - PRINT_MODULE_USAGE_PARAMS_I2C_KEEP_RUNNING_FLAG(); - PRINT_MODULE_USAGE_PARAM_INT('t', 1, 1, 3, "battery index for calibration values (1-3)", true); - PRINT_MODULE_USAGE_DEFAULT_COMMANDS(); -} - -extern "C" int -ina228_main(int argc, char *argv[]) -{ - int ch; - using ThisDriver = INA228; - BusCLIArguments cli{true, false}; - cli.i2c_address = INA228_BASEADDR; - cli.default_i2c_frequency = 100000; - cli.support_keep_running = true; - cli.custom1 = 1; - - while ((ch = cli.getOpt(argc, argv, "t:")) != EOF) { - switch (ch) { - case 't': // battery index - cli.custom1 = (int)strtol(cli.optArg(), NULL, 0); - - if (cli.custom1 < 1 || cli.custom1 > 3) { - PX4_ERR("index must be 1-3"); - return -1; - } - - break; - } - } - - const char *verb = cli.optArg(); - if (!verb) { - ThisDriver::print_usage(); - return -1; - } - - BusInstanceIterator iterator(MODULE_NAME, cli, DRV_POWER_DEVTYPE_INA228); - - if (!strcmp(verb, "start")) { - return ThisDriver::module_start(cli, iterator); - } - - if (!strcmp(verb, "stop")) { - return ThisDriver::module_stop(iterator); - } - - if (!strcmp(verb, "status")) { - return ThisDriver::module_status(iterator); - } - - ThisDriver::print_usage(); - return -1; -} diff --git a/src/drivers/power_monitor/ina228/ina228_params.yaml b/src/drivers/power_monitor/ina228/ina228_params.yaml index 7f1d51a7b16..bf133d3a601 100644 --- a/src/drivers/power_monitor/ina228/ina228_params.yaml +++ b/src/drivers/power_monitor/ina228/ina228_params.yaml @@ -9,16 +9,6 @@ parameters: type: boolean default: 0 reboot_required: true - INA228_CONFIG: - description: - short: INA228 Power Monitor Config - type: int32 - default: 63779 - min: 0 - max: 65535 - decimal: 1 - increment: 1 - reboot_required: true INA228_CURRENT: description: short: INA228 Power Monitor Max Current diff --git a/src/drivers/power_monitor/ina238/ina238.cpp b/src/drivers/power_monitor/ina238/ina238.cpp index fa95ab60850..3a79c28c361 100644 --- a/src/drivers/power_monitor/ina238/ina238.cpp +++ b/src/drivers/power_monitor/ina238/ina238.cpp @@ -43,11 +43,8 @@ INA238::INA238(const I2CSPIDriverConfig &config, int battery_index) ModuleParams(nullptr), I2CSPIDriver(config), _battery(battery_index, this, SAMPLE_INTERVAL_US, battery_status_s::SOURCE_POWER_MODULE), - _sample_perf(perf_alloc(PC_ELAPSED, "ina238_read")), - _comms_errors(perf_alloc(PC_COUNT, "ina238_com_err")), - _collection_errors(perf_alloc(PC_COUNT, "ina238_collection_err")), - _bad_register_perf(perf_alloc(PC_COUNT, "ina238_bad_register")), - _reinit_perf(perf_alloc(PC_COUNT, "ina238_reinit")) + // On NuttX, I2C::init() rejects a bus running faster than the frequency the driver was started with + _trigger_write_min_us(config.bus_frequency > 0 ? TRIGGER_WRITE_BITS * 1'000'000 / config.bus_frequency : 0) { float max_current = _param_ina238_current.get(); float shunt_resistance = _param_ina238_shunt.get(); @@ -65,8 +62,9 @@ INA238::INA238(const I2CSPIDriverConfig &config, int battery_index) _shunt_calibration *= 4; } - // Continuous conversion, 540us conversion per channel x 3 channels x 64-sample average = 103.7 ms per output sample = ~10Hz - _adc_config_value = MODE_TEMP_SHUNT_BUS_CONT | VBUSCT_540US | VSHCT_540US | VTCT_540US | AVERAGES_64; + // Triggered: writing this value starts one conversion. The shunt gets the longer conversion time, + // and temperature the shortest: it only adds to the sample time. + _adc_config_value = MODE_TEMP_SHUNT_BUS_TRIG | VBUSCT_540US | VSHCT_1052US | VTCT_50US | AVERAGES_4; // Publish an initial disconnected status so the first instance grabs uORB instance 0 immediately. _battery.updateAndPublishBatteryStatus(hrt_absolute_time()); @@ -79,8 +77,6 @@ INA238::~INA238() { perf_free(_sample_perf); perf_free(_comms_errors); - perf_free(_collection_errors); - perf_free(_bad_register_perf); perf_free(_reinit_perf); } @@ -124,53 +120,100 @@ void INA238::RunImpl() } _state = State::CONFIGURE; + _failing_since = 0; ScheduleDelayed(RESET_DELAY_US); return; } case State::CONFIGURE: { + // The ADCCONFIG write also triggers the first conversion. const bool ok = (probe() == PX4_OK) && (registerWrite(Register::SHUNT_CAL, _shunt_calibration) == PX4_OK) && (registerWrite(Register::CONFIG, _config_value) == PX4_OK) && (registerWrite(Register::ADCCONFIG, _adc_config_value) == PX4_OK); if (!ok) { - _state = State::RESET; - ScheduleDelayed(INIT_RETRY_INTERVAL_US); + // Keep retrying every tick and only report the battery as disconnected (RESET) + // after DISCONNECT_DEBOUNCE_US without a published sample. + if (_failing_since == 0) { + _failing_since = start_time; + } + + if (start_time - _failing_since >= DISCONNECT_DEBOUNCE_US) { + perf_count(_reinit_perf); + PX4_WARN("consecutive failures, resetting"); + _state = State::RESET; + ScheduleNow(); + + } else { + ScheduleDelayed(SAMPLE_INTERVAL_US); + } + return; } - // Communication success - _consecutive_failures = 0; + _trigger_time = hrt_absolute_time(); _next_reg_to_check = 0; + _last_config_check = start_time; _state = State::MEASURE; - // Wait one full sample period + some margin - ScheduleDelayed(SAMPLE_INTERVAL_US + 5_ms); + // The first tick comes one interval later, when the first conversion is complete. + ScheduleOnInterval(SAMPLE_INTERVAL_US, SAMPLE_INTERVAL_US); return; } case State::MEASURE: { - if (collect() == PX4_OK) { - _consecutive_failures = 0; + const int ret = collect(); - } else { - perf_count(_collection_errors); + if (ret == -EAGAIN) { + // The previous conversion can't be done yet (this tick came early): read it next tick. + return; + } - if (++_consecutive_failures >= MAX_CONSECUTIVE_FAILURES) { + if (ret != PX4_OK) { + // The device may have lost power and come back with its reset configuration, and + // its result registers read zero until the first conversion after that. Write the + // configuration again before the next read instead of publishing such a sample. + if (_failing_since == 0) { + _failing_since = start_time; + } + + ScheduleClear(); + + if (start_time - _failing_since >= DISCONNECT_DEBOUNCE_US) { perf_count(_reinit_perf); - _state = State::RESET; - _consecutive_failures = 0; PX4_WARN("consecutive failures, resetting"); + _state = State::RESET; + ScheduleNow(); + + } else { + _state = State::CONFIGURE; + ScheduleDelayed(SAMPLE_INTERVAL_US); + } + + return; + } + + _failing_since = 0; + + // Checked after publishing so it doesn't add to the sample latency. A failed + // read here is only counted as a comms error; the sample reads above decide + // whether the device is gone. + if (start_time - _last_config_check >= CONFIG_CHECK_INTERVAL_US) { + _last_config_check = start_time; + + if (checkConfigurationRotating() == -EBADMSG) { + // The device lost its configuration (e.g. brown-out while plugging the battery) + // but is still responding: write it again without reporting the battery as + // disconnected, which the commander would treat as a battery failure in flight. + perf_count(_reinit_perf); + PX4_WARN("configuration lost, reconfiguring"); + ScheduleClear(); + _state = State::CONFIGURE; ScheduleNow(); - return; } } - const hrt_abstime elapsed = hrt_elapsed_time(&start_time); - const hrt_abstime scheduled_time = elapsed < SAMPLE_INTERVAL_US ? SAMPLE_INTERVAL_US - elapsed : 0; - - ScheduleDelayed(scheduled_time); return; } } @@ -178,17 +221,28 @@ void INA238::RunImpl() int INA238::collect() { + // Ticks are on a fixed hrt grid, so a tick after a late one comes early. Triggering + // before the previous conversion is done would restart it and we would read (and + // publish) the one before it again. _trigger_time is taken after the previous trigger + // write, so that conversion started before it, and the next one starts when the write + // below ends, at least _trigger_write_min_us from now. + if (hrt_elapsed_time(&_trigger_time) + _trigger_write_min_us < CONVERSION_TIME_MAX_US) { + return -EAGAIN; + } + perf_begin(_sample_perf); - // Verify one config register per cycle - bool config_ok = checkConfigurationRotating(); - - if (!config_ok) { - perf_count(_bad_register_perf); + // Start the next conversion first. The result registers keep the previous, completed + // conversion until the new one finishes, so reading them right after the trigger returns + // the sample triggered one tick ago. This gives a fixed sample latency and the full tick + // for the conversion. + if (registerWrite(Register::ADCCONFIG, _adc_config_value) != PX4_OK) { perf_end(_sample_perf); return PX4_ERROR; } + _trigger_time = hrt_absolute_time(); + int16_t bus_voltage = 0; int16_t current = 0; int16_t temperature = 0; @@ -226,30 +280,37 @@ int INA238::probe() return PX4_OK; } -bool INA238::checkConfigurationRotating() +int INA238::checkConfigurationRotating() { const struct { Register reg; uint16_t expected; } checks[] = { { Register::CONFIG, _config_value }, - { Register::ADCCONFIG, _adc_config_value }, { Register::SHUNT_CAL, _shunt_calibration }, }; + // ADCCONFIG is not checked: it is rewritten every tick to trigger the next conversion. const auto &check = checks[_next_reg_to_check]; uint16_t actual = 0; if (registerRead(check.reg, actual) != PX4_OK) { - return false; + return -EIO; } if (actual != check.expected) { - return false; + // I2C has no CRC: confirm the mismatch with a second read before acting on it. + if (registerRead(check.reg, actual) != PX4_OK) { + return -EIO; + } + + if (actual != check.expected) { + return -EBADMSG; + } } _next_reg_to_check = (_next_reg_to_check + 1) % (sizeof(checks) / sizeof(checks[0])); - return true; + return PX4_OK; } int INA238::registerRead(Register reg, uint16_t &value) @@ -314,8 +375,6 @@ void INA238::print_status() PX4_INFO("sample interval: %llu us", SAMPLE_INTERVAL_US); perf_print_counter(_sample_perf); perf_print_counter(_comms_errors); - perf_print_counter(_collection_errors); - perf_print_counter(_bad_register_perf); perf_print_counter(_reinit_perf); } @@ -355,6 +414,9 @@ Multiple instances can run simultaneously on separate buses or different I2C add If the device is not powered at startup, pass `-k` (keep_running) and the driver will retry initialization every 500 ms so the battery can be plugged in later. + +The device is sampled at 100 Hz. Every sample is triggered by the driver, so the latency +from the measurement to the publication is the same for every sample. )DESCR_STR"); PRINT_MODULE_USAGE_NAME("ina238", "driver"); diff --git a/src/drivers/power_monitor/ina238/ina238.h b/src/drivers/power_monitor/ina238/ina238.h index 935e5d6933b..087fc4fff9c 100644 --- a/src/drivers/power_monitor/ina238/ina238.h +++ b/src/drivers/power_monitor/ina238/ina238.h @@ -58,15 +58,23 @@ static constexpr float SHUNT_CAL_K = 819.2e6f; // shunt-cal scaling constant static constexpr float ADCRANGE_LOW_V_SENSE = 0.04096f; // ±40.96 mV // Sample timing -// ADC produces one averaged sample every 540us x 3 channels x 64 avg = 103.68 ms. -// Poll a hair slower than that so we always read a fresh sample rather than aliasing. -static constexpr hrt_abstime SAMPLE_INTERVAL_US = 105_ms; +// Each tick triggers one conversion, (540us bus + 1052us shunt + 50us temperature) x 4 averages +// = 6.568 ms, read on the next tick. The rest of the tick is margin for scheduling latency. +static constexpr uint32_t CONVERSION_TIME_US = (540 + 1052 + 50) * 4; +static constexpr hrt_abstime SAMPLE_INTERVAL_US = 10_ms; +static constexpr hrt_abstime WAKEUP_TIME_US = 60; // from shutdown, the state between triggered conversions +// Worst case from the trigger to a completed conversion: the internal oscillator running 1 % slow, +// plus the wake-up from shutdown. +static constexpr hrt_abstime CONVERSION_TIME_MAX_US = (CONVERSION_TIME_US * 100 + 98) / 99 + WAKEUP_TIME_US; +// The conversion starts when the trigger write ends, at least this many bit times after the write +// starts: address, register pointer and two data bytes, not counting the ACKs. +static constexpr uint32_t TRIGGER_WRITE_BITS = 32; // Recovery / robustness timing static constexpr hrt_abstime INIT_RETRY_INTERVAL_US = 500_ms; static constexpr hrt_abstime RESET_DELAY_US = 1_ms; // datasheet specifies 300us. Give some margin static constexpr hrt_abstime DISCONNECT_DEBOUNCE_US = 2_s; -static constexpr uint8_t MAX_CONSECUTIVE_FAILURES = DISCONNECT_DEBOUNCE_US / SAMPLE_INTERVAL_US; +static constexpr hrt_abstime CONFIG_CHECK_INTERVAL_US = 100_ms; // Register map (subset used by this driver) enum class Register : uint8_t { @@ -102,11 +110,11 @@ enum ADCCONFIG_BIT : uint16_t { AVERAGES_512 = (6u << 0), AVERAGES_1024 = (7u << 0), - VTCT_540US = (4u << 3), - VSHCT_540US = (4u << 6), + VTCT_50US = (0u << 3), + VSHCT_1052US = (5u << 6), VBUSCT_540US = (4u << 9), - MODE_TEMP_SHUNT_BUS_CONT = (15u << 12), + MODE_TEMP_SHUNT_BUS_TRIG = (7u << 12), // triggered (single-shot) temperature, shunt and bus voltage }; } // namespace ina238 @@ -134,14 +142,15 @@ private: UNINITIALIZED, // I2C::init() not yet called successfully — retry until it does RESET, // soft-reset the device, then transition to CONFIGURE CONFIGURE, // write SHUNT_CAL / CONFIG / ADCCONFIG, then transition to MEASURE - MEASURE, // steady-state: read VS_BUS / CURRENT / DIETEMP, publish, repeat + MEASURE, // steady-state: trigger, read VS_BUS / CURRENT / DIETEMP, publish, repeat }; int collect(); - // Rotates through the configuration registers one per call. Returns false - // if a read fails or the value doesn't match what we wrote. - bool checkConfigurationRotating(); + // Rotates through the configuration registers, one per call. Returns PX4_OK, + // -EIO if the read fails, or -EBADMSG if the value doesn't match what we wrote + // (the device has been reset behind our back). + int checkConfigurationRotating(); int registerRead(ina238::Register reg, uint16_t &value); int registerWrite(ina238::Register reg, uint16_t value); @@ -150,9 +159,12 @@ private: Battery _battery; State _state{State::UNINITIALIZED}; - uint8_t _consecutive_failures{0}; + hrt_abstime _failing_since{0}; // first failure of the current run of failures, 0 if none uint8_t _next_reg_to_check{0}; + hrt_abstime _last_config_check{0}; + hrt_abstime _trigger_time{0}; // when the last conversion was triggered + const hrt_abstime _trigger_write_min_us; // shortest time the trigger write takes on the bus // Configuration computed from params float _current_lsb{0.f}; @@ -161,11 +173,9 @@ private: uint16_t _adc_config_value{0}; // ADCCONFIG register value we wrote // Perf counters - perf_counter_t _sample_perf; - perf_counter_t _comms_errors; - perf_counter_t _collection_errors; - perf_counter_t _bad_register_perf; - perf_counter_t _reinit_perf; + perf_counter_t _sample_perf{perf_alloc(PC_ELAPSED, "ina238_read")}; + perf_counter_t _comms_errors{perf_alloc(PC_COUNT, "ina238_com_err")}; + perf_counter_t _reinit_perf{perf_alloc(PC_COUNT, "ina238_reinit")}; DEFINE_PARAMETERS( (ParamFloat) _param_ina238_current,