An example of testing the micro:bit battery without any external components

Dependencies:   microbit

Fork of microbit-component-display by BBC

main.cpp

Committer:
JonnyA
Date:
20 months ago
Revision:
1:6c9081f485dd
Parent:
0:0c37474c8541

File content as of revision 1:6c9081f485dd:

/* See 
 * http://lancaster-university.github.io/microbit-docs/advanced/ 
 * for docs about using the micro:bit library
*/
#include "MicroBit.h"

MicroBitDisplay display;

/*
* This is a simple program that let us use the ADC to read the input voltage.
* - thanks Marcelo: https://os.mbed.com/users/MarceloSalazar/notebook/measuring-battery-voltage-with-nordic-nrf51x/
*/
 
 
void vdd_analogin_init(void)
{
    NRF_ADC->ENABLE = ADC_ENABLE_ENABLE_Enabled;
    NRF_ADC->CONFIG = (ADC_CONFIG_RES_10bit << 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);
}
 
uint16_t vdd_analogin_read_u16(void)
{
    NRF_ADC->CONFIG     &= ~ADC_CONFIG_PSEL_Msk;
    NRF_ADC->CONFIG     |= ADC_CONFIG_PSEL_Disabled << ADC_CONFIG_PSEL_Pos;
    NRF_ADC->TASKS_START = 1;
    while (((NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) {};
    return (uint16_t)NRF_ADC->RESULT; // 10 bit
}
 
int main()
{
    float value;
    char buffer[5];
    vdd_analogin_init();
    
    while(1) {     
        value = (float)vdd_analogin_read_u16();    
        value = (value * 3.6) / 1024.0;
        //May seem risky, but device will die before it reaches 10V ;)
        sprintf(buffer, "%.2f", value);
        display.scroll(buffer);
        wait(3.0);
    }
}