circuitpython/ports/stm/common-hal/pulseio/PulseIn.c

289 lines
9.8 KiB
C
Raw Normal View History

2019-10-22 11:09:46 -04:00
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
2019-11-03 16:33:01 -05:00
* Copyright (c) 2019 Lucian Copeland for Adafruit Industries
2019-10-22 11:09:46 -04:00
*
* 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/pulseio/PulseIn.h"
#include <stdint.h>
#include <string.h>
#include "py/mpconfig.h"
#include "py/runtime.h"
#include "shared-bindings/microcontroller/__init__.h"
#include "shared-bindings/microcontroller/Pin.h"
2019-10-22 11:09:46 -04:00
#include "shared-bindings/pulseio/PulseIn.h"
#include "timers.h"
2019-10-22 11:09:46 -04:00
#include "peripherals/exti.h"
#include STM32_HAL_H
2020-03-10 17:16:31 -04:00
#define STM32_GPIO_PORT_SIZE 16
STATIC pulseio_pulsein_obj_t *callback_obj_ref[STM32_GPIO_PORT_SIZE];
2020-03-10 17:16:31 -04:00
STATIC TIM_HandleTypeDef tim_handle;
STATIC uint32_t overflow_count = 0;
2020-03-23 17:46:25 -04:00
STATIC uint8_t refcount = 0;
2021-03-15 09:57:36 -04:00
void pulsein_timer_event_handler(void) {
2020-03-23 17:46:25 -04:00
// Detect TIM Update event
2021-03-15 09:57:36 -04:00
if (__HAL_TIM_GET_FLAG(&tim_handle, TIM_FLAG_UPDATE) != RESET) {
if (__HAL_TIM_GET_IT_SOURCE(&tim_handle, TIM_IT_UPDATE) != RESET) {
__HAL_TIM_CLEAR_IT(&tim_handle, TIM_IT_UPDATE);
2020-03-23 17:46:25 -04:00
overflow_count++;
}
}
}
STATIC void pulsein_exti_event_handler(uint8_t num) {
2020-03-10 17:16:31 -04:00
// Grab the current time first.
2020-03-23 17:46:25 -04:00
uint32_t current_overflow = overflow_count;
uint32_t current_count = tim_handle.Instance->CNT;
2020-03-10 17:16:31 -04:00
2020-03-23 17:46:25 -04:00
// Interrupt register must be cleared manually
feat: add Blues Swan R5 support complete pin mapping for Feather pins stubbed out files needed for complilation. still to be modified 0 out all CPY modules in mpconfigboard.mk until we get the build running add csv for pin generation for STM32L4R5 add F4R5 references in peripherals files refactored out board files BECAUSE I AM AN IDIOT; add L4 series system clocks file from CubeMX took a guess at the number of USB endpoint pairs to get the build done guess was close, but wrong. It is 8 clean up peripheral DEFs Fixes build error: ``` In file included from ../../py/mpstate.h:33, from ../../py/mpstate.c:27: ../../py/misc.h: In function 'vstr_str': ../../py/misc.h:196:1: sorry, unimplemented: Thumb-1 hard-float VFP ABI static inline char *vstr_str(vstr_t *vstr) { ^~~~~~ ``` Sleuthing steps: * verify that the feather_stm32f4_express board builds correctly * put a `#error` at the bottom of the `mpstate.c` file. * build for the feather and swan boards, with V=2 to capture the build command for that file. * use a differencing tool to inspect the differences between the two invocations * inspecting the differences, I saw a missing `-mcpu=cortex-m4` I tested by adding that to the Swan build command. The file built fine (stopping at the hard error, but no other warnings.) A grep through the sources revealed where this flag was being set for the stm ports. With this commit, the build gets further, but does not complete. The next exciting episode in this unfolding coding saga is just a commit away! working build with minimal set of modules for the Blues Swan r5 chore:change header copyright name to Blues Wireless Contributors USB operational. Fixed up clocks to be hardwired for LSE no HSE case. (Trying to combine HSE in there made the code much more complex, and I don't have a board to test it out on.) USART working adds support for `ENABLE_3V3` and `DISCHARGE_3V3` pins. I am surprised that pin definitions are quite low-level and don't include default direction and state, so the code currently has to initialize `ENABLE_3V3` pin as output. The LED takes over a second to discharge, so I wonder if the board startup code is not having the desired affect. short circuit implementation of backup memory for the STM32L4 all the ports remove company name from board name to be consistent with the Arduino board definition. add default pins for I2C, SPI and UART, so that `board.I2C` et al. works as expected. Confirmed I2C timing. fix board name fix incorrect pin definition. add test to allow manual check of each output pin analog IO code changes for WebUSB. Doesn't appear to work, will revisit later. ensure that `sys.platform` is available checkin missing file feat: make room for a larger filesystem so the sensor tutorial will fit on the device. fix:(stm32l4r5zi.csv): merged AF0-7 and AF8-15 into single lines and removed extraneous headers mixed in with the data. fix(parse_af_csv.py): pin index in the csv is 0 not 1, and AF index made 1 larger chore(Swan R5): update peripherals pins from `parse_af_csv.py` output optimize flash sector access
2021-07-29 18:06:31 -04:00
#if CPY_STM32L4
EXTI->PR1 = 1 << num;
#else
2020-03-23 17:46:25 -04:00
EXTI->PR = 1 << num;
feat: add Blues Swan R5 support complete pin mapping for Feather pins stubbed out files needed for complilation. still to be modified 0 out all CPY modules in mpconfigboard.mk until we get the build running add csv for pin generation for STM32L4R5 add F4R5 references in peripherals files refactored out board files BECAUSE I AM AN IDIOT; add L4 series system clocks file from CubeMX took a guess at the number of USB endpoint pairs to get the build done guess was close, but wrong. It is 8 clean up peripheral DEFs Fixes build error: ``` In file included from ../../py/mpstate.h:33, from ../../py/mpstate.c:27: ../../py/misc.h: In function 'vstr_str': ../../py/misc.h:196:1: sorry, unimplemented: Thumb-1 hard-float VFP ABI static inline char *vstr_str(vstr_t *vstr) { ^~~~~~ ``` Sleuthing steps: * verify that the feather_stm32f4_express board builds correctly * put a `#error` at the bottom of the `mpstate.c` file. * build for the feather and swan boards, with V=2 to capture the build command for that file. * use a differencing tool to inspect the differences between the two invocations * inspecting the differences, I saw a missing `-mcpu=cortex-m4` I tested by adding that to the Swan build command. The file built fine (stopping at the hard error, but no other warnings.) A grep through the sources revealed where this flag was being set for the stm ports. With this commit, the build gets further, but does not complete. The next exciting episode in this unfolding coding saga is just a commit away! working build with minimal set of modules for the Blues Swan r5 chore:change header copyright name to Blues Wireless Contributors USB operational. Fixed up clocks to be hardwired for LSE no HSE case. (Trying to combine HSE in there made the code much more complex, and I don't have a board to test it out on.) USART working adds support for `ENABLE_3V3` and `DISCHARGE_3V3` pins. I am surprised that pin definitions are quite low-level and don't include default direction and state, so the code currently has to initialize `ENABLE_3V3` pin as output. The LED takes over a second to discharge, so I wonder if the board startup code is not having the desired affect. short circuit implementation of backup memory for the STM32L4 all the ports remove company name from board name to be consistent with the Arduino board definition. add default pins for I2C, SPI and UART, so that `board.I2C` et al. works as expected. Confirmed I2C timing. fix board name fix incorrect pin definition. add test to allow manual check of each output pin analog IO code changes for WebUSB. Doesn't appear to work, will revisit later. ensure that `sys.platform` is available checkin missing file feat: make room for a larger filesystem so the sensor tutorial will fit on the device. fix:(stm32l4r5zi.csv): merged AF0-7 and AF8-15 into single lines and removed extraneous headers mixed in with the data. fix(parse_af_csv.py): pin index in the csv is 0 not 1, and AF index made 1 larger chore(Swan R5): update peripherals pins from `parse_af_csv.py` output optimize flash sector access
2021-07-29 18:06:31 -04:00
#endif
2020-03-10 17:16:31 -04:00
pulseio_pulsein_obj_t *self = callback_obj_ref[num];
2021-03-15 09:57:36 -04:00
if (!self) {
return;
}
2020-03-10 17:16:31 -04:00
if (self->first_edge) {
// first pulse is opposite state from idle
bool state = HAL_GPIO_ReadPin(pin_port(self->pin->port), pin_mask(self->pin->number));
2021-03-15 09:57:36 -04:00
if (self->idle_state != state) {
2020-03-10 17:16:31 -04:00
self->first_edge = false;
}
} else {
2020-04-14 20:09:48 -04:00
uint32_t total_diff = current_count + 0x10000 * (current_overflow - self->last_overflow) - self->last_count;
2020-03-23 17:46:25 -04:00
// Cap duration at 16 bits.
2020-04-14 20:09:48 -04:00
uint16_t duration = MIN(0xffff, total_diff);
2020-03-10 17:16:31 -04:00
uint16_t i = (self->start + self->len) % self->maxlen;
self->buffer[i] = duration;
if (self->len < self->maxlen) {
self->len++;
} else {
2022-04-27 22:22:33 -04:00
self->start = (self->start + 1) % self->maxlen;
2020-03-10 17:16:31 -04:00
}
}
2020-03-23 17:46:25 -04:00
self->last_count = current_count;
self->last_overflow = current_overflow;
2020-03-10 17:16:31 -04:00
}
2019-10-22 11:09:46 -04:00
void pulsein_reset(void) {
2020-03-10 17:16:31 -04:00
// Disable all active interrupts and clear array
for (uint i = 0; i < STM32_GPIO_PORT_SIZE; i++) {
if (callback_obj_ref[i] != NULL) {
stm_peripherals_exti_disable(callback_obj_ref[i]->pin->number);
2020-03-10 17:16:31 -04:00
}
}
memset(callback_obj_ref, 0, sizeof(callback_obj_ref));
2020-03-23 17:46:25 -04:00
HAL_TIM_Base_DeInit(&tim_handle);
tim_clock_disable(stm_peripherals_timer_get_index(tim_handle.Instance));
memset(&tim_handle, 0, sizeof(tim_handle));
2020-03-23 17:46:25 -04:00
refcount = 0;
2019-10-22 11:09:46 -04:00
}
2021-03-15 09:57:36 -04:00
void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin,
uint16_t maxlen, bool idle_state) {
2020-03-10 17:16:31 -04:00
// STM32 has one shared EXTI for each pin number, 0-15
if (!stm_peripherals_exti_is_free(pin->number)) {
mp_raise_RuntimeError(translate("Pin interrupt already in use"));
2020-03-10 17:16:31 -04:00
}
// Allocate pulse buffer
2021-03-15 09:57:36 -04:00
self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t), false);
2020-03-10 17:16:31 -04:00
if (self->buffer == NULL) {
// TODO: free the EXTI here?
m_malloc_fail(maxlen * sizeof(uint16_t));
2020-03-10 17:16:31 -04:00
}
2020-03-10 17:16:31 -04:00
// Set internal variables
self->pin = pin;
self->maxlen = maxlen;
self->idle_state = idle_state;
self->start = 0;
self->len = 0;
self->first_edge = true;
self->paused = false;
2020-03-23 17:46:25 -04:00
self->last_count = 0;
self->last_overflow = 0;
if (HAL_TIM_Base_GetState(&tim_handle) == HAL_TIM_STATE_RESET) {
// Find a suitable timer
2021-03-15 09:57:36 -04:00
TIM_TypeDef *tim_instance = stm_peripherals_find_timer();
stm_peripherals_timer_reserve(tim_instance);
// Set ticks to 1us
uint32_t source = stm_peripherals_timer_get_source_freq(tim_instance);
2021-03-15 09:57:36 -04:00
uint32_t prescaler = source / 1000000;
// Enable clocks and IRQ, set callback
stm_peripherals_timer_preinit(tim_instance, 4, pulsein_timer_event_handler);
// Set the new period
tim_handle.Instance = tim_instance;
tim_handle.Init.Prescaler = prescaler - 1;
2021-03-15 09:57:36 -04:00
tim_handle.Init.Period = 0x10000 - 1; // 65 ms period (maximum)
HAL_TIM_Base_Init(&tim_handle);
2020-03-23 17:46:25 -04:00
// Set registers manually
tim_handle.Instance->SR = 0; // Prevent the SR from triggering an interrupt
tim_handle.Instance->CR1 |= TIM_CR1_CEN; // Resume timer
tim_handle.Instance->CR1 |= TIM_CR1_URS; // Disable non-overflow interrupts
__HAL_TIM_ENABLE_IT(&tim_handle, TIM_IT_UPDATE);
2020-03-23 17:46:25 -04:00
overflow_count = 0;
}
// Add to active PulseIns
refcount++;
2020-03-10 17:16:31 -04:00
if (!stm_peripherals_exti_reserve(pin->number)) {
mp_raise_RuntimeError(translate("Pin interrupt already in use"));
}
2020-03-10 17:16:31 -04:00
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = pin_mask(pin->number);
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(pin_port(pin->port), &GPIO_InitStruct);
stm_peripherals_exti_set_callback(pulsein_exti_event_handler, pin->number);
// Store PulseIn object for use in callback
callback_obj_ref[pin->number] = self;
2020-03-10 17:16:31 -04:00
// Interrupt starts immediately
stm_peripherals_exti_enable(pin->number);
common_hal_mcu_pin_claim(pin);
2019-10-22 11:09:46 -04:00
}
2021-03-15 09:57:36 -04:00
bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self) {
return self->pin == NULL;
2019-10-22 11:09:46 -04:00
}
2021-03-15 09:57:36 -04:00
void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) {
2020-03-10 17:16:31 -04:00
if (common_hal_pulseio_pulsein_deinited(self)) {
return;
}
// Remove pulsein slot from shared array
callback_obj_ref[self->pin->number] = NULL;
stm_peripherals_exti_free(self->pin->number);
2020-03-10 17:16:31 -04:00
reset_pin_number(self->pin->port, self->pin->number);
self->pin = NULL;
2020-03-23 17:46:25 -04:00
refcount--;
if (refcount == 0) {
2020-07-22 13:58:57 -04:00
stm_peripherals_timer_free(tim_handle.Instance);
2020-03-23 17:46:25 -04:00
}
2019-10-22 11:09:46 -04:00
}
void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self) {
stm_peripherals_exti_disable(self->pin->number);
2020-03-10 17:16:31 -04:00
self->paused = true;
2019-10-22 11:09:46 -04:00
}
2021-03-15 09:57:36 -04:00
void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t *self, uint16_t trigger_duration) {
2020-03-10 17:16:31 -04:00
// Make sure we're paused.
2021-03-15 09:57:36 -04:00
if (!self->paused) {
2020-03-10 17:16:31 -04:00
common_hal_pulseio_pulsein_pause(self);
}
// Send the trigger pulse.
if (trigger_duration > 0) {
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = pin_mask(self->pin->number);
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(pin_port(self->pin->port), &GPIO_InitStruct);
HAL_GPIO_WritePin(pin_port(self->pin->port), pin_mask(self->pin->number), !self->idle_state);
common_hal_mcu_delay_us((uint32_t)trigger_duration);
HAL_GPIO_WritePin(pin_port(self->pin->port), pin_mask(self->pin->number), self->idle_state);
GPIO_InitStruct.Pin = pin_mask(self->pin->number);
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(pin_port(self->pin->port), &GPIO_InitStruct);
}
self->first_edge = true;
self->paused = false;
2020-03-23 17:46:25 -04:00
self->last_count = 0;
self->last_overflow = 0;
2020-03-10 17:16:31 -04:00
stm_peripherals_exti_enable(self->pin->number);
2019-10-22 11:09:46 -04:00
}
void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t *self) {
stm_peripherals_exti_disable(self->pin->number);
2020-03-10 17:16:31 -04:00
self->start = 0;
self->len = 0;
stm_peripherals_exti_enable(self->pin->number);
2019-10-22 11:09:46 -04:00
}
uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t *self, int16_t index) {
stm_peripherals_exti_disable(self->pin->number);
2020-03-10 17:16:31 -04:00
if (index < 0) {
index += self->len;
}
if (index < 0 || index >= self->len) {
stm_peripherals_exti_enable(self->pin->number);
mp_raise_IndexError_varg(translate("%q out of range"), MP_QSTR_index);
2020-03-10 17:16:31 -04:00
}
uint16_t value = self->buffer[(self->start + index) % self->maxlen];
stm_peripherals_exti_enable(self->pin->number);
2020-03-10 17:16:31 -04:00
return value;
2019-10-22 11:09:46 -04:00
}
2021-03-15 09:57:36 -04:00
uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t *self) {
2020-03-10 17:16:31 -04:00
if (self->len == 0) {
mp_raise_IndexError_varg(translate("pop from empty %q"), MP_QSTR_PulseIn);
2020-03-10 17:16:31 -04:00
}
stm_peripherals_exti_disable(self->pin->number);
2020-03-10 17:16:31 -04:00
uint16_t value = self->buffer[self->start];
self->start = (self->start + 1) % self->maxlen;
self->len--;
stm_peripherals_exti_enable(self->pin->number);
2020-03-10 17:16:31 -04:00
return value;
2019-10-22 11:09:46 -04:00
}
2021-03-15 09:57:36 -04:00
uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t *self) {
2020-03-10 17:16:31 -04:00
return self->maxlen;
2019-10-22 11:09:46 -04:00
}
2021-03-15 09:57:36 -04:00
bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t *self) {
2020-03-10 17:16:31 -04:00
return self->paused;
2019-10-22 11:09:46 -04:00
}
2021-03-15 09:57:36 -04:00
uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t *self) {
2020-03-10 17:16:31 -04:00
return self->len;
}