serialize SAADC access with shared mutex for VDD and battery reads

This commit is contained in:
Ethan-chen1234-zy
2026-03-25 10:23:09 +08:00
parent bf162e5a14
commit 7b665e020c
4 changed files with 38 additions and 2 deletions
+8
View File
@@ -35,6 +35,11 @@
#include "nrfx_power.h"
#endif
#if defined(ARCH_NRF52)
#include "Nrf52SaadcLock.h"
#include "concurrency/LockGuard.h"
#endif
#if defined(DEBUG_HEAP_MQTT) && !MESHTASTIC_EXCLUDE_MQTT
#include "mqtt/MQTT.h"
#include "target_specific.h"
@@ -328,6 +333,9 @@ class AnalogBatteryLevel : public HasBatteryLevel
scaled = esp_adc_cal_raw_to_voltage(raw, adc_characs);
scaled *= operativeAdcMultiplier;
#else // block for all other platforms
#ifdef ARCH_NRF52
concurrency::LockGuard saadcGuard(concurrency::nrf52SaadcLock);
#endif
for (uint32_t i = 0; i < BATTERY_SENSE_SAMPLES; i++) {
raw += analogRead(BATTERY_PIN);
}
+13
View File
@@ -0,0 +1,13 @@
#include "configuration.h"
#include "Nrf52SaadcLock.h"
#include "concurrency/Lock.h"
#ifdef ARCH_NRF52
namespace concurrency
{
static Lock nrf52SaadcLockInstance;
Lock *nrf52SaadcLock = &nrf52SaadcLockInstance;
} // namespace concurrency
#endif
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#ifdef ARCH_NRF52
namespace concurrency
{
class Lock;
/** Shared mutex for SAADC configuration and reads (VDD + battery analog path). */
extern Lock *nrf52SaadcLock;
} // namespace concurrency
#endif
+5 -2
View File
@@ -25,6 +25,8 @@
#include "power.h"
#include <power/PowerHAL.h>
#include "Nrf52SaadcLock.h"
#include "concurrency/LockGuard.h"
#include <hal/nrf_lpcomp.h>
#ifdef BQ25703A_ADDR
@@ -136,11 +138,12 @@ void powerHAL_platformInit()
// get VDD voltage (in millivolts)
uint16_t getVDDVoltage()
{
// we use the same values as regular battery read so there is no conflict on SAADC
concurrency::LockGuard guard(concurrency::nrf52SaadcLock);
// Match battery read resolution; SAADC is shared with AnalogBatteryLevel in Power.cpp.
analogReadResolution(BATTERY_SENSE_RESOLUTION_BITS);
// VDD range on NRF52840 is 1.8-3.3V so we need to remap analog reference to 3.6V
// let's hope battery reading runs in same task and we don't have race condition
analogReference(AR_INTERNAL);
uint16_t vddADCRead = analogReadVDD();