52 lines
1.3 KiB
C
52 lines
1.3 KiB
C
#include "battery_adc.h"
|
|
#include <zephyr/drivers/adc.h>
|
|
#include <zephyr/drivers/gpio.h>
|
|
#include <zephyr/sys/printk.h>
|
|
|
|
#define USER_NODE DT_PATH(zephyr_user)
|
|
static const struct gpio_dt_spec btt_meas_en = GPIO_DT_SPEC_GET(USER_NODE, btt_meas_en_gpios);
|
|
static const struct adc_dt_spec adc_channel = ADC_DT_SPEC_GET(USER_NODE);
|
|
|
|
static uint32_t sample_buffer;
|
|
|
|
struct adc_sequence sequence = {
|
|
.buffer = &sample_buffer,
|
|
.buffer_size = sizeof(sample_buffer),
|
|
//.calibrate = true
|
|
};
|
|
|
|
int battery_adc_init(void) {
|
|
if (!adc_is_ready_dt(&adc_channel)) {
|
|
printk("ADC not ready\n");
|
|
return -ENODEV;
|
|
}
|
|
gpio_pin_configure_dt(&btt_meas_en, GPIO_OUTPUT_INACTIVE);
|
|
int ret = 0;
|
|
ret = adc_channel_setup_dt(&adc_channel);
|
|
if(ret){
|
|
return ret;
|
|
}
|
|
ret = adc_sequence_init_dt(&adc_channel, &sequence);
|
|
if(ret){
|
|
return ret;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int battery_measure_mv(int32_t *mv_out) {
|
|
int ret = 0;
|
|
gpio_pin_set_dt(&btt_meas_en, 1); // enable measurement
|
|
k_sleep(K_MSEC(5));
|
|
|
|
|
|
ret = adc_read(adc_channel.dev, &sequence);
|
|
if (ret) return ret;
|
|
|
|
ret = adc_raw_to_millivolts_dt(&adc_channel, &sample_buffer);
|
|
*mv_out = (int)((float)sample_buffer*((270.0f+110.0f)/270.0f));
|
|
|
|
gpio_pin_set_dt(&btt_meas_en, 0); // disable measurement
|
|
|
|
return ret;
|
|
}
|