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

Dependencies:   microbit

Fork of microbit-component-display by BBC

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* See 
00002  * http://lancaster-university.github.io/microbit-docs/advanced/ 
00003  * for docs about using the micro:bit library
00004 */
00005 #include "MicroBit.h"
00006 
00007 MicroBitDisplay display;
00008 
00009 /*
00010 * This is a simple program that let us use the ADC to read the input voltage.
00011 * - thanks Marcelo: https://os.mbed.com/users/MarceloSalazar/notebook/measuring-battery-voltage-with-nordic-nrf51x/
00012 */
00013  
00014  
00015 void vdd_analogin_init(void)
00016 {
00017     NRF_ADC->ENABLE = ADC_ENABLE_ENABLE_Enabled;
00018     NRF_ADC->CONFIG = (ADC_CONFIG_RES_10bit << ADC_CONFIG_RES_Pos) |
00019                       (ADC_CONFIG_INPSEL_SupplyOneThirdPrescaling << ADC_CONFIG_INPSEL_Pos) |
00020                       (ADC_CONFIG_REFSEL_VBG << ADC_CONFIG_REFSEL_Pos) |
00021                       (ADC_CONFIG_PSEL_Disabled << ADC_CONFIG_PSEL_Pos) |
00022                       (ADC_CONFIG_EXTREFSEL_None << ADC_CONFIG_EXTREFSEL_Pos);
00023 }
00024  
00025 uint16_t vdd_analogin_read_u16(void)
00026 {
00027     NRF_ADC->CONFIG     &= ~ADC_CONFIG_PSEL_Msk;
00028     NRF_ADC->CONFIG     |= ADC_CONFIG_PSEL_Disabled << ADC_CONFIG_PSEL_Pos;
00029     NRF_ADC->TASKS_START = 1;
00030     while (((NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) {};
00031     return (uint16_t)NRF_ADC->RESULT; // 10 bit
00032 }
00033  
00034 int main()
00035 {
00036     float value;
00037     char buffer[5];
00038     vdd_analogin_init();
00039     
00040     while(1) {     
00041         value = (float)vdd_analogin_read_u16();    
00042         value = (value * 3.6) / 1024.0;
00043         //May seem risky, but device will die before it reaches 10V ;)
00044         sprintf(buffer, "%.2f", value);
00045         display.scroll(buffer);
00046         wait(3.0);
00047     }
00048 }