Beware that this post is related to an SDK in maintenance mode
More Info: Consider nRF Connect SDK for new designs
This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

nrf52 obtain battery level using internal bandgap (sdk 14)

Can anyone give me a tip on porting the code below, which works great in sdk12, to sdk14?  I'm using the nrf52832 and the ble_app_hids_keyboard example and need to get a real battery level measurement.  The code below was originally found here.  

#define VBAT_MAX_IN_MV                  3000
uint8_t battery_level_get(void)
{
  // Configure ADC
  NRF_ADC->CONFIG     = (ADC_CONFIG_RES_8bit                        << ADC_CONFIG_RES_Pos)     |
                        (ADC_CONFIG_INPSEL_SupplyOneThirdPrescaling << ADC_CONFIG_INPSEL_Pos)  |
                        (ADC_CONFIG_REFSEL_VBG                      << ADC_CONFIG_REFSEL_Pos)  |
                        (ADC_CONFIG_PSEL_Disabled                   << ADC_CONFIG_PSEL_Pos)    |
                        (ADC_CONFIG_EXTREFSEL_None                  << ADC_CONFIG_EXTREFSEL_Pos);
  NRF_ADC->EVENTS_END = 0;
  NRF_ADC->ENABLE     = ADC_ENABLE_ENABLE_Enabled;

  NRF_ADC->EVENTS_END  = 0;    // Stop any running conversions.
  NRF_ADC->TASKS_START = 1;

  while (!NRF_ADC->EVENTS_END)
  {
  }

  uint16_t vbg_in_mv = 1200;
  uint8_t adc_max = 255;
  uint16_t vbat_current_in_mv = (NRF_ADC->RESULT * 3 * vbg_in_mv) / adc_max;

  NRF_ADC->EVENTS_END     = 0;
  NRF_ADC->TASKS_STOP     = 1;

  return (uint8_t) ((vbat_current_in_mv * 100) / VBAT_MAX_IN_MV);
}

Parents Reply Children
  • Thanks guys for the replies.  After looking closer, I see what you mean that the problem is not a difference in sdk, but instead a difference in platform.  I was in a hurry and when it didn't compile I jumped to the conclusion that it was very different, but after looking closer maybe it's not so different.  The code above works on the nrf51 and uses  NRF_ADC_Type to configure the ADC, but I need it to work on the nrf52 where NRF_SAADC_Type is used.  So perhaps I just need to port the settings over to NRF_SAADC_Type.  I'll give this a shot and post my code if it works.  

  • As a relative newbie to Nordic, configuring the nrf52 saadc to behave like the nrf51 code above was requiring more reading than I have time for at the moment, but I stumbled upon the eddystone library and used es_battery_voltage_get() from there, which seems to have done the trick.   

Related