adc_saadc.c

nRF52840-MDK (boards.json id: nrf52840-mdk) · File : adc_saadc.c · Language : C · Use case : Mesurer une tension avec le SAADC (surveillance batterie LiPo)

The nRF52840 SAADC measures with the 0.6 V internal reference and fractional gain: halving the LiPo battery lets 0-3.3 V on the pin reconstruct 0-6.6 V. The base of any battery-powered monitoring design.

Hardware

An nRF52840-MDK board (Nordic nRF52840, Cortex-M4F @ 64 MHz, 1 MB flash / 256 KB RAM, BLE 5 + 802.15.4) with onboard debugger, programmed in C with nRF5 SDK v17 and the S140 SoftDevice. 3.7 V LiPo battery + 2 × 1 MΩ divider (midpoint to P0.04), 100 nF capacitor to GND.

Wiring

Vbat → 1 MΩ → P0.04 → 1 MΩ → GND; 100 nF across the lower resistor. Battery ground shared with the board.

How it works

The SE channel measures P0.04 against GND with 1/6 gain and internal reference; the 12-bit sample converts to millivolts then ×2 for the true battery voltage.

Running it

Open the matching nRF5 SDK v17 example (custom_board target), paste this code into main.c, build with Segger Embedded Studio or the gcc Makefile, then flash through the onboard debugger.

Variants

Sample in buffered + EasyDMA mode, keep history in flash (NVCU) and publish battery level over BLE (NUS example).

adc_saadc.c

// nRF52840-MDK : mesure SAADC canal 1 (P0.04) — batterie LiPo via pont diviseur.
// Diviseur 1M/1M -> Vbat = 2 x Vpin ; ref interne 0,6 V, gain 1/6 -> pleine echelle 3,6 V.
#include "nrfx_saadc.h"
#include "nrf_delay.h"

static volatile int16_t echantillon;
static volatile bool pret = false;

static void evt(nrfx_saadc_evt_t const *p_evt) {
  if (p_evt->type == NRFX_SAADC_EVT_DONE) {
    pret = true;                       // la conversion demandee est terminee
  }
}

int main(void) {
  nrfx_saadc_config_t cfg = NRFX_SAADC_DEFAULT_CONFIG;
  cfg.resolution = NRF_SAADC_RESOLUTION_12BIT;
  nrfx_saadc_init(&cfg, evt);

  nrf_saadc_channel_config_t ch = NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(4); // AIN1 = P0.04
  ch.gain = NRF_SAADC_GAIN1_6;             // pleine echelle ~ 3,6 V
  ch.reference = NRF_SAADC_REFERENCE_INTERNAL;
  nrfx_saadc_channel_init(0, &ch);

  for (;;) {
    nrfx_saadc_buffer_convert((int16_t *)&echantillon, 1);
    nrfx_saadc_simple_mode_start(1, 0, false, 0);
    while (!pret) { }                    // attend l'evenement DONE
    pret = false;
    int mv_pin = (int)((echantillon / 4095.0f) * 3600.0f);  // 12 bits -> mV
    int mv_bat = 2 * mv_pin;             // dediviseur x2 : tension batterie
    // Afficher mv_bat sur la console (voir exemple console_uart) ou le
    // publier en BLE. Temoin visuel : LED si batterie < 3,3 V.
    nrf_gpio_cfg_output(6);
    nrf_gpio_pin_write(6, mv_bat < 3300);
    nrf_delay_ms(1000);
  }
}

← Back to the board