esp32/machine_adc: Add ADC.read_u16() method.
This commit is contained in:
parent
0e72cc9029
commit
983283a8cd
|
@ -53,12 +53,15 @@ STATIC const madc_obj_t madc_obj[] = {
|
|||
{{&machine_adc_type}, GPIO_NUM_35, ADC1_CHANNEL_7},
|
||||
};
|
||||
|
||||
STATIC uint8_t adc_bit_width;
|
||||
|
||||
STATIC mp_obj_t madc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw,
|
||||
const mp_obj_t *args) {
|
||||
|
||||
static int initialized = 0;
|
||||
if (!initialized) {
|
||||
adc1_config_width(ADC_WIDTH_12Bit);
|
||||
adc_bit_width = 12;
|
||||
initialized = 1;
|
||||
}
|
||||
|
||||
|
@ -79,6 +82,17 @@ STATIC void madc_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_
|
|||
mp_printf(print, "ADC(Pin(%u))", self->gpio_id);
|
||||
}
|
||||
|
||||
// read_u16()
|
||||
STATIC mp_obj_t madc_read_u16(mp_obj_t self_in) {
|
||||
madc_obj_t *self = MP_OBJ_TO_PTR(self_in);
|
||||
uint32_t raw = adc1_get_raw(self->adc1_id);
|
||||
// Scale raw reading to 16 bit value using a Taylor expansion (for 8 <= bits <= 16)
|
||||
uint32_t u16 = raw << (16 - adc_bit_width) | raw >> (2 * adc_bit_width - 16);
|
||||
return MP_OBJ_NEW_SMALL_INT(u16);
|
||||
}
|
||||
STATIC MP_DEFINE_CONST_FUN_OBJ_1(madc_read_u16_obj, madc_read_u16);
|
||||
|
||||
// Legacy method
|
||||
STATIC mp_obj_t madc_read(mp_obj_t self_in) {
|
||||
madc_obj_t *self = self_in;
|
||||
int val = adc1_get_raw(self->adc1_id);
|
||||
|
@ -99,13 +113,24 @@ MP_DEFINE_CONST_FUN_OBJ_2(madc_atten_obj, madc_atten);
|
|||
STATIC mp_obj_t madc_width(mp_obj_t cls_in, mp_obj_t width_in) {
|
||||
adc_bits_width_t width = mp_obj_get_int(width_in);
|
||||
esp_err_t err = adc1_config_width(width);
|
||||
if (err == ESP_OK) return mp_const_none;
|
||||
mp_raise_ValueError("Parameter Error");
|
||||
if (err != ESP_OK) {
|
||||
mp_raise_ValueError("Parameter Error");
|
||||
}
|
||||
switch (width) {
|
||||
case ADC_WIDTH_9Bit: adc_bit_width = 9; break;
|
||||
case ADC_WIDTH_10Bit: adc_bit_width = 10; break;
|
||||
case ADC_WIDTH_11Bit: adc_bit_width = 11; break;
|
||||
case ADC_WIDTH_12Bit: adc_bit_width = 12; break;
|
||||
default: break;
|
||||
}
|
||||
return mp_const_none;
|
||||
}
|
||||
MP_DEFINE_CONST_FUN_OBJ_2(madc_width_fun_obj, madc_width);
|
||||
MP_DEFINE_CONST_CLASSMETHOD_OBJ(madc_width_obj, MP_ROM_PTR(&madc_width_fun_obj));
|
||||
|
||||
STATIC const mp_rom_map_elem_t madc_locals_dict_table[] = {
|
||||
{ MP_ROM_QSTR(MP_QSTR_read_u16), MP_ROM_PTR(&madc_read_u16_obj) },
|
||||
|
||||
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&madc_read_obj) },
|
||||
{ MP_ROM_QSTR(MP_QSTR_atten), MP_ROM_PTR(&madc_atten_obj) },
|
||||
{ MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&madc_width_obj) },
|
||||
|
|
Loading…
Reference in New Issue