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

Dependencies:   microbit

Fork of microbit-component-display by BBC

Files at this revision

API Documentation at this revision

Comitter:
JonnyA
Date:
Thu Sep 28 18:23:33 2017 +0000
Parent:
0:0c37474c8541
Commit message:
Repurpose a simple display example into a battery voltage one. Thanks to Marcelo's article https://os.mbed.com/users/MarceloSalazar/notebook/measuring-battery-voltage-with-nordic-nrf51x/

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
diff -r 0c37474c8541 -r 6c9081f485dd main.cpp
--- a/main.cpp	Wed Apr 20 14:01:36 2016 +0000
+++ b/main.cpp	Thu Sep 28 18:23:33 2017 +0000
@@ -6,8 +6,43 @@
 
 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()
 {
-    while(1)
-        display.scroll(":)");
+    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);
+    }
 }
\ No newline at end of file