adc.c 24.5 KB
Newer Older
1
/*
2
 * This file is part of the MicroPython project, http://micropython.org/
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

D
Dave Hylands 已提交
27 28 29
#include <stdio.h>
#include <string.h>

30 31
#include "py/runtime.h"
#include "py/binary.h"
32
#include "py/mphal.h"
D
Dave Hylands 已提交
33 34
#include "adc.h"
#include "pin.h"
35
#include "genhdr/pins.h"
36
#include "timer.h"
D
Dave Hylands 已提交
37

38 39 40 41 42 43 44 45 46 47 48 49 50
/// \moduleref pyb
/// \class ADC - analog to digital conversion: read analog values on a pin
///
/// Usage:
///
///     adc = pyb.ADC(pin)              # create an analog object from a pin
///     val = adc.read()                # read an analog value
///
///     adc = pyb.ADCAll(resolution)    # creale an ADCAll object
///     val = adc.read_channel(channel) # read the given channel
///     val = adc.read_core_temp()      # read MCU temperature
///     val = adc.read_core_vbat()      # read MCU VBAT
///     val = adc.read_core_vref()      # read MCU VREF
D
Dave Hylands 已提交
51 52 53

/* ADC defintions */
#define ADCx                    (ADC1)
54
#define ADCx_CLK_ENABLE         __HAL_RCC_ADC1_CLK_ENABLE
D
Dave Hylands 已提交
55
#define ADC_NUM_CHANNELS        (19)
56

57 58 59 60 61
#if defined(MCU_SERIES_F4)

#define ADC_FIRST_GPIO_CHANNEL  (0)
#define ADC_LAST_GPIO_CHANNEL   (15)
#define ADC_CAL_ADDRESS         (0x1fff7a2a)
62 63
#define ADC_CAL1                ((uint16_t*)(ADC_CAL_ADDRESS + 2))
#define ADC_CAL2                ((uint16_t*)(ADC_CAL_ADDRESS + 4))
64 65 66

#elif defined(MCU_SERIES_F7)

67 68
#define ADC_FIRST_GPIO_CHANNEL  (0)
#define ADC_LAST_GPIO_CHANNEL   (15)
69 70 71 72
#if defined(STM32F722xx) || defined(STM32F723xx) || \
    defined(STM32F732xx) || defined(STM32F733xx)
#define ADC_CAL_ADDRESS         (0x1ff07a2a)
#else
73
#define ADC_CAL_ADDRESS         (0x1ff0f44a)
74 75
#endif

76 77
#define ADC_CAL1                ((uint16_t*)(ADC_CAL_ADDRESS + 2))
#define ADC_CAL2                ((uint16_t*)(ADC_CAL_ADDRESS + 4))
78

79
#elif defined(MCU_SERIES_L4)
80

81 82
#define ADC_FIRST_GPIO_CHANNEL  (1)
#define ADC_LAST_GPIO_CHANNEL   (16)
83
#define ADC_CAL_ADDRESS         (0x1fff75aa)
84 85
#define ADC_CAL1                ((uint16_t*)(ADC_CAL_ADDRESS - 2))
#define ADC_CAL2                ((uint16_t*)(ADC_CAL_ADDRESS + 0x20))
86

87
#else
88

89
#error Unsupported processor
90

91
#endif
D
Dave Hylands 已提交
92 93 94

#if defined(STM32F405xx) || defined(STM32F415xx) || \
    defined(STM32F407xx) || defined(STM32F417xx) || \
95 96
    defined(STM32F401xC) || defined(STM32F401xE) || \
    defined(STM32F411xE)
D
Dave Hylands 已提交
97 98
#define VBAT_DIV (2)
#elif defined(STM32F427xx) || defined(STM32F429xx) || \
99
      defined(STM32F437xx) || defined(STM32F439xx) || \
100 101
      defined(STM32F722xx) || defined(STM32F723xx) || \
      defined(STM32F732xx) || defined(STM32F733xx) || \
R
Rami Ali 已提交
102
      defined(STM32F746xx) || defined(STM32F767xx) || \
103
      defined(STM32F769xx) || defined(STM32F446xx)
D
Dave Hylands 已提交
104
#define VBAT_DIV (4)
105
#elif defined(STM32L475xx) || defined(STM32L476xx)
106
#define VBAT_DIV (3)
107 108
#else
#error Unsupported processor
D
Dave Hylands 已提交
109 110 111 112 113 114
#endif

/* Core temperature sensor definitions */
#define CORE_TEMP_V25          (943)  /* (0.76v/3.3v)*(2^ADC resoultion) */
#define CORE_TEMP_AVG_SLOPE    (3)    /* (2.5mv/3.3v)*(2^ADC resoultion) */

115 116 117 118
// scale and calibration values for VBAT and VREF
#define ADC_SCALE (3.3f / 4095)
#define VREFIN_CAL ((uint16_t *)ADC_CAL_ADDRESS)

D
Dave Hylands 已提交
119 120 121 122 123 124 125
typedef struct _pyb_obj_adc_t {
    mp_obj_base_t base;
    mp_obj_t pin_name;
    int channel;
    ADC_HandleTypeDef handle;
} pyb_obj_adc_t;

126 127 128 129 130 131 132 133 134 135 136 137
// convert user-facing channel number into internal channel number
static inline uint32_t adc_get_internal_channel(uint32_t channel) {
    #if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
    // on F4 and F7 MCUs we want channel 16 to always be the TEMPSENSOR
    // (on some MCUs ADC_CHANNEL_TEMPSENSOR=16, on others it doesn't)
    if (channel == 16) {
        channel = ADC_CHANNEL_TEMPSENSOR;
    }
    #endif
    return channel;
}

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
STATIC bool is_adcx_channel(int channel) {
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
    return IS_ADC_CHANNEL(channel);
#elif defined(MCU_SERIES_L4)
    ADC_HandleTypeDef handle;
    handle.Instance = ADCx;
    return IS_ADC_CHANNEL(&handle, channel);
#else
    #error Unsupported processor
#endif
}

STATIC void adc_wait_for_eoc_or_timeout(int32_t timeout) {
    uint32_t tickstart = HAL_GetTick();
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
    while ((ADCx->SR & ADC_FLAG_EOC) != ADC_FLAG_EOC) {
#elif defined(MCU_SERIES_L4)
    while (READ_BIT(ADCx->ISR, ADC_FLAG_EOC) != ADC_FLAG_EOC) {
#else
    #error Unsupported processor
#endif
        if (((HAL_GetTick() - tickstart ) > timeout)) {
            break; // timeout
        }
    }
}

STATIC void adcx_clock_enable(void) {
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
    ADCx_CLK_ENABLE();
#elif defined(MCU_SERIES_L4)
    __HAL_RCC_ADC_CLK_ENABLE();
#else
    #error Unsupported processor
#endif
}

175
STATIC void adc_init_single(pyb_obj_adc_t *adc_obj) {
176
    if (!is_adcx_channel(adc_obj->channel)) {
D
Dave Hylands 已提交
177 178 179
        return;
    }

180
    if (ADC_FIRST_GPIO_CHANNEL <= adc_obj->channel && adc_obj->channel <= ADC_LAST_GPIO_CHANNEL) {
D
Dave Hylands 已提交
181 182 183
      // Channels 0-16 correspond to real pins. Configure the GPIO pin in
      // ADC mode.
      const pin_obj_t *pin = pin_adc1[adc_obj->channel];
184
      mp_hal_gpio_clock_enable(pin->gpio);
D
Dave Hylands 已提交
185 186
      GPIO_InitTypeDef GPIO_InitStructure;
      GPIO_InitStructure.Pin = pin->pin_mask;
187
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
D
Dave Hylands 已提交
188
      GPIO_InitStructure.Mode = GPIO_MODE_ANALOG;
189 190 191 192 193
#elif defined(MCU_SERIES_L4)
      GPIO_InitStructure.Mode = GPIO_MODE_ANALOG_ADC_CONTROL;
#else
    #error Unsupported processor
#endif
D
Dave Hylands 已提交
194 195 196 197
      GPIO_InitStructure.Pull = GPIO_NOPULL;
      HAL_GPIO_Init(pin->gpio, &GPIO_InitStructure);
    }

198
    adcx_clock_enable();
D
Dave Hylands 已提交
199 200 201 202 203 204 205 206 207 208

    ADC_HandleTypeDef *adcHandle = &adc_obj->handle;
    adcHandle->Instance                   = ADCx;
    adcHandle->Init.ContinuousConvMode    = DISABLE;
    adcHandle->Init.DiscontinuousConvMode = DISABLE;
    adcHandle->Init.NbrOfDiscConversion   = 0;
    adcHandle->Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
    adcHandle->Init.DataAlign             = ADC_DATAALIGN_RIGHT;
    adcHandle->Init.NbrOfConversion       = 1;
    adcHandle->Init.DMAContinuousRequests = DISABLE;
209
    adcHandle->Init.Resolution            = ADC_RESOLUTION_12B;
210
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
211
    adcHandle->Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV2;
212 213
    adcHandle->Init.ScanConvMode          = DISABLE;
    adcHandle->Init.ExternalTrigConv      = ADC_EXTERNALTRIGCONV_T1_CC1;
214
    adcHandle->Init.EOCSelection          = DISABLE;
215
#elif defined(MCU_SERIES_L4)
216
    adcHandle->Init.ClockPrescaler        = ADC_CLOCK_ASYNC_DIV1;
217
    adcHandle->Init.ScanConvMode          = ADC_SCAN_DISABLE;
218 219 220
    adcHandle->Init.EOCSelection          = ADC_EOC_SINGLE_CONV;
    adcHandle->Init.ExternalTrigConv      = ADC_SOFTWARE_START;
    adcHandle->Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
221 222 223 224 225 226
    adcHandle->Init.LowPowerAutoWait      = DISABLE;
    adcHandle->Init.Overrun               = ADC_OVR_DATA_PRESERVED;
    adcHandle->Init.OversamplingMode      = DISABLE;
#else
    #error Unsupported processor
#endif
D
Dave Hylands 已提交
227 228

    HAL_ADC_Init(adcHandle);
229 230 231 232 233 234 235 236 237

#if defined(MCU_SERIES_L4)
    ADC_MultiModeTypeDef multimode;
    multimode.Mode = ADC_MODE_INDEPENDENT;
    if (HAL_ADCEx_MultiModeConfigChannel(adcHandle, &multimode) != HAL_OK)
    {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Can not set multimode on ADC1 channel: %d", adc_obj->channel));
    }
#endif
238
}
D
Dave Hylands 已提交
239

240
STATIC void adc_config_channel(ADC_HandleTypeDef *adc_handle, uint32_t channel) {
D
Dave Hylands 已提交
241 242
    ADC_ChannelConfTypeDef sConfig;

243
    sConfig.Channel = channel;
D
Dave Hylands 已提交
244
    sConfig.Rank = 1;
245
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
D
Dave Hylands 已提交
246
    sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES;
247 248
#elif defined(MCU_SERIES_L4)
    sConfig.SamplingTime = ADC_SAMPLETIME_12CYCLES_5;
249 250
    sConfig.SingleDiff = ADC_SINGLE_ENDED;
    sConfig.OffsetNumber = ADC_OFFSET_NONE;
251 252 253
#else
    #error Unsupported processor
#endif
D
Dave Hylands 已提交
254 255
    sConfig.Offset = 0;

256
    HAL_ADC_ConfigChannel(adc_handle, &sConfig);
D
Dave Hylands 已提交
257 258
}

259
STATIC uint32_t adc_read_channel(ADC_HandleTypeDef *adcHandle) {
D
Dave Hylands 已提交
260 261 262
    uint32_t rawValue = 0;

    HAL_ADC_Start(adcHandle);
263
    if (HAL_ADC_PollForConversion(adcHandle, 10) == HAL_OK
264
        && (HAL_ADC_GetState(adcHandle) & HAL_ADC_STATE_REG_EOC) == HAL_ADC_STATE_REG_EOC) {
D
Dave Hylands 已提交
265 266 267 268 269 270 271 272
        rawValue = HAL_ADC_GetValue(adcHandle);
    }
    HAL_ADC_Stop(adcHandle);

    return rawValue;
}

/******************************************************************************/
273
/* MicroPython bindings : adc object (single channel)                         */
D
Dave Hylands 已提交
274

275
STATIC void adc_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
D
Dave Hylands 已提交
276
    pyb_obj_adc_t *self = self_in;
277 278 279
    mp_print_str(print, "<ADC on ");
    mp_obj_print_helper(print, self->pin_name, PRINT_STR);
    mp_printf(print, " channel=%lu>", self->channel);
D
Dave Hylands 已提交
280 281
}

282 283 284
/// \classmethod \constructor(pin)
/// Create an ADC object associated with the given pin.
/// This allows you to then read analog values on that pin.
285
STATIC mp_obj_t adc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
286
    // check number of arguments
D
Damien George 已提交
287
    mp_arg_check_num(n_args, n_kw, 1, 1, false);
D
Dave Hylands 已提交
288

289 290
    // 1st argument is the pin name
    mp_obj_t pin_obj = args[0];
D
Dave Hylands 已提交
291 292 293 294

    uint32_t channel;

    if (MP_OBJ_IS_INT(pin_obj)) {
295
        channel = adc_get_internal_channel(mp_obj_get_int(pin_obj));
D
Dave Hylands 已提交
296
    } else {
297
        const pin_obj_t *pin = pin_find(pin_obj);
D
Dave Hylands 已提交
298 299
        if ((pin->adc_num & PIN_ADC1) == 0) {
            // No ADC1 function on that pin
300
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin %q does not have ADC capabilities", pin->name));
D
Dave Hylands 已提交
301 302 303 304
        }
        channel = pin->adc_channel;
    }

305
    if (!is_adcx_channel(channel)) {
306
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "not a valid ADC Channel: %d", channel));
D
Dave Hylands 已提交
307
    }
308 309 310 311 312 313 314 315


    if (ADC_FIRST_GPIO_CHANNEL <= channel && channel <= ADC_LAST_GPIO_CHANNEL) {
        // these channels correspond to physical GPIO ports so make sure they exist
        if (pin_adc1[channel] == NULL) {
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
                "channel %d not available on this board", channel));
        }
D
Dave Hylands 已提交
316 317 318 319
    }

    pyb_obj_adc_t *o = m_new_obj(pyb_obj_adc_t);
    memset(o, 0, sizeof(*o));
320
    o->base.type = &pyb_adc_type;
D
Dave Hylands 已提交
321 322 323 324 325 326 327
    o->pin_name = pin_obj;
    o->channel = channel;
    adc_init_single(o);

    return o;
}

328 329 330
/// \method read()
/// Read the value on the analog pin and return it.  The returned value
/// will be between 0 and 4095.
331 332 333
STATIC mp_obj_t adc_read(mp_obj_t self_in) {
    pyb_obj_adc_t *self = self_in;

334
    adc_config_channel(&self->handle, self->channel);
335 336 337 338 339
    uint32_t data = adc_read_channel(&self->handle);
    return mp_obj_new_int(data);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_read_obj, adc_read);

340
/// \method read_timed(buf, timer)
341
///
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
/// Read analog values into `buf` at a rate set by the `timer` object.
///
/// `buf` can be bytearray or array.array for example.  The ADC values have
/// 12-bit resolution and are stored directly into `buf` if its element size is
/// 16 bits or greater.  If `buf` has only 8-bit elements (eg a bytearray) then
/// the sample resolution will be reduced to 8 bits.
///
/// `timer` should be a Timer object, and a sample is read each time the timer
/// triggers.  The timer must already be initialised and running at the desired
/// sampling frequency.
///
/// To support previous behaviour of this function, `timer` can also be an
/// integer which specifies the frequency (in Hz) to sample at.  In this case
/// Timer(6) will be automatically configured to run at the given frequency.
///
/// Example using a Timer object (preferred way):
///
///     adc = pyb.ADC(pyb.Pin.board.X19)    # create an ADC on pin X19
///     tim = pyb.Timer(6, freq=10)         # create a timer running at 10Hz
///     buf = bytearray(100)                # creat a buffer to store the samples
///     adc.read_timed(buf, tim)            # sample 100 values, taking 10s
///
/// Example using an integer for the frequency:
365 366 367 368 369 370 371 372 373
///
///     adc = pyb.ADC(pyb.Pin.board.X19)    # create an ADC on pin X19
///     buf = bytearray(100)                # create a buffer of 100 bytes
///     adc.read_timed(buf, 10)             # read analog values into buf at 10Hz
///                                         #   this will take 10 seconds to finish
///     for val in buf:                     # loop over all values
///         print(val)                      # print the value out
///
/// This function does not allocate any memory.
374 375 376
STATIC mp_obj_t adc_read_timed(mp_obj_t self_in, mp_obj_t buf_in, mp_obj_t freq_in) {
    pyb_obj_adc_t *self = self_in;

377 378
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE);
379
    size_t typesize = mp_binary_get_size('@', bufinfo.typecode, NULL);
380

381 382 383 384 385 386 387 388 389 390 391 392
    TIM_HandleTypeDef *tim;
    #if defined(TIM6)
    if (mp_obj_is_integer(freq_in)) {
        // freq in Hz given so init TIM6 (legacy behaviour)
        tim = timer_tim6_init(mp_obj_get_int(freq_in));
        HAL_TIM_Base_Start(tim);
    } else
    #endif
    {
        // use the supplied timer object as the sampling time base
        tim = pyb_timer_get_handle(freq_in);
    }
393

394
    // configure the ADC channel
395
    adc_config_channel(&self->handle, self->channel);
396 397 398 399

    // This uses the timer in polling mode to do the sampling
    // TODO use DMA

400 401
    uint nelems = bufinfo.len / typesize;
    for (uint index = 0; index < nelems; index++) {
402
        // Wait for the timer to trigger so we sample at the correct frequency
403
        while (__HAL_TIM_GET_FLAG(tim, TIM_FLAG_UPDATE) == RESET) {
404
        }
405
        __HAL_TIM_CLEAR_FLAG(tim, TIM_FLAG_UPDATE);
406 407 408 409 410 411

        if (index == 0) {
            // for the first sample we need to turn the ADC on
            HAL_ADC_Start(&self->handle);
        } else {
            // for subsequent samples we can just set the "start sample" bit
412
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
413
            ADCx->CR2 |= (uint32_t)ADC_CR2_SWSTART;
414 415 416 417 418
#elif defined(MCU_SERIES_L4)
            SET_BIT(ADCx->CR, ADC_CR_ADSTART);
#else
            #error Unsupported processor
#endif
419 420 421
        }

        // wait for sample to complete
422 423
        #define READ_TIMED_TIMEOUT (10) // in ms
        adc_wait_for_eoc_or_timeout(READ_TIMED_TIMEOUT);
424 425 426 427 428

        // read value
        uint value = ADCx->DR;

        // store value in buffer
429 430 431 432
        if (typesize == 1) {
            value >>= 4;
        }
        mp_binary_set_val_array_from_int(bufinfo.typecode, bufinfo.buf, index, value);
433 434
    }

435 436 437
    // turn the ADC off
    HAL_ADC_Stop(&self->handle);

438 439 440 441 442 443
    #if defined(TIM6)
    if (mp_obj_is_integer(freq_in)) {
        // stop timer if we initialised TIM6 in this function (legacy behaviour)
        HAL_TIM_Base_Stop(tim);
    }
    #endif
444 445 446 447 448

    return mp_obj_new_int(bufinfo.len);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(adc_read_timed_obj, adc_read_timed);

449 450 451
STATIC const mp_rom_map_elem_t adc_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&adc_read_obj) },
    { MP_ROM_QSTR(MP_QSTR_read_timed), MP_ROM_PTR(&adc_read_timed_obj) },
452 453
};

454 455
STATIC MP_DEFINE_CONST_DICT(adc_locals_dict, adc_locals_dict_table);

456 457 458 459 460
const mp_obj_type_t pyb_adc_type = {
    { &mp_type_type },
    .name = MP_QSTR_ADC,
    .print = adc_print,
    .make_new = adc_make_new,
461
    .locals_dict = (mp_obj_dict_t*)&adc_locals_dict,
462
};
D
Dave Hylands 已提交
463 464 465 466

/******************************************************************************/
/* adc all object                                                             */

467
typedef struct _pyb_adc_all_obj_t {
D
Dave Hylands 已提交
468 469
    mp_obj_base_t base;
    ADC_HandleTypeDef handle;
470
} pyb_adc_all_obj_t;
D
Dave Hylands 已提交
471

472
void adc_init_all(pyb_adc_all_obj_t *adc_all, uint32_t resolution, uint32_t en_mask) {
D
Dave Hylands 已提交
473 474

    switch (resolution) {
475 476 477 478
        case 6:  resolution = ADC_RESOLUTION_6B;  break;
        case 8:  resolution = ADC_RESOLUTION_8B;  break;
        case 10: resolution = ADC_RESOLUTION_10B; break;
        case 12: resolution = ADC_RESOLUTION_12B; break;
D
Dave Hylands 已提交
479
        default:
480
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
D
Dave Hylands 已提交
481 482 483
                "resolution %d not supported", resolution));
    }

484
    for (uint32_t channel = ADC_FIRST_GPIO_CHANNEL; channel <= ADC_LAST_GPIO_CHANNEL; ++channel) {
485 486 487 488 489 490 491 492 493 494 495 496 497 498
        // only initialise those channels that are selected with the en_mask
        if (en_mask & (1 << channel)) {
            // Channels 0-16 correspond to real pins. Configure the GPIO pin in
            // ADC mode.
            const pin_obj_t *pin = pin_adc1[channel];
            if (pin) {
                mp_hal_gpio_clock_enable(pin->gpio);
                GPIO_InitTypeDef GPIO_InitStructure;
                GPIO_InitStructure.Pin = pin->pin_mask;
                GPIO_InitStructure.Mode = GPIO_MODE_ANALOG;
                GPIO_InitStructure.Pull = GPIO_NOPULL;
                HAL_GPIO_Init(pin->gpio, &GPIO_InitStructure);
            }
        }
D
Dave Hylands 已提交
499 500
    }

501
    adcx_clock_enable();
D
Dave Hylands 已提交
502 503 504 505 506 507 508 509 510 511 512 513

    ADC_HandleTypeDef *adcHandle = &adc_all->handle;
    adcHandle->Instance = ADCx;
    adcHandle->Init.Resolution            = resolution;
    adcHandle->Init.ContinuousConvMode    = DISABLE;
    adcHandle->Init.DiscontinuousConvMode = DISABLE;
    adcHandle->Init.NbrOfDiscConversion   = 0;
    adcHandle->Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
    adcHandle->Init.DataAlign             = ADC_DATAALIGN_RIGHT;
    adcHandle->Init.NbrOfConversion       = 1;
    adcHandle->Init.DMAContinuousRequests = DISABLE;
    adcHandle->Init.EOCSelection          = DISABLE;
514
#if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
515
    adcHandle->Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV2;
516 517 518 519 520 521 522 523 524 525 526 527
    adcHandle->Init.ScanConvMode          = DISABLE;
    adcHandle->Init.ExternalTrigConv      = ADC_EXTERNALTRIGCONV_T1_CC1;
#elif defined(MCU_SERIES_L4)
    adcHandle->Init.ClockPrescaler        = ADC_CLOCK_ASYNC_DIV2;
    adcHandle->Init.ScanConvMode          = ADC_SCAN_DISABLE;
    adcHandle->Init.ExternalTrigConv      = ADC_EXTERNALTRIG_T1_CC1;
    adcHandle->Init.LowPowerAutoWait      = DISABLE;
    adcHandle->Init.Overrun               = ADC_OVR_DATA_PRESERVED;
    adcHandle->Init.OversamplingMode      = DISABLE;
#else
    #error Unsupported processor
#endif
D
Dave Hylands 已提交
528 529 530 531

    HAL_ADC_Init(adcHandle);
}

532
uint32_t adc_config_and_read_channel(ADC_HandleTypeDef *adcHandle, uint32_t channel) {
533
    adc_config_channel(adcHandle, channel);
D
Dave Hylands 已提交
534 535 536
    return adc_read_channel(adcHandle);
}

D
Dave Hylands 已提交
537
int adc_get_resolution(ADC_HandleTypeDef *adcHandle) {
538
    uint32_t res_reg = ADC_GET_RESOLUTION(adcHandle);
D
Dave Hylands 已提交
539 540

    switch (res_reg) {
541 542 543
        case ADC_RESOLUTION_6B:  return 6;
        case ADC_RESOLUTION_8B:  return 8;
        case ADC_RESOLUTION_10B: return 10;
D
Dave Hylands 已提交
544 545 546 547
    }
    return 12;
}

548
int adc_read_core_temp(ADC_HandleTypeDef *adcHandle) {
D
Dave Hylands 已提交
549
    int32_t raw_value = adc_config_and_read_channel(adcHandle, ADC_CHANNEL_TEMPSENSOR);
D
Dave Hylands 已提交
550 551 552 553 554

    // Note: constants assume 12-bit resolution, so we scale the raw value to
    //       be 12-bits.
    raw_value <<= (12 - adc_get_resolution(adcHandle));

D
Dave Hylands 已提交
555 556 557
    return ((raw_value - CORE_TEMP_V25) / CORE_TEMP_AVG_SLOPE) + 25;
}

D
Dave Hylands 已提交
558
#if MICROPY_PY_BUILTINS_FLOAT
559 560 561
// correction factor for reference value
STATIC volatile float adc_refcor = 1.0f;

562 563 564 565 566 567 568 569 570 571
float adc_read_core_temp_float(ADC_HandleTypeDef *adcHandle) {
    int32_t raw_value = adc_config_and_read_channel(adcHandle, ADC_CHANNEL_TEMPSENSOR);

    // constants assume 12-bit resolution so we scale the raw value to 12-bits
    raw_value <<= (12 - adc_get_resolution(adcHandle));

    float core_temp_avg_slope = (*ADC_CAL2 - *ADC_CAL1) / 80.0;
    return (((float)raw_value * adc_refcor - *ADC_CAL1) / core_temp_avg_slope) + 30.0f;
}

572
float adc_read_core_vbat(ADC_HandleTypeDef *adcHandle) {
D
Dave Hylands 已提交
573
    uint32_t raw_value = adc_config_and_read_channel(adcHandle, ADC_CHANNEL_VBAT);
D
Dave Hylands 已提交
574 575 576 577 578

    // Note: constants assume 12-bit resolution, so we scale the raw value to
    //       be 12-bits.
    raw_value <<= (12 - adc_get_resolution(adcHandle));

579 580 581 582 583 584 585 586 587 588
    #if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
    // ST docs say that (at least on STM32F42x and STM32F43x), VBATE must
    // be disabled when TSVREFE is enabled for TEMPSENSOR and VREFINT
    // conversions to work.  VBATE is enabled by the above call to read
    // the channel, and here we disable VBATE so a subsequent call for
    // TEMPSENSOR or VREFINT works correctly.
    ADC->CCR &= ~ADC_CCR_VBATE;
    #endif

    return raw_value * VBAT_DIV * ADC_SCALE * adc_refcor;
D
Dave Hylands 已提交
589 590
}

591
float adc_read_core_vref(ADC_HandleTypeDef *adcHandle) {
D
Dave Hylands 已提交
592
    uint32_t raw_value = adc_config_and_read_channel(adcHandle, ADC_CHANNEL_VREFINT);
D
Dave Hylands 已提交
593 594 595 596 597

    // Note: constants assume 12-bit resolution, so we scale the raw value to
    //       be 12-bits.
    raw_value <<= (12 - adc_get_resolution(adcHandle));

598 599 600 601
    // update the reference correction factor
    adc_refcor = ((float)(*VREFIN_CAL)) / ((float)raw_value);

    return (*VREFIN_CAL) * ADC_SCALE;
D
Dave Hylands 已提交
602
}
D
Dave Hylands 已提交
603
#endif
D
Dave Hylands 已提交
604 605

/******************************************************************************/
606
/* MicroPython bindings : adc_all object                                      */
D
Dave Hylands 已提交
607

608
STATIC mp_obj_t adc_all_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
609
    // check number of arguments
610
    mp_arg_check_num(n_args, n_kw, 1, 2, false);
611 612 613 614

    // make ADCAll object
    pyb_adc_all_obj_t *o = m_new_obj(pyb_adc_all_obj_t);
    o->base.type = &pyb_adc_all_type;
615 616 617 618 619 620
    mp_int_t res = mp_obj_get_int(args[0]);
    uint32_t en_mask = 0xffffffff;
    if (n_args > 1) {
        en_mask =  mp_obj_get_int(args[1]);
    }
    adc_init_all(o, res, en_mask);
621 622

    return o;
D
Dave Hylands 已提交
623 624
}

625
STATIC mp_obj_t adc_all_read_channel(mp_obj_t self_in, mp_obj_t channel) {
626
    pyb_adc_all_obj_t *self = self_in;
627
    uint32_t chan = adc_get_internal_channel(mp_obj_get_int(channel));
D
Dave Hylands 已提交
628 629 630
    uint32_t data = adc_config_and_read_channel(&self->handle, chan);
    return mp_obj_new_int(data);
}
631
STATIC MP_DEFINE_CONST_FUN_OBJ_2(adc_all_read_channel_obj, adc_all_read_channel);
D
Dave Hylands 已提交
632

633
STATIC mp_obj_t adc_all_read_core_temp(mp_obj_t self_in) {
634
    pyb_adc_all_obj_t *self = self_in;
635 636 637 638
    #if MICROPY_PY_BUILTINS_FLOAT
    float data = adc_read_core_temp_float(&self->handle);
    return mp_obj_new_float(data);
    #else
D
Dave Hylands 已提交
639 640
    int data  = adc_read_core_temp(&self->handle);
    return mp_obj_new_int(data);
641
    #endif
D
Dave Hylands 已提交
642
}
643
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_temp_obj, adc_all_read_core_temp);
D
Dave Hylands 已提交
644

D
Dave Hylands 已提交
645
#if MICROPY_PY_BUILTINS_FLOAT
646
STATIC mp_obj_t adc_all_read_core_vbat(mp_obj_t self_in) {
647
    pyb_adc_all_obj_t *self = self_in;
D
Dave Hylands 已提交
648 649 650
    float data = adc_read_core_vbat(&self->handle);
    return mp_obj_new_float(data);
}
651
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_vbat_obj, adc_all_read_core_vbat);
D
Dave Hylands 已提交
652

653
STATIC mp_obj_t adc_all_read_core_vref(mp_obj_t self_in) {
654
    pyb_adc_all_obj_t *self = self_in;
D
Dave Hylands 已提交
655 656 657
    float data  = adc_read_core_vref(&self->handle);
    return mp_obj_new_float(data);
}
658
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_vref_obj, adc_all_read_core_vref);
659 660 661 662 663 664 665

STATIC mp_obj_t adc_all_read_vref(mp_obj_t self_in) {
    pyb_adc_all_obj_t *self = self_in;
    adc_read_core_vref(&self->handle);
    return mp_obj_new_float(3.3 * adc_refcor);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_vref_obj, adc_all_read_vref);
D
Dave Hylands 已提交
666
#endif
D
Dave Hylands 已提交
667

668 669 670
STATIC const mp_rom_map_elem_t adc_all_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_read_channel), MP_ROM_PTR(&adc_all_read_channel_obj) },
    { MP_ROM_QSTR(MP_QSTR_read_core_temp), MP_ROM_PTR(&adc_all_read_core_temp_obj) },
D
Dave Hylands 已提交
671
#if MICROPY_PY_BUILTINS_FLOAT
672 673 674
    { MP_ROM_QSTR(MP_QSTR_read_core_vbat), MP_ROM_PTR(&adc_all_read_core_vbat_obj) },
    { MP_ROM_QSTR(MP_QSTR_read_core_vref), MP_ROM_PTR(&adc_all_read_core_vref_obj) },
    { MP_ROM_QSTR(MP_QSTR_read_vref), MP_ROM_PTR(&adc_all_read_vref_obj) },
D
Dave Hylands 已提交
675
#endif
D
Dave Hylands 已提交
676 677
};

678 679
STATIC MP_DEFINE_CONST_DICT(adc_all_locals_dict, adc_all_locals_dict_table);

680
const mp_obj_type_t pyb_adc_all_type = {
D
Dave Hylands 已提交
681
    { &mp_type_type },
682 683
    .name = MP_QSTR_ADCAll,
    .make_new = adc_all_make_new,
684
    .locals_dict = (mp_obj_dict_t*)&adc_all_locals_dict,
D
Dave Hylands 已提交
685
};