1010# Cache to reduce WiFi interruptions (ADC2 requires WiFi to be disabled)
1111_cached_raw_adc = None
1212_last_read_time = 0
13- CACHE_DURATION_MS = 30000 # 30 seconds
13+ CACHE_DURATION_ADC2_MS = 300000 # 300 seconds (expensive: requires WiFi disable)
14+ CACHE_DURATION_ADC1_MS = 30000 # 30 seconds (cheaper: no WiFi interference)
1415
1516
1617def _is_adc2_pin (pin ):
@@ -46,7 +47,7 @@ def init_adc(pinnr, sf):
4647
4748def read_raw_adc (force_refresh = False ):
4849 """
49- Read raw ADC value (0-4095) with caching.
50+ Read raw ADC value (0-4095) with adaptive caching.
5051
5152 On ESP32-S3 with ADC2, WiFi is temporarily disabled during reading.
5253 Raises RuntimeError if WifiService is busy (connecting/scanning) when using ADC2.
@@ -69,16 +70,19 @@ def read_raw_adc(force_refresh=False):
6970 int (MIN_VOLTAGE / scale_factor ), int (MAX_VOLTAGE / scale_factor )
7071 )
7172
73+ # Check if this is an ADC2 pin (requires WiFi disable)
74+ needs_wifi_disable = adc_pin is not None and _is_adc2_pin (adc_pin )
75+
76+ # Use different cache durations based on cost
77+ cache_duration = CACHE_DURATION_ADC2_MS if needs_wifi_disable else CACHE_DURATION_ADC1_MS
78+
7279 # Check cache
7380 current_time = time .ticks_ms ()
7481 if not force_refresh and _cached_raw_adc is not None :
7582 age = time .ticks_diff (current_time , _last_read_time )
76- if age < CACHE_DURATION_MS :
83+ if age < cache_duration :
7784 return _cached_raw_adc
7885
79- # Check if this is an ADC2 pin (requires WiFi disable)
80- needs_wifi_disable = adc_pin is not None and _is_adc2_pin (adc_pin )
81-
8286 # Import WifiService only if needed
8387 WifiService = None
8488 if needs_wifi_disable :
0 commit comments