ble nano hid over gatt

Dependencies:   BLE_API mbed-dev nRF51822

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers BatteryLevel.h Source File

BatteryLevel.h

00001 class BatteryLevel {
00002 
00003 public:
00004     static const float BATTERY_MAX = 2.8;
00005     static const float REFERNECE = 1.2;
00006     static const float PRESCALE = 3;
00007     static const float BATTERY_LOW = 2.0;
00008 
00009     static uint8_t readBatteryPercentage(const float voltage) {
00010         uint16_t percentage = (voltage - BATTERY_LOW) / (BATTERY_MAX - BATTERY_LOW) * 100;
00011         if (percentage > 100) percentage = 100;
00012         return percentage;
00013     }
00014 
00015     static float readBatteryVoltage() {
00016         NRF_ADC->ENABLE = ADC_ENABLE_ENABLE_Enabled;
00017 
00018         // Use internal 1.2V reference for batteryInput
00019         //  1/3 pre-scaled input and 1.2V internal band gap reference
00020         // ref. mbed-src/targets/hal/TARGET_NORDIC/TARGET_MCU_NRF51822/analogin_api.c
00021         NRF_ADC->CONFIG =
00022             (ADC_CONFIG_RES_10bit << ADC_CONFIG_RES_Pos) |
00023             // Use VDD 1/3 for input
00024             (ADC_CONFIG_INPSEL_SupplyOneThirdPrescaling << ADC_CONFIG_INPSEL_Pos) |
00025             // Use internal band gap for reference
00026             (ADC_CONFIG_REFSEL_VBG << ADC_CONFIG_REFSEL_Pos) |
00027             (ADC_CONFIG_EXTREFSEL_None << ADC_CONFIG_EXTREFSEL_Pos);
00028 
00029         // Start ADC
00030         NRF_ADC->TASKS_START = 1;
00031         while (((NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) {
00032             // busy loop
00033         }
00034 
00035         // Read ADC result
00036         uint16_t raw10bit = static_cast<uint16_t>(NRF_ADC->RESULT);
00037 
00038         NRF_ADC->ENABLE = ADC_ENABLE_ENABLE_Disabled;
00039 
00040         float ratio = raw10bit / static_cast<float>(1<<10);
00041 
00042         float batteryVoltage = ratio * (REFERNECE * PRESCALE);
00043         return batteryVoltage;
00044     }
00045 };