adc.c 31.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 "timer.h"
D
Dave Hylands 已提交
36

37 38
#if MICROPY_HW_ENABLE_ADC

39 40 41 42 43 44 45 46 47 48 49 50 51
/// \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 已提交
52 53 54

/* ADC defintions */
#define ADCx                    (ADC1)
55 56 57
#define PIN_ADC_MASK            PIN_ADC1
#define pin_adc_table           pin_adc1

58 59 60 61 62 63 64 65 66 67 68
#if defined(STM32H7)
// On the H7 ADC3 is used for ADCAll to be able to read internal
// channels. For all other GPIO channels, ADC12 is used instead.
#define ADCALLx                 (ADC3)
#define pin_adcall_table        pin_adc3
#else
// Use ADC1 for ADCAll instance by default for all other MCUs.
#define ADCALLx                 (ADC1)
#define pin_adcall_table        pin_adc1
#endif

69
#define ADCx_CLK_ENABLE         __HAL_RCC_ADC1_CLK_ENABLE
70

71 72
#if defined(STM32F0)

73
#define ADC_SCALE_V             (3.3f)
74
#define ADC_CAL_ADDRESS         (0x1ffff7ba)
75 76
#define ADC_CAL1                ((uint16_t *)0x1ffff7b8)
#define ADC_CAL2                ((uint16_t *)0x1ffff7c2)
77
#define ADC_CAL_BITS            (12)
78 79

#elif defined(STM32F4)
80

81
#define ADC_SCALE_V             (3.3f)
82
#define ADC_CAL_ADDRESS         (0x1fff7a2a)
83 84
#define ADC_CAL1                ((uint16_t *)(ADC_CAL_ADDRESS + 2))
#define ADC_CAL2                ((uint16_t *)(ADC_CAL_ADDRESS + 4))
85
#define ADC_CAL_BITS            (12)
86

87
#elif defined(STM32F7)
88

89
#define ADC_SCALE_V             (3.3f)
90 91 92 93
#if defined(STM32F722xx) || defined(STM32F723xx) || \
    defined(STM32F732xx) || defined(STM32F733xx)
#define ADC_CAL_ADDRESS         (0x1ff07a2a)
#else
94
#define ADC_CAL_ADDRESS         (0x1ff0f44a)
95 96
#endif

97 98
#define ADC_CAL1                ((uint16_t *)(ADC_CAL_ADDRESS + 2))
#define ADC_CAL2                ((uint16_t *)(ADC_CAL_ADDRESS + 4))
99
#define ADC_CAL_BITS            (12)
100

101 102
#elif defined(STM32H7)

103
#define ADC_SCALE_V             (3.3f)
104
#define ADC_CAL_ADDRESS         (0x1FF1E860)
105 106
#define ADC_CAL1                ((uint16_t *)(0x1FF1E820))
#define ADC_CAL2                ((uint16_t *)(0x1FF1E840))
107
#define ADC_CAL_BITS            (16)
108

109
#elif defined(STM32L4) || defined(STM32WB)
110

111 112 113 114
#define ADC_SCALE_V             (VREFINT_CAL_VREF / 1000.0f)
#define ADC_CAL_ADDRESS         (VREFINT_CAL_ADDR)
#define ADC_CAL1                (TEMPSENSOR_CAL1_ADDR)
#define ADC_CAL2                (TEMPSENSOR_CAL2_ADDR)
115
#define ADC_CAL_BITS            (12)
116

117
#else
118

119
#error Unsupported processor
120

121
#endif
D
Dave Hylands 已提交
122

123 124 125
#if defined(STM32F091xC)
#define VBAT_DIV (2)
#elif defined(STM32F405xx) || defined(STM32F415xx) || \
126 127
    defined(STM32F407xx) || defined(STM32F417xx) || \
    defined(STM32F401xC) || defined(STM32F401xE)
D
Dave Hylands 已提交
128
#define VBAT_DIV (2)
129 130 131 132
#elif defined(STM32F411xE) || defined(STM32F412Zx) || \
    defined(STM32F413xx) || defined(STM32F427xx) || \
    defined(STM32F429xx) || defined(STM32F437xx) || \
    defined(STM32F439xx) || defined(STM32F446xx)
133 134
#define VBAT_DIV (4)
#elif defined(STM32F722xx) || defined(STM32F723xx) || \
135 136 137
    defined(STM32F732xx) || defined(STM32F733xx) || \
    defined(STM32F746xx) || defined(STM32F765xx) || \
    defined(STM32F767xx) || defined(STM32F769xx)
D
Dave Hylands 已提交
138
#define VBAT_DIV (4)
139
#elif defined(STM32H743xx) || defined(STM32H747xx)
140
#define VBAT_DIV (4)
141
#elif defined(STM32L432xx) || \
142 143
    defined(STM32L451xx) || defined(STM32L452xx) || \
    defined(STM32L462xx) || defined(STM32L475xx) || \
144 145
    defined(STM32L476xx) || defined(STM32L496xx) || \
    defined(STM32WB55xx)
146
#define VBAT_DIV (3)
147 148
#else
#error Unsupported processor
D
Dave Hylands 已提交
149 150
#endif

151 152 153
// Timeout for waiting for end-of-conversion, in ms
#define EOC_TIMEOUT (10)

D
Dave Hylands 已提交
154 155 156 157
/* 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) */

158
// scale and calibration values for VBAT and VREF
159
#define ADC_SCALE (ADC_SCALE_V / ((1 << ADC_CAL_BITS) - 1))
160 161
#define VREFIN_CAL ((uint16_t *)ADC_CAL_ADDRESS)

162 163 164
#ifndef __HAL_ADC_IS_CHANNEL_INTERNAL
#define __HAL_ADC_IS_CHANNEL_INTERNAL(channel) \
    (channel == ADC_CHANNEL_VBAT \
165 166
    || channel == ADC_CHANNEL_VREFINT \
    || channel == ADC_CHANNEL_TEMPSENSOR)
167 168
#endif

D
Dave Hylands 已提交
169 170 171
typedef struct _pyb_obj_adc_t {
    mp_obj_base_t base;
    mp_obj_t pin_name;
172
    uint32_t channel;
D
Dave Hylands 已提交
173 174 175
    ADC_HandleTypeDef handle;
} pyb_obj_adc_t;

176 177
// convert user-facing channel number into internal channel number
static inline uint32_t adc_get_internal_channel(uint32_t channel) {
178
    #if defined(STM32F4) || defined(STM32F7)
179 180 181 182 183 184 185 186 187
    // 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;
}

188
STATIC bool is_adcx_channel(int channel) {
189
    #if defined(STM32F411xE)
190 191
    // The HAL has an incorrect IS_ADC_CHANNEL macro for the F411 so we check for temp
    return IS_ADC_CHANNEL(channel) || channel == ADC_CHANNEL_TEMPSENSOR;
192
    #elif defined(STM32F0) || defined(STM32F4) || defined(STM32F7)
193
    return IS_ADC_CHANNEL(channel);
194
    #elif defined(STM32H7)
195
    return __HAL_ADC_IS_CHANNEL_INTERNAL(channel)
196 197
           || IS_ADC_CHANNEL(__HAL_ADC_DECIMAL_NB_TO_CHANNEL(channel));
    #elif defined(STM32L4)
198 199 200
    ADC_HandleTypeDef handle;
    handle.Instance = ADCx;
    return IS_ADC_CHANNEL(&handle, channel);
201 202 203 204 205
    #elif defined(STM32WB)
    ADC_HandleTypeDef handle;
    handle.Instance = ADCx;
    return __HAL_ADC_IS_CHANNEL_INTERNAL(channel)
           || IS_ADC_CHANNEL(&handle, __HAL_ADC_DECIMAL_NB_TO_CHANNEL(channel));
206
    #else
207
    #error Unsupported processor
208
    #endif
209 210
}

211
STATIC void adc_wait_for_eoc_or_timeout(ADC_HandleTypeDef *adcHandle, int32_t timeout) {
212
    uint32_t tickstart = HAL_GetTick();
213
    #if defined(STM32F4) || defined(STM32F7)
214
    while ((adcHandle->Instance->SR & ADC_FLAG_EOC) != ADC_FLAG_EOC) {
215
    #elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4) || defined(STM32WB)
216
    while (READ_BIT(adcHandle->Instance->ISR, ADC_FLAG_EOC) != ADC_FLAG_EOC) {
217
    #else
218
    #error Unsupported processor
219
        #endif
220
        if (((HAL_GetTick() - tickstart) > timeout)) {
221 222 223 224 225
            break; // timeout
        }
    }
}

226
STATIC void adcx_clock_enable(ADC_HandleTypeDef *adch) {
227
    #if defined(STM32F0) || defined(STM32F4) || defined(STM32F7)
228
    ADCx_CLK_ENABLE();
229
    #elif defined(STM32H7)
230 231 232 233 234
    if (adch->Instance == ADC3) {
        __HAL_RCC_ADC3_CLK_ENABLE();
    } else {
        __HAL_RCC_ADC12_CLK_ENABLE();
    }
235
    __HAL_RCC_ADC_CONFIG(RCC_ADCCLKSOURCE_CLKP);
236 237 238 239
    #elif defined(STM32L4) || defined(STM32WB)
    if (__HAL_RCC_GET_ADC_SOURCE() == RCC_ADCCLKSOURCE_NONE) {
        __HAL_RCC_ADC_CONFIG(RCC_ADCCLKSOURCE_SYSCLK);
    }
240
    __HAL_RCC_ADC_CLK_ENABLE();
241
    #else
242
    #error Unsupported processor
243
    #endif
244 245
}

246
STATIC void adcx_init_periph(ADC_HandleTypeDef *adch, uint32_t resolution) {
247
    adcx_clock_enable(adch);
248

249 250
    adch->Init.Resolution = resolution;
    adch->Init.ContinuousConvMode = DISABLE;
251
    adch->Init.DiscontinuousConvMode = DISABLE;
252
    #if !defined(STM32F0)
253 254
    adch->Init.NbrOfDiscConversion = 0;
    adch->Init.NbrOfConversion = 1;
255
    #endif
256 257 258
    adch->Init.EOCSelection = ADC_EOC_SINGLE_CONV;
    adch->Init.ExternalTrigConv = ADC_SOFTWARE_START;
    adch->Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
259
    #if defined(STM32F0)
260 261 262
    adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;        // 12MHz
    adch->Init.ScanConvMode = DISABLE;
    adch->Init.DataAlign = ADC_DATAALIGN_RIGHT;
263
    adch->Init.DMAContinuousRequests = DISABLE;
264
    adch->Init.SamplingTimeCommon = ADC_SAMPLETIME_55CYCLES_5;    // ~4uS
265
    #elif defined(STM32F4) || defined(STM32F7)
266 267 268
    adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
    adch->Init.ScanConvMode = DISABLE;
    adch->Init.DataAlign = ADC_DATAALIGN_RIGHT;
269 270
    adch->Init.DMAContinuousRequests = DISABLE;
    #elif defined(STM32H7)
271 272 273 274 275 276
    adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
    adch->Init.ScanConvMode = DISABLE;
    adch->Init.LowPowerAutoWait = DISABLE;
    adch->Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
    adch->Init.OversamplingMode = DISABLE;
    adch->Init.LeftBitShift = ADC_LEFTBITSHIFT_NONE;
277
    adch->Init.ConversionDataManagement = ADC_CONVERSIONDATA_DR;
278
    #elif defined(STM32L4) || defined(STM32WB)
279 280 281 282 283 284
    adch->Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
    adch->Init.ScanConvMode = ADC_SCAN_DISABLE;
    adch->Init.LowPowerAutoWait = DISABLE;
    adch->Init.Overrun = ADC_OVR_DATA_PRESERVED;
    adch->Init.OversamplingMode = DISABLE;
    adch->Init.DataAlign = ADC_DATAALIGN_RIGHT;
285
    adch->Init.DMAContinuousRequests = DISABLE;
286 287 288 289 290
    #else
    #error Unsupported processor
    #endif

    HAL_ADC_Init(adch);
291 292 293 294

    #if defined(STM32H7)
    HAL_ADCEx_Calibration_Start(adch, ADC_CALIB_OFFSET, ADC_SINGLE_ENDED);
    #endif
295
    #if defined(STM32L4) || defined(STM32WB)
296 297
    HAL_ADCEx_Calibration_Start(adch, ADC_SINGLE_ENDED);
    #endif
298 299
}

300
STATIC void adc_init_single(pyb_obj_adc_t *adc_obj) {
301
    adc_obj->handle.Instance = ADCx;
302
    adcx_init_periph(&adc_obj->handle, ADC_RESOLUTION_12B);
303

304
    #if defined(STM32L4) && defined(ADC_DUALMODE_REGSIMULT_INJECSIMULT)
305 306
    ADC_MultiModeTypeDef multimode;
    multimode.Mode = ADC_MODE_INDEPENDENT;
307
    if (HAL_ADCEx_MultiModeConfigChannel(&adc_obj->handle, &multimode) != HAL_OK) {
308
        mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("Can not set multimode on ADC1 channel: %d"), adc_obj->channel);
309
    }
310
    #endif
311
}
D
Dave Hylands 已提交
312

313
STATIC void adc_config_channel(ADC_HandleTypeDef *adc_handle, uint32_t channel) {
D
Dave Hylands 已提交
314 315
    ADC_ChannelConfTypeDef sConfig;

316
    #if defined(STM32H7) || defined(STM32WB)
317 318 319 320 321
    sConfig.Rank = ADC_REGULAR_RANK_1;
    if (__HAL_ADC_IS_CHANNEL_INTERNAL(channel) == 0) {
        channel = __HAL_ADC_DECIMAL_NB_TO_CHANNEL(channel);
    }
    #else
D
Dave Hylands 已提交
322
    sConfig.Rank = 1;
323 324 325
    #endif
    sConfig.Channel = channel;

326
    #if defined(STM32F0)
327
    sConfig.SamplingTime = ADC_SAMPLETIME_55CYCLES_5;
328
    #elif defined(STM32F4) || defined(STM32F7)
329 330 331 332 333
    if (__HAL_ADC_IS_CHANNEL_INTERNAL(channel)) {
        sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
    } else {
        sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES;
    }
334
    #elif defined(STM32H7)
335
    if (__HAL_ADC_IS_CHANNEL_INTERNAL(channel)) {
336
        sConfig.SamplingTime = ADC_SAMPLETIME_810CYCLES_5;
337 338 339
    } else {
        sConfig.SamplingTime = ADC_SAMPLETIME_8CYCLES_5;
    }
340 341 342 343
    sConfig.SingleDiff = ADC_SINGLE_ENDED;
    sConfig.OffsetNumber = ADC_OFFSET_NONE;
    sConfig.OffsetRightShift = DISABLE;
    sConfig.OffsetSignedSaturation = DISABLE;
344
    #elif defined(STM32L4) || defined(STM32WB)
345
    if (__HAL_ADC_IS_CHANNEL_INTERNAL(channel)) {
346 347 348 349
        sConfig.SamplingTime = ADC_SAMPLETIME_247CYCLES_5;
    } else {
        sConfig.SamplingTime = ADC_SAMPLETIME_12CYCLES_5;
    }
350 351
    sConfig.SingleDiff = ADC_SINGLE_ENDED;
    sConfig.OffsetNumber = ADC_OFFSET_NONE;
352
    sConfig.Offset = 0;
353
    #else
354
    #error Unsupported processor
355
    #endif
D
Dave Hylands 已提交
356

357 358 359 360 361 362
    #if defined(STM32F0)
    // On the STM32F0 we must select only one channel at a time to sample, so clear all
    // channels before calling HAL_ADC_ConfigChannel, which will select the desired one.
    adc_handle->Instance->CHSELR = 0;
    #endif

363
    HAL_ADC_ConfigChannel(adc_handle, &sConfig);
D
Dave Hylands 已提交
364 365
}

366
STATIC uint32_t adc_read_channel(ADC_HandleTypeDef *adcHandle) {
D
Dave Hylands 已提交
367
    HAL_ADC_Start(adcHandle);
368 369
    adc_wait_for_eoc_or_timeout(adcHandle, EOC_TIMEOUT);
    uint32_t value = adcHandle->Instance->DR;
D
Dave Hylands 已提交
370
    HAL_ADC_Stop(adcHandle);
371 372
    return value;
}
D
Dave Hylands 已提交
373

374 375
STATIC uint32_t adc_config_and_read_channel(ADC_HandleTypeDef *adcHandle, uint32_t channel) {
    adc_config_channel(adcHandle, channel);
376 377 378 379 380 381 382
    uint32_t raw_value = adc_read_channel(adcHandle);

    // 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.
383 384 385
    // It's also good to disable the VBAT switch to prevent battery drain,
    // so disable it for all MCUs.
    adc_deselect_vbat(adcHandle->Instance, channel);
386 387

    return raw_value;
D
Dave Hylands 已提交
388 389 390
}

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

393
STATIC void adc_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
394
    pyb_obj_adc_t *self = MP_OBJ_TO_PTR(self_in);
395 396
    mp_print_str(print, "<ADC on ");
    mp_obj_print_helper(print, self->pin_name, PRINT_STR);
397
    mp_printf(print, " channel=%u>", self->channel);
D
Dave Hylands 已提交
398 399
}

400 401 402
/// \classmethod \constructor(pin)
/// Create an ADC object associated with the given pin.
/// This allows you to then read analog values on that pin.
403
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) {
404
    // check number of arguments
D
Damien George 已提交
405
    mp_arg_check_num(n_args, n_kw, 1, 1, false);
D
Dave Hylands 已提交
406

407 408
    // 1st argument is the pin name
    mp_obj_t pin_obj = args[0];
D
Dave Hylands 已提交
409 410 411

    uint32_t channel;

412
    if (mp_obj_is_int(pin_obj)) {
413
        channel = adc_get_internal_channel(mp_obj_get_int(pin_obj));
D
Dave Hylands 已提交
414
    } else {
415
        const pin_obj_t *pin = pin_find(pin_obj);
416
        if ((pin->adc_num & PIN_ADC_MASK) == 0) {
417 418
            // No ADC function on the given pin.
            mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("Pin(%q) doesn't have ADC capabilities"), pin->name);
D
Dave Hylands 已提交
419 420 421 422
        }
        channel = pin->adc_channel;
    }

423
    if (!is_adcx_channel(channel)) {
424
        mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("not a valid ADC Channel: %d"), channel);
D
Dave Hylands 已提交
425
    }
426

427 428 429 430 431
    // If this channel corresponds to a pin then configure the pin in ADC mode.
    if (channel < MP_ARRAY_SIZE(pin_adc_table)) {
        const pin_obj_t *pin = pin_adc_table[channel];
        if (pin != NULL) {
            mp_hal_pin_config(pin, MP_HAL_PIN_MODE_ADC, MP_HAL_PIN_PULL_NONE, 0);
432
        }
D
Dave Hylands 已提交
433 434 435 436
    }

    pyb_obj_adc_t *o = m_new_obj(pyb_obj_adc_t);
    memset(o, 0, sizeof(*o));
437
    o->base.type = &pyb_adc_type;
D
Dave Hylands 已提交
438 439 440 441
    o->pin_name = pin_obj;
    o->channel = channel;
    adc_init_single(o);

442
    return MP_OBJ_FROM_PTR(o);
D
Dave Hylands 已提交
443 444
}

445 446 447
/// \method read()
/// Read the value on the analog pin and return it.  The returned value
/// will be between 0 and 4095.
448
STATIC mp_obj_t adc_read(mp_obj_t self_in) {
449
    pyb_obj_adc_t *self = MP_OBJ_TO_PTR(self_in);
450
    return mp_obj_new_int(adc_config_and_read_channel(&self->handle, self->channel));
451 452 453
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_read_obj, adc_read);

454
/// \method read_timed(buf, timer)
455
///
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
/// 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:
479 480 481 482 483 484 485 486 487
///
///     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.
488
STATIC mp_obj_t adc_read_timed(mp_obj_t self_in, mp_obj_t buf_in, mp_obj_t freq_in) {
489
    pyb_obj_adc_t *self = MP_OBJ_TO_PTR(self_in);
490

491 492
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE);
493
    size_t typesize = mp_binary_get_size('@', bufinfo.typecode, NULL);
494

495 496 497 498 499 500 501 502 503 504 505 506
    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);
    }
507

508
    // configure the ADC channel
509
    adc_config_channel(&self->handle, self->channel);
510 511 512 513

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

514 515
    uint nelems = bufinfo.len / typesize;
    for (uint index = 0; index < nelems; index++) {
516
        // Wait for the timer to trigger so we sample at the correct frequency
517
        while (__HAL_TIM_GET_FLAG(tim, TIM_FLAG_UPDATE) == RESET) {
518
        }
519
        __HAL_TIM_CLEAR_FLAG(tim, TIM_FLAG_UPDATE);
520 521 522 523 524 525

        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
526
            #if defined(STM32F4) || defined(STM32F7)
527
            self->handle.Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
528
            #elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4) || defined(STM32WB)
529
            SET_BIT(self->handle.Instance->CR, ADC_CR_ADSTART);
530
            #else
531
            #error Unsupported processor
532
            #endif
533 534 535
        }

        // wait for sample to complete
536
        adc_wait_for_eoc_or_timeout(&self->handle, EOC_TIMEOUT);
537 538

        // read value
539
        uint value = self->handle.Instance->DR;
540 541

        // store value in buffer
542 543 544 545
        if (typesize == 1) {
            value >>= 4;
        }
        mp_binary_set_val_array_from_int(bufinfo.typecode, bufinfo.buf, index, value);
546 547
    }

548 549 550
    // turn the ADC off
    HAL_ADC_Stop(&self->handle);

551 552 553 554 555 556
    #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
557 558 559 560 561

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

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
// read_timed_multi((adcx, adcy, ...), (bufx, bufy, ...), timer)
//
// Read analog values from multiple ADC's into buffers at a rate set by the
// timer.  The ADC values have 12-bit resolution and are stored directly into
// the corresponding buffer if its element size is 16 bits or greater, otherwise
// the sample resolution will be reduced to 8 bits.
//
// This function should not allocate any heap memory.
STATIC mp_obj_t adc_read_timed_multi(mp_obj_t adc_array_in, mp_obj_t buf_array_in, mp_obj_t tim_in) {
    size_t nadcs, nbufs;
    mp_obj_t *adc_array, *buf_array;
    mp_obj_get_array(adc_array_in, &nadcs, &adc_array);
    mp_obj_get_array(buf_array_in, &nbufs, &buf_array);

    if (nadcs < 1) {
577
        mp_raise_ValueError(MP_ERROR_TEXT("need at least 1 ADC"));
578 579
    }
    if (nadcs != nbufs) {
580
        mp_raise_ValueError(MP_ERROR_TEXT("length of ADC and buffer lists differ"));
581 582 583 584 585 586
    }

    // Get buf for first ADC, get word size, check other buffers match in type
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(buf_array[0], &bufinfo, MP_BUFFER_WRITE);
    size_t typesize = mp_binary_get_size('@', bufinfo.typecode, NULL);
587
    void *bufptrs[nbufs];
588 589 590 591
    for (uint array_index = 0; array_index < nbufs; array_index++) {
        mp_buffer_info_t bufinfo_curr;
        mp_get_buffer_raise(buf_array[array_index], &bufinfo_curr, MP_BUFFER_WRITE);
        if ((bufinfo.len != bufinfo_curr.len) || (bufinfo.typecode != bufinfo_curr.typecode)) {
592
            mp_raise_ValueError(MP_ERROR_TEXT("size and type of buffers must match"));
593
        }
594
        bufptrs[array_index] = bufinfo_curr.buf;
595 596 597 598 599 600 601
    }

    // Use the supplied timer object as the sampling time base
    TIM_HandleTypeDef *tim;
    tim = pyb_timer_get_handle(tim_in);

    // Start adc; this is slow so wait for it to start
602
    pyb_obj_adc_t *adc0 = MP_OBJ_TO_PTR(adc_array[0]);
603 604 605
    adc_config_channel(&adc0->handle, adc0->channel);
    HAL_ADC_Start(&adc0->handle);
    // Wait for sample to complete and discard
606
    adc_wait_for_eoc_or_timeout(&adc0->handle, EOC_TIMEOUT);
607
    // Read (and discard) value
608
    uint value = adc0->handle.Instance->DR;
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630

    // Ensure first sample is on a timer tick
    __HAL_TIM_CLEAR_FLAG(tim, TIM_FLAG_UPDATE);
    while (__HAL_TIM_GET_FLAG(tim, TIM_FLAG_UPDATE) == RESET) {
    }
    __HAL_TIM_CLEAR_FLAG(tim, TIM_FLAG_UPDATE);

    // Overrun check: assume success
    bool success = true;
    size_t nelems = bufinfo.len / typesize;
    for (size_t elem_index = 0; elem_index < nelems; elem_index++) {
        if (__HAL_TIM_GET_FLAG(tim, TIM_FLAG_UPDATE) != RESET) {
            // Timer has already triggered
            success = false;
        } else {
            // Wait for the timer to trigger so we sample at the correct frequency
            while (__HAL_TIM_GET_FLAG(tim, TIM_FLAG_UPDATE) == RESET) {
            }
        }
        __HAL_TIM_CLEAR_FLAG(tim, TIM_FLAG_UPDATE);

        for (size_t array_index = 0; array_index < nadcs; array_index++) {
631
            pyb_obj_adc_t *adc = MP_OBJ_TO_PTR(adc_array[array_index]);
632 633 634 635 636
            // configure the ADC channel
            adc_config_channel(&adc->handle, adc->channel);
            // for the first sample we need to turn the ADC on
            // ADC is started: set the "start sample" bit
            #if defined(STM32F4) || defined(STM32F7)
637
            adc->handle.Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
638
            #elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4) || defined(STM32WB)
639
            SET_BIT(adc->handle.Instance->CR, ADC_CR_ADSTART);
640 641 642 643
            #else
            #error Unsupported processor
            #endif
            // wait for sample to complete
644
            adc_wait_for_eoc_or_timeout(&adc->handle, EOC_TIMEOUT);
645 646

            // read value
647
            value = adc->handle.Instance->DR;
648 649 650 651 652

            // store values in buffer
            if (typesize == 1) {
                value >>= 4;
            }
653
            mp_binary_set_val_array_from_int(bufinfo.typecode, bufptrs[array_index], elem_index, value);
654 655 656 657
        }
    }

    // Turn the ADC off
658
    adc0 = MP_OBJ_TO_PTR(adc_array[0]);
659 660 661 662 663 664 665
    HAL_ADC_Stop(&adc0->handle);

    return mp_obj_new_bool(success);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(adc_read_timed_multi_fun_obj, adc_read_timed_multi);
STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(adc_read_timed_multi_obj, MP_ROM_PTR(&adc_read_timed_multi_fun_obj));

666 667 668
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) },
669
    { MP_ROM_QSTR(MP_QSTR_read_timed_multi), MP_ROM_PTR(&adc_read_timed_multi_obj) },
670 671
};

672 673
STATIC MP_DEFINE_CONST_DICT(adc_locals_dict, adc_locals_dict_table);

674 675 676 677 678
const mp_obj_type_t pyb_adc_type = {
    { &mp_type_type },
    .name = MP_QSTR_ADC,
    .print = adc_print,
    .make_new = adc_make_new,
679
    .locals_dict = (mp_obj_dict_t *)&adc_locals_dict,
680
};
D
Dave Hylands 已提交
681 682 683 684

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

685
typedef struct _pyb_adc_all_obj_t {
D
Dave Hylands 已提交
686 687
    mp_obj_base_t base;
    ADC_HandleTypeDef handle;
688
} pyb_adc_all_obj_t;
D
Dave Hylands 已提交
689

690
void adc_init_all(pyb_adc_all_obj_t *adc_all, uint32_t resolution, uint32_t en_mask) {
D
Dave Hylands 已提交
691 692

    switch (resolution) {
693
        #if !defined(STM32H7)
694 695 696
        case 6:
            resolution = ADC_RESOLUTION_6B;
            break;
697
        #endif
698 699 700 701 702 703 704 705 706
        case 8:
            resolution = ADC_RESOLUTION_8B;
            break;
        case 10:
            resolution = ADC_RESOLUTION_10B;
            break;
        case 12:
            resolution = ADC_RESOLUTION_12B;
            break;
707
        #if defined(STM32H7)
708 709 710
        case 16:
            resolution = ADC_RESOLUTION_16B;
            break;
711
        #endif
D
Dave Hylands 已提交
712
        default:
713
            mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("resolution %d not supported"), resolution);
D
Dave Hylands 已提交
714 715
    }

716
    for (uint32_t channel = 0; channel < MP_ARRAY_SIZE(pin_adcall_table); ++channel) {
717 718
        // only initialise those channels that are selected with the en_mask
        if (en_mask & (1 << channel)) {
719
            // If this channel corresponds to a pin then configure the pin in ADC mode.
720
            const pin_obj_t *pin = pin_adcall_table[channel];
721
            if (pin) {
722
                mp_hal_pin_config(pin, MP_HAL_PIN_MODE_ADC, MP_HAL_PIN_PULL_NONE, 0);
723 724
            }
        }
D
Dave Hylands 已提交
725 726
    }

727
    adc_all->handle.Instance = ADCALLx;
728
    adcx_init_periph(&adc_all->handle, resolution);
D
Dave Hylands 已提交
729 730
}

D
Dave Hylands 已提交
731
int adc_get_resolution(ADC_HandleTypeDef *adcHandle) {
732
    uint32_t res_reg = ADC_GET_RESOLUTION(adcHandle);
D
Dave Hylands 已提交
733 734

    switch (res_reg) {
735
        #if !defined(STM32H7)
736 737
        case ADC_RESOLUTION_6B:
            return 6;
738
        #endif
739 740 741 742
        case ADC_RESOLUTION_8B:
            return 8;
        case ADC_RESOLUTION_10B:
            return 10;
743
        #if defined(STM32H7)
744 745
        case ADC_RESOLUTION_16B:
            return 16;
746
        #endif
D
Dave Hylands 已提交
747 748 749 750
    }
    return 12;
}

751 752 753 754 755
STATIC uint32_t adc_config_and_read_ref(ADC_HandleTypeDef *adcHandle, uint32_t channel) {
    uint32_t raw_value = adc_config_and_read_channel(adcHandle, channel);
    // Scale raw reading to the number of bits used by the calibration constants
    return raw_value << (ADC_CAL_BITS - adc_get_resolution(adcHandle));
}
D
Dave Hylands 已提交
756

757 758
int adc_read_core_temp(ADC_HandleTypeDef *adcHandle) {
    int32_t raw_value = adc_config_and_read_ref(adcHandle, ADC_CHANNEL_TEMPSENSOR);
D
Dave Hylands 已提交
759 760 761
    return ((raw_value - CORE_TEMP_V25) / CORE_TEMP_AVG_SLOPE) + 25;
}

D
Dave Hylands 已提交
762
#if MICROPY_PY_BUILTINS_FLOAT
763 764 765
// correction factor for reference value
STATIC volatile float adc_refcor = 1.0f;

766
float adc_read_core_temp_float(ADC_HandleTypeDef *adcHandle) {
767
    int32_t raw_value = adc_config_and_read_ref(adcHandle, ADC_CHANNEL_TEMPSENSOR);
768
    float core_temp_avg_slope = (*ADC_CAL2 - *ADC_CAL1) / 80.0f;
769 770 771
    return (((float)raw_value * adc_refcor - *ADC_CAL1) / core_temp_avg_slope) + 30.0f;
}

772
float adc_read_core_vbat(ADC_HandleTypeDef *adcHandle) {
773
    uint32_t raw_value = adc_config_and_read_ref(adcHandle, ADC_CHANNEL_VBAT);
774
    return raw_value * VBAT_DIV * ADC_SCALE * adc_refcor;
D
Dave Hylands 已提交
775 776
}

777
float adc_read_core_vref(ADC_HandleTypeDef *adcHandle) {
778
    uint32_t raw_value = adc_config_and_read_ref(adcHandle, ADC_CHANNEL_VREFINT);
D
Dave Hylands 已提交
779

780 781 782 783
    // update the reference correction factor
    adc_refcor = ((float)(*VREFIN_CAL)) / ((float)raw_value);

    return (*VREFIN_CAL) * ADC_SCALE;
D
Dave Hylands 已提交
784
}
D
Dave Hylands 已提交
785
#endif
D
Dave Hylands 已提交
786 787

/******************************************************************************/
788
/* MicroPython bindings : adc_all object                                      */
D
Dave Hylands 已提交
789

790
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) {
791
    // check number of arguments
792
    mp_arg_check_num(n_args, n_kw, 1, 2, false);
793 794 795 796

    // make ADCAll object
    pyb_adc_all_obj_t *o = m_new_obj(pyb_adc_all_obj_t);
    o->base.type = &pyb_adc_all_type;
797 798 799
    mp_int_t res = mp_obj_get_int(args[0]);
    uint32_t en_mask = 0xffffffff;
    if (n_args > 1) {
800
        en_mask = mp_obj_get_int(args[1]);
801 802
    }
    adc_init_all(o, res, en_mask);
803

804
    return MP_OBJ_FROM_PTR(o);
D
Dave Hylands 已提交
805 806
}

807
STATIC mp_obj_t adc_all_read_channel(mp_obj_t self_in, mp_obj_t channel) {
808
    pyb_adc_all_obj_t *self = MP_OBJ_TO_PTR(self_in);
809
    uint32_t chan = adc_get_internal_channel(mp_obj_get_int(channel));
D
Dave Hylands 已提交
810 811 812
    uint32_t data = adc_config_and_read_channel(&self->handle, chan);
    return mp_obj_new_int(data);
}
813
STATIC MP_DEFINE_CONST_FUN_OBJ_2(adc_all_read_channel_obj, adc_all_read_channel);
D
Dave Hylands 已提交
814

815
STATIC mp_obj_t adc_all_read_core_temp(mp_obj_t self_in) {
816
    pyb_adc_all_obj_t *self = MP_OBJ_TO_PTR(self_in);
817 818 819 820
    #if MICROPY_PY_BUILTINS_FLOAT
    float data = adc_read_core_temp_float(&self->handle);
    return mp_obj_new_float(data);
    #else
821
    int data = adc_read_core_temp(&self->handle);
D
Dave Hylands 已提交
822
    return mp_obj_new_int(data);
823
    #endif
D
Dave Hylands 已提交
824
}
825
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_temp_obj, adc_all_read_core_temp);
D
Dave Hylands 已提交
826

D
Dave Hylands 已提交
827
#if MICROPY_PY_BUILTINS_FLOAT
828
STATIC mp_obj_t adc_all_read_core_vbat(mp_obj_t self_in) {
829
    pyb_adc_all_obj_t *self = MP_OBJ_TO_PTR(self_in);
D
Dave Hylands 已提交
830 831 832
    float data = adc_read_core_vbat(&self->handle);
    return mp_obj_new_float(data);
}
833
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_vbat_obj, adc_all_read_core_vbat);
D
Dave Hylands 已提交
834

835
STATIC mp_obj_t adc_all_read_core_vref(mp_obj_t self_in) {
836
    pyb_adc_all_obj_t *self = MP_OBJ_TO_PTR(self_in);
837
    float data = adc_read_core_vref(&self->handle);
D
Dave Hylands 已提交
838 839
    return mp_obj_new_float(data);
}
840
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_vref_obj, adc_all_read_core_vref);
841 842

STATIC mp_obj_t adc_all_read_vref(mp_obj_t self_in) {
843
    pyb_adc_all_obj_t *self = MP_OBJ_TO_PTR(self_in);
844
    adc_read_core_vref(&self->handle);
845
    return mp_obj_new_float(ADC_SCALE_V * adc_refcor);
846 847
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_vref_obj, adc_all_read_vref);
D
Dave Hylands 已提交
848
#endif
D
Dave Hylands 已提交
849

850 851 852
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) },
853
    #if MICROPY_PY_BUILTINS_FLOAT
854 855 856
    { 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) },
857
    #endif
D
Dave Hylands 已提交
858 859
};

860 861
STATIC MP_DEFINE_CONST_DICT(adc_all_locals_dict, adc_all_locals_dict_table);

862
const mp_obj_type_t pyb_adc_all_type = {
D
Dave Hylands 已提交
863
    { &mp_type_type },
864 865
    .name = MP_QSTR_ADCAll,
    .make_new = adc_all_make_new,
866
    .locals_dict = (mp_obj_dict_t *)&adc_all_locals_dict,
D
Dave Hylands 已提交
867
};
868 869

#endif // MICROPY_HW_ENABLE_ADC