|
7 | 7 |
|
8 | 8 | #include <stdbool.h> |
9 | 9 |
|
| 10 | +#include <pbdrv/adc.h> |
10 | 11 | #include <pbdrv/battery.h> |
11 | 12 | #include <pbio/error.h> |
12 | 13 | #include <pbdrv/gpio.h> |
|
15 | 16 | #include <tiam1808/hw/hw_syscfg0_AM1808.h> |
16 | 17 |
|
17 | 18 | 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 |
18 | 23 |
|
19 | 24 | void pbdrv_battery_init(void) { |
20 | 25 | pbdrv_gpio_alt(&battery_type_gpio, SYSCFG_PINMUX19_PINMUX19_7_4_GPIO8_8); |
| 26 | + pbdrv_gpio_out_high(&battery_voltage_measure_en_gpio); |
21 | 27 | } |
22 | 28 |
|
23 | 29 | 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; |
27 | 39 | return PBIO_SUCCESS; |
28 | 40 | } |
29 | 41 |
|
30 | 42 | 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; |
34 | 53 | } |
35 | 54 |
|
36 | 55 | pbio_error_t pbdrv_battery_get_type(pbdrv_battery_type_t *value) { |
|
0 commit comments