AnalogFastIn

This commit is contained in:
Lee Atkinson 2022-08-10 09:42:24 -04:00
parent f69939c49c
commit 9e0c580d3d
6 changed files with 444 additions and 4 deletions

View File

@ -1 +1,169 @@
/* AnalogFastIn.c */
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Scott Shawcroft for Adafruit Industries
*
* 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.
*/
#include "common-hal/analogio/AnalogFastIn.h"
#include "shared-bindings/analogio/AnalogFastIn.h"
#include "shared-bindings/microcontroller/Pin.h"
#include "py/runtime.h"
#include "supervisor/shared/translate/translate.h"
#include "src/rp2_common/hardware_adc/include/hardware/adc.h"
#include "src/rp2_common/hardware_dma/include/hardware/dma.h"
// /sdk/src/rp2_common/hardware_dma/include/hardware/dma.h
// ports/raspberrypi/
#include "sdk/src/common/pico_stdlib/include/pico/stdlib.h"
#define ADC_FIRST_PIN_NUMBER 26
#define ADC_PIN_COUNT 4
// Channel 0 is GPIO26
#define CAPTURE_CHANNEL 0
#define CAPTURE_DEPTH 1000
uint8_t capture_buf[CAPTURE_DEPTH];
// ADC unit8 or int8 ??? ---> unint16
//
// uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) {
// adc_select_input(self->pin->number - ADC_FIRST_PIN_NUMBER);
// uint16_t value = adc_read();
//
// // Stretch 12-bit ADC reading to 16-bit range
// return (value << 4) | (value >> 8);
// }
/*
typedef struct {
mp_obj_base_t base;
uint8_t number;
} mcu_pin_obj_t;
*/
// self->pin = pin;
// self->buffer = buffer;
// self->len = len;
// //self->bits_per_sample = bytes_per_sample * 8;
// self->samples_signed = samples_signed;
// self->sample_rate = sample_rate;
void common_hal_analogio_analogfastin_construct(analogio_analogfastin_obj_t *self, const mcu_pin_obj_t *pin, uint8_t *buffer, uint32_t len, uint8_t bytes_per_sample, bool samples_signed, uint32_t sample_rate) {
// Set pin and channel
self->pin = pin;
self->chan = pin->number - ADC_FIRST_PIN_NUMBER;
// Checks on chan value here
// Set buffer and length
self->buffer = buffer;
self->len = len;
// checks on length here
// uint8_t bytes_per_sample
// Set sample rate
// self->bits_per_sample = bytes_per_sample * 8;
self->sample_rate = sample_rate;
// Standard IO Init
stdio_init_all();
// Init GPIO for analogue use: hi-Z, no pulls, disable digital input buffer.
adc_init();
adc_gpio_init(pin->number);
adc_select_input(self->chan); // chan = pin - 26 ??
// adc_select_input(self->pin->number - ADC_FIRST_PIN_NUMBER);
adc_fifo_setup(
true, // Write each completed conversion to the sample FIFO
true, // Enable DMA data request (DREQ)
1, // DREQ (and IRQ) asserted when at least 1 sample present
false, // We won't see the ERR bit because of 8 bit reads; disable. // ??
true // Shift each sample to 8 bits when pushing to FIFO // ??
);
// Divisor of 0 -> full speed. Free-running capture with the divider is
// equivalent to pressing the ADC_CS_START_ONCE button once per `div + 1`
// cycles (div not necessarily an integer). Each conversion takes 96
// cycles, so in general you want a divider of 0 (hold down the button
// continuously) or > 95 (take samples less frequently than 96 cycle
// intervals). This is all timed by the 48 MHz ADC clock.
// sample rate determines divisor, not zero.
adc_set_clkdiv(0);
// sleep_ms(1000);
// Set up the DMA to start transferring data as soon as it appears in FIFO
uint dma_chan = dma_claim_unused_channel(true);
self->dma_chan = dma_chan;
dma_channel_config cfg = dma_channel_get_default_config(dma_chan);
// Reading from constant address, writing to incrementing byte addresses
channel_config_set_transfer_data_size(&cfg, DMA_SIZE_8);
channel_config_set_read_increment(&cfg, false);
channel_config_set_write_increment(&cfg, true);
// Pace transfers based on availability of ADC samples
channel_config_set_dreq(&cfg, DREQ_ADC);
dma_channel_configure(dma_chan, &cfg,
capture_buf, // dst
&adc_hw->fifo, // src
self->len, // CAPTURE_DEPTH, // transfer count
true // start immediately
);
}
bool common_hal_analogio_analogfastin_deinited(analogio_analogfastin_obj_t *self) {
return self->pin == NULL;
}
void common_hal_analogio_analogfastin_deinit(analogio_analogfastin_obj_t *self) {
if (common_hal_analogio_analogfastin_deinited(self)) {
return;
}
reset_pin_number(self->pin->number);
self->pin = NULL;
}
// ================================================================
// capture()
// make this a bool so that later we can perform integrity checking
// ================================================================
bool common_hal_analogio_analogfastin_capture(analogio_analogfastin_obj_t *self) {
// uint16_t value = adc_read();
// Stretch 12-bit ADC reading to 16-bit range
// return (value << 4) | (value >> 8);
adc_run(true);
// Once DMA finishes, stop any new conversions from starting, and clean up
// the FIFO in case the ADC was still mid-conversion.
dma_channel_wait_for_finish_blocking(self->dma_chan);
// printf("Capture finished\n");
adc_run(false);
adc_fifo_drain();
return true;
}

View File

@ -1 +1,71 @@
/* AnalogFastIn.h */
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Scott Shawcroft for Adafruit Industries
*
* 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.
*/
#ifndef MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_ANALOGIO_ANALOGFASTIN_H
#define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_ANALOGIO_ANALOGFASTIN_H
#include "common-hal/microcontroller/Pin.h"
#include "py/obj.h"
// We can extend the struct without impact to existing code
typedef struct {
mp_obj_base_t base;
const mcu_pin_obj_t *pin;
uint8_t *buffer;
uint32_t len;
uint8_t bytes_per_sample;
bool samples_signed;
uint32_t sample_rate;
uint8_t chan;
uint dma_chan;
// data_size = DMA_SIZE_8; // - default DMA_SIZE_8
// data_size = DMA_SIZE_16; // - default DMA_SIZE_16
// Either 12 bits in 16 or 12 over 2 bytes or truncate 12 to 8 in 8
// Either B or H, default array.array("h", [0]*length) "h"==short (16 bits signed)
} analogio_analogfastin_obj_t;
// void common_hal_analogio_analogfastin_construct(analogio_analogfastin_obj_t *self, const mcu_pin_obj_t *pin, uint8_t *buffer, uint32_t len, uint8_t bytes_per_sample, bool samples_signed, uint32_t sample_rate)
/*
void common_hal_analogio_analogfastin_construct(analogio_analogfastin_obj_t *self,
const mcu_pin_obj_t *pin,
uint8_t *buffer,
uint32_t len,
uint8_t bytes_per_sample,
bool samples_signed,
uint32_t sample_rate) {
self->pin = pin;
self->buffer = buffer;
self->len = len;
//self->bits_per_sample = bytes_per_sample * 8;
self->samples_signed = samples_signed;
self->sample_rate = sample_rate;
}
*/
void analogfastin_init(void);
#endif // MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_ANALOGIO_ANALOGFASTIN_H

View File

@ -390,6 +390,7 @@ SRC_COMMON_HAL_ALL = \
alarm/time/TimeAlarm.c \
alarm/touch/TouchAlarm.c \
analogio/AnalogIn.c \
analogio/AnalogFastIn.c \
analogio/AnalogOut.c \
analogio/__init__.c \
audiobusio/I2SOut.c \

View File

@ -1 +1,162 @@
/* AnalogFastIn.c */
/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* SPDX-FileCopyrightText: 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.
*/
#include <string.h>
#include "shared/runtime/context_manager_helpers.h"
#include "py/binary.h"
#include "py/mphal.h"
#include "py/nlr.h"
#include "py/objproperty.h"
#include "py/runtime.h"
#include "shared-bindings/microcontroller/Pin.h"
#include "shared-bindings/analogio/AnalogFastIn.h"
#include "shared-bindings/util.h"
// pin, buffer, rate
STATIC mp_obj_t analogio_analogfastin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
enum { ARG_pin, ARG_buffer, ARG_sample_rate };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_pin, MP_ARG_REQUIRED | MP_ARG_OBJ },
{ MP_QSTR_buffer, MP_ARG_OBJ | MP_ARG_REQUIRED },
{ MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
// Validate Pin
const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj);
// Buffer Pointer defined and allocated by user
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ);
// signed or unsigned, byte per sample
bool signed_samples = bufinfo.typecode == 'b' || bufinfo.typecode == 'h';
uint8_t bytes_per_sample = 1;
// Bytes Per Sample
if (bufinfo.typecode == 'h' || bufinfo.typecode == 'H') {
bytes_per_sample = 2;
} else if (bufinfo.typecode != 'b' && bufinfo.typecode != 'B' && bufinfo.typecode != BYTEARRAY_TYPECODE) {
mp_raise_ValueError(translate("sample_source buffer must be a bytearray or array of type 'h', 'H', 'b' or 'B'"));
}
// Validate sample rate here
uint32_t sample_rate = args[ARG_sample_rate].u_int;
// Create local object
analogio_analogfastin_obj_t *self = m_new_obj(analogio_analogfastin_obj_t);
self->base.type = &analogio_analogfastin_type;
// Call local intereface in ports/common-hal/analogio
common_hal_analogio_analogfastin_construct(self,
pin,
((uint8_t *)bufinfo.buf),
bufinfo.len,
bytes_per_sample,
signed_samples,
sample_rate
);
return MP_OBJ_FROM_PTR(self);
}
//| def deinit(self) -> None:
//| """Turn off the AnalogFastIn and release the pin for other use."""
//| ...
//|
STATIC mp_obj_t analogio_analogfastin_deinit(mp_obj_t self_in) {
analogio_analogfastin_obj_t *self = MP_OBJ_TO_PTR(self_in);
common_hal_analogio_analogfastin_deinit(self);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_1(analogio_analogfastin_deinit_obj, analogio_analogfastin_deinit);
STATIC void check_for_deinit(analogio_analogfastin_obj_t *self) {
if (common_hal_analogio_analogfastin_deinited(self)) {
raise_deinited_error();
}
}
//| def __enter__(self) -> AnalogFastIn:
//| """No-op used by Context Managers."""
//| ...
//|
// Provided by context manager helper.
//| def __exit__(self) -> None:
//| """Automatically deinitializes the hardware when exiting a context. See
//| :ref:`lifetime-and-contextmanagers` for more info."""
//| ...
//|
STATIC mp_obj_t analogio_analogfastin___exit__(size_t n_args, const mp_obj_t *args) {
(void)n_args;
common_hal_analogio_analogfastin_deinit(args[0]);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(analogio_analogfastin___exit___obj, 4, 4, analogio_analogfastin___exit__);
//| value: int
//| """The value on the analog pin between 0 and 65535 inclusive (16-bit). (read-only)
//|
//| Even if the underlying analog to digital converter (ADC) is lower
//| resolution, the value is 16-bit."""
//|
STATIC mp_obj_t analogio_analogfastin_obj_capture(mp_obj_t self_in) {
analogio_analogfastin_obj_t *self = MP_OBJ_TO_PTR(self_in);
check_for_deinit(self);
return MP_OBJ_NEW_SMALL_INT(common_hal_analogio_analogfastin_capture(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(analogio_analogfastin_capture_obj, analogio_analogfastin_obj_capture);
// MP_PROPERTY_GETTER(analogio_analogfastin_value_obj,
// (mp_obj_t)&analogio_analogfastin_get_value_obj);
//| reference_voltage: float
//| """The maximum voltage measurable (also known as the reference voltage) as a
//| `float` in Volts. Note the ADC value may not scale to the actual voltage linearly
//| at ends of the analog range."""
//|
STATIC const mp_rom_map_elem_t analogio_analogfastin_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&analogio_analogfastin_deinit_obj) },
{ MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) },
{ MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&analogio_analogfastin___exit___obj) },
{ MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&analogio_analogfastin_capture_obj)},
};
STATIC MP_DEFINE_CONST_DICT(analogio_analogfastin_locals_dict, analogio_analogfastin_locals_dict_table);
const mp_obj_type_t analogio_analogfastin_type = {
{ &mp_type_type },
.name = MP_QSTR_AnalogFastIn,
.make_new = analogio_analogfastin_make_new,
.locals_dict = (mp_obj_t)&analogio_analogfastin_locals_dict,
};

View File

@ -1 +1,39 @@
/* AnalogFastIn.h */
/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* SPDX-FileCopyrightText: 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.
*/
#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_ANALOGIO_ANALOGFASTIN_H
#define MICROPY_INCLUDED_SHARED_BINDINGS_ANALOGIO_ANALOGFASTIN_H
#include "common-hal/microcontroller/Pin.h"
#include "common-hal/analogio/AnalogFastIn.h"
extern const mp_obj_type_t analogio_analogfastin_type;
void common_hal_analogio_analogfastin_construct(analogio_analogfastin_obj_t *self, const mcu_pin_obj_t *pin, uint8_t *buffer, uint32_t len, uint8_t bytes_per_sample, bool samples_signed, uint32_t sample_rate);
void common_hal_analogio_analogfastin_deinit(analogio_analogfastin_obj_t *self);
bool common_hal_analogio_analogfastin_deinited(analogio_analogfastin_obj_t *self);
bool common_hal_analogio_analogfastin_capture(analogio_analogfastin_obj_t *self);
#endif // __MICROPY_INCLUDED_SHARED_BINDINGS_ANALOGIO_ANALOGFASTIN_H__

View File

@ -32,6 +32,7 @@
#include "shared-bindings/microcontroller/Pin.h"
#include "shared-bindings/analogio/__init__.h"
#include "shared-bindings/analogio/AnalogIn.h"
#include "shared-bindings/analogio/AnalogFastIn.h"
#include "shared-bindings/analogio/AnalogOut.h"
//| """Analog hardware support
@ -70,6 +71,7 @@
STATIC const mp_rom_map_elem_t analogio_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_analogio) },
{ MP_ROM_QSTR(MP_QSTR_AnalogIn), MP_ROM_PTR(&analogio_analogin_type) },
{ MP_ROM_QSTR(MP_QSTR_AnalogFastIn), MP_ROM_PTR(&analogio_analogfastin_type) },
{ MP_ROM_QSTR(MP_QSTR_AnalogOut), MP_ROM_PTR(&analogio_analogout_type) },
};