Skip to content

Commit 32d0a54

Browse files
committed
pbio/drv/battery/battery_ev3.c: Implement EV3 battery driver
This reads the values from the ADC and scales them according to the ideal scaling factors.
1 parent af9c1f4 commit 32d0a54

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

lib/pbio/drv/battery/battery_ev3.c

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
#include <stdbool.h>
99

10+
#include <pbdrv/adc.h>
1011
#include <pbdrv/battery.h>
1112
#include <pbio/error.h>
1213
#include <pbdrv/gpio.h>
@@ -15,22 +16,40 @@
1516
#include <tiam1808/hw/hw_syscfg0_AM1808.h>
1617

1718
static const pbdrv_gpio_t battery_type_gpio = PBDRV_GPIO_EV3_PIN(19, 7, 4, 8, 8);
19+
static const pbdrv_gpio_t battery_voltage_measure_en_gpio = PBDRV_GPIO_EV3_PIN(1, 7, 4, 0, 6);
20+
21+
#define PBDRV_EV3_BATTERY_VOLTAGE_ADC_CH 4
22+
#define PBDRV_EV3_BATTERY_CURRENT_ADC_CH 3
1823

1924
void pbdrv_battery_init(void) {
2025
pbdrv_gpio_alt(&battery_type_gpio, SYSCFG_PINMUX19_PINMUX19_7_4_GPIO8_8);
26+
pbdrv_gpio_out_high(&battery_voltage_measure_en_gpio);
2127
}
2228

2329
pbio_error_t pbdrv_battery_get_voltage_now(uint16_t *value) {
24-
// TODO. Calculate battery voltage based on ADC channel 4.
25-
// For now, return nominal value for now so we don't trigger low battery shutdown.
26-
*value = 7200;
30+
pbio_error_t err;
31+
uint16_t value_raw;
32+
if ((err = pbdrv_adc_get_ch(PBDRV_EV3_BATTERY_VOLTAGE_ADC_CH, &value_raw)) != PBIO_SUCCESS) {
33+
return err;
34+
}
35+
// Battery voltage is read through a voltage divider consisting of two
36+
// 100 K resistors, which halves the voltage. The ADC returns 10 LSBs,
37+
// where full scale is 5 V.
38+
*value = ((uint32_t)(value_raw) * 2 * 5000) / 1023;
2739
return PBIO_SUCCESS;
2840
}
2941

3042
pbio_error_t pbdrv_battery_get_current_now(uint16_t *value) {
31-
// TODO. Calculate battery current based on ADC channel 3.
32-
*value = 0;
33-
return PBIO_ERROR_NOT_IMPLEMENTED;
43+
pbio_error_t err;
44+
uint16_t value_raw;
45+
if ((err = pbdrv_adc_get_ch(PBDRV_EV3_BATTERY_CURRENT_ADC_CH, &value_raw)) != PBIO_SUCCESS) {
46+
return err;
47+
}
48+
// Battery current is read across a 0.05 ohm equivalent shunt resistor
49+
// which is then connected to an op-amp configured with a gain of 16
50+
// (non-inverting). This yields 1 A = 0.8 V.
51+
*value = ((uint32_t)(value_raw) * 5000 * 10) / (1023 * 8);
52+
return PBIO_SUCCESS;
3453
}
3554

3655
pbio_error_t pbdrv_battery_get_type(pbdrv_battery_type_t *value) {

0 commit comments

Comments
 (0)