circuitpython/ports/stm32f4/common-hal/pulseio/PWMOut.c
Hierophect cb491e855c WIP
2019-10-27 14:31:25 -04:00

343 lines
12 KiB
C

/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Dan Halbert for Adafruit Industries
* Copyright (c) 2019 Lucian Copeland for Adafruit Industries
* Uses code from Micropython, Copyright (c) 2013-2016 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 <stdint.h>
#include "py/runtime.h"
#include "common-hal/pulseio/PWMOut.h"
#include "shared-bindings/pulseio/PWMOut.h"
#include "supervisor/shared/translate.h"
#include "stm32f4xx_hal.h"
#define PWM_MAX_FREQ 6000000
#define ALL_CLOCKS 0xFFFF
STATIC uint8_t reserved_tim[TIM_BANK_ARRAY_LEN];
STATIC uint32_t tim_frequencies[TIM_BANK_ARRAY_LEN];
STATIC void tim_clock_enable(uint16_t mask);
STATIC void tim_clock_disable(uint16_t mask);
// Get the frequency (in Hz)
static uint32_t timer_get_source_freq(uint32_t tim_id) {
uint32_t source, clk_div;
if (tim_id == 1 || (8 <= tim_id && tim_id <= 11)) {
// TIM{1,8,9,10,11} are on APB2
source = HAL_RCC_GetPCLK2Freq();
clk_div = RCC->CFGR & RCC_CFGR_PPRE2;
} else {
// TIM{2,3,4,5,6,7,12,13,14} are on APB1
source = HAL_RCC_GetPCLK1Freq();
clk_div = RCC->CFGR & RCC_CFGR_PPRE1;
}
if (clk_div != 0) {
// APB prescaler for this timer is > 1
source *= 2;
}
return source;
}
void pwmout_reset(void) {
tim_clock_disable(ALL_CLOCKS);
}
void common_hal_pulseio_pwmout_never_reset(pulseio_pwmout_obj_t *self) {
}
void common_hal_pulseio_pwmout_reset_ok(pulseio_pwmout_obj_t *self) {
}
pwmout_result_t common_hal_pulseio_pwmout_construct(pulseio_pwmout_obj_t* self,
const mcu_pin_obj_t* pin,
uint16_t duty,
uint32_t frequency,
bool variable_frequency) {
if (frequency == 0 || frequency > 6000000) {
return PWMOUT_INVALID_FREQUENCY;
}
TIM_TypeDef * TIMx;
//TODO: style/safety question, use this instead?
//uint8_t tim_num_pins = TIM_PIN_ARRAY_LEN;
uint8_t tim_num = sizeof(mcu_tim_pin_list)/sizeof(*mcu_tim_pin_list);
//TODO: use an enum to make this prettier?
bool tim_chan_taken = false;
bool tim_taken_f_mismatch = false;
bool var_freq_mismatch = false;
bool first_time_setup = true;
for(uint i = 0; i < tim_num; i++) {
//if pin is same
if(mcu_tim_pin_list[i].pin = pin) {
//check if the timer has a channel active
if (reserved_tim[mcu_tim_pin_list[i].tim_index] != 0) {
//is it the same channel? (or all channels reserved by a var-freq)
if(reserved_tim[mcu_tim_pin_list[i].tim_index-1] & 1<<(mcu_tim_pin_list[i].channel_index-1)) {
tim_chan_taken = true;
continue; //keep looking, might be another viable option
}
//If the frequencies are the same it's ok
if(tim_frequencies[mcu_tim_pin_list[i].tim_index-1] != frequency) {
tim_taken_f_mismatch = true;
continue; //keep looking
}
//you can't put a variable frequency on a partially reserved timer
if(variable_frequency) {
var_freq_mismatch = true;
continue; //keep looking
}
first_time_setup = false; //skip setting up the timer
}
//No problems taken, so set it up
self->tim = &mcu_tim_pin_list[i];
break;
}
}
//handle valid/invalid timer instance
//TODO: why doesn't PWM handle its own value errors like every other module?
//The samd value errors don't really fit for STM32.
if(self->tim!=NULL) {
//create instance
TIMx = mcu_tim_banks[self->tim->tim_index-1];
//reserve timer/channel
if (variable_frequency) {
reserved_tim[self->tim->tim_index-1] = 0x0F;
} else {
reserved_tim[self->tim->tim_index-1] |= 1<<self->tim->channel_index-1;
}
} else { //no match found
if (tim_chan_taken) {
mp_raise_ValueError(translate("Timer hardware is reserved"));
//return PWMOUT_ALL_TIMERS_ON_PIN_IN_USE;
} else if (tim_taken_f_mismatch) {
mp_raise_ValueError(translate("Frequency mismatch with existing reserved channel"));
//return PWMOUT_INVALID_FREQUENCY;
} else if (var_freq_mismatch) {
mp_raise_ValueError(translate("Cannot vary frequency of a partially reserved timer"));
//return PWMOUT_INVALID_FREQUENCY; //I guess?
} else {
mp_raise_ValueError(translate("Invalid pins"));
//return PWMOUT_INVALID_PIN;
}
}
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = pin_mask(pin->number);
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = self->tim->altfn_index;
HAL_GPIO_Init(pin_port(pin->port), &GPIO_InitStruct);
//TODO: factor all of these into periph.c?
tim_clock_enable(1<<(self->tim->tim_index - 1));
//translate channel into handle value
switch (self->tim->channel_index) {
case 1: self->channel = TIM_CHANNEL_1; break;
case 2: self->channel = TIM_CHANNEL_2; break;
case 3: self->channel = TIM_CHANNEL_3; break;
case 4: self->channel = TIM_CHANNEL_4; break;
}
uint32_t source_freq = timer_get_source_freq(self->tim->tim_index);
uint32_t period = PWM_MAX_FREQ/frequency;
mp_printf(&mp_plat_print, "SysCoreClock: %d\n", SystemCoreClock);
mp_printf(&mp_plat_print, "Source Freq: %d\n", source_freq);
mp_printf(&mp_plat_print, "Timer Freq: %d\n", source_freq/(source_freq / PWM_MAX_FREQ));
mp_printf(&mp_plat_print, "Actual Freq: %d\n", (source_freq/(source_freq / PWM_MAX_FREQ))/period);
mp_printf(&mp_plat_print, "Period: %d\n", (PWM_MAX_FREQ/frequency));
//Timer init
self->handle.Instance = TIMx;
self->handle.Init.Period = period - 1;
self->handle.Init.Prescaler = (source_freq / PWM_MAX_FREQ) - 1; // TIM runs at ~6MHz
self->handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
self->handle.Init.CounterMode = TIM_COUNTERMODE_UP;
self->handle.Init.RepetitionCounter = 0;
//only run init if this is the first instance of this timer
if(first_time_setup) {
if(HAL_TIM_PWM_Init(&self->handle) != HAL_OK) {
mp_raise_ValueError(translate("Timer Init Error"));
}
}
//Channel/PWM init
self->chan_handle.OCMode = TIM_OCMODE_PWM1;
self->chan_handle.Pulse = (period*duty)/100 - 1;
self->chan_handle.OCPolarity = TIM_OCPOLARITY_LOW;
self->chan_handle.OCFastMode = TIM_OCFAST_DISABLE;
self->chan_handle.OCNPolarity = TIM_OCNPOLARITY_LOW; // needed for TIM1 and TIM8
self->chan_handle.OCIdleState = TIM_OCIDLESTATE_SET; // needed for TIM1 and TIM8
self->chan_handle.OCNIdleState = TIM_OCNIDLESTATE_SET; // needed for TIM1 and TIM8
if(HAL_TIM_PWM_ConfigChannel(&self->handle, &self->chan_handle, self->channel) != HAL_OK) {
mp_raise_ValueError(translate("Channel Init Error"));
}
if(HAL_TIM_PWM_Start(&self->handle, self->channel) != HAL_OK) {
mp_raise_ValueError(translate("Error starting PWM"));
}
self->variable_frequency = variable_frequency;
self->frequency = frequency;
self->duty_cycle = duty;
return PWMOUT_OK;
}
bool common_hal_pulseio_pwmout_deinited(pulseio_pwmout_obj_t* self) {
return self->tim == mp_const_none;
}
void common_hal_pulseio_pwmout_deinit(pulseio_pwmout_obj_t* self) {
if (common_hal_pulseio_pwmout_deinited(self)) {
return;
}
//var freq shuts down entire timer, others just their channel
if(self->variable_frequency) {
reserved_tim[self->tim->tim_index-1] = 0x00;
} else {
reserved_tim[self->tim->tim_index-1] &= !(1<<self->tim->channel_index);
HAL_TIM_PWM_Stop(&self->handle, self->channel);
}
reset_pin_number(self->tim->pin->port,self->tim->pin->number);
self->tim = mp_const_none;
//if reserved timer has no active channels, we can disable it
if (!reserved_tim[self->tim->tim_index-1]) {
tim_frequencies[self->tim->tim_index-1] = 0x00;
tim_clock_disable(1<<(self->tim->tim_index-1));
}
}
void common_hal_pulseio_pwmout_set_duty_cycle(pulseio_pwmout_obj_t* self, uint16_t duty_cycle) {
HAL_TIM_PWM_Stop(&self->handle, self->channel);
self->chan_handle.Pulse = ((PWM_MAX_FREQ/self->frequency)*duty_cycle)/100 - 1;
if(HAL_TIM_PWM_ConfigChannel(&self->handle, &self->chan_handle, self->channel) != HAL_OK) {
mp_raise_ValueError(translate("Channel Re-Init Error"));
}
if(HAL_TIM_PWM_Start(&self->handle, self->channel) != HAL_OK) {
mp_raise_ValueError(translate("Error restarting PWM"));
}
}
uint16_t common_hal_pulseio_pwmout_get_duty_cycle(pulseio_pwmout_obj_t* self) {
return self->duty_cycle;
}
void common_hal_pulseio_pwmout_set_frequency(pulseio_pwmout_obj_t* self, uint32_t frequency) {
}
uint32_t common_hal_pulseio_pwmout_get_frequency(pulseio_pwmout_obj_t* self) {
return 0;
}
bool common_hal_pulseio_pwmout_get_variable_frequency(pulseio_pwmout_obj_t* self) {
return self->variable_frequency;
}
STATIC void tim_clock_enable(uint16_t mask) {
#ifdef TIM1
if(mask & 1<<0) __HAL_RCC_TIM1_CLK_ENABLE();
#endif
#ifdef TIM2
if(mask & 1<<1) __HAL_RCC_TIM2_CLK_ENABLE();
#endif
#ifdef TIM3
if(mask & 1<<2) __HAL_RCC_TIM3_CLK_ENABLE();
#endif
#ifdef TIM4
if(mask & 1<<3) __HAL_RCC_TIM4_CLK_ENABLE();
#endif
#ifdef TIM5
if(mask & 1<<4) __HAL_RCC_TIM5_CLK_ENABLE();
#endif
//6 and 7 are reserved ADC timers
#ifdef TIM8
if(mask & 1<<7) __HAL_RCC_TIM8_CLK_ENABLE();
#endif
#ifdef TIM9
if(mask & 1<<8) __HAL_RCC_TIM9_CLK_ENABLE();
#endif
#ifdef TIM10
if(mask & 1<<9) __HAL_RCC_TIM10_CLK_ENABLE();
#endif
#ifdef TIM11
if(mask & 1<<10) __HAL_RCC_TIM11_CLK_ENABLE();
#endif
#ifdef TIM12
if(mask & 1<<11) __HAL_RCC_TIM12_CLK_ENABLE();
#endif
#ifdef TIM13
if(mask & 1<<12) __HAL_RCC_TIM13_CLK_ENABLE();
#endif
#ifdef TIM14
if(mask & 1<<13) __HAL_RCC_TIM14_CLK_ENABLE();
#endif
}
STATIC void tim_clock_disable(uint16_t mask) {
#ifdef TIM1
if(mask & 1<<0) __HAL_RCC_TIM1_CLK_DISABLE();
#endif
#ifdef TIM2
if(mask & 1<<1) __HAL_RCC_TIM2_CLK_DISABLE();
#endif
#ifdef TIM3
if(mask & 1<<2) __HAL_RCC_TIM3_CLK_DISABLE();
#endif
#ifdef TIM4
if(mask & 1<<3) __HAL_RCC_TIM4_CLK_DISABLE();
#endif
#ifdef TIM5
if(mask & 1<<4) __HAL_RCC_TIM5_CLK_DISABLE();
#endif
//6 and 7 are reserved ADC timers
#ifdef TIM8
if(mask & 1<<7) __HAL_RCC_TIM8_CLK_DISABLE();
#endif
#ifdef TIM9
if(mask & 1<<8) __HAL_RCC_TIM9_CLK_DISABLE();
#endif
#ifdef TIM10
if(mask & 1<<9) __HAL_RCC_TIM10_CLK_DISABLE();
#endif
#ifdef TIM11
if(mask & 1<<10) __HAL_RCC_TIM11_CLK_DISABLE();
#endif
#ifdef TIM12
if(mask & 1<<11) __HAL_RCC_TIM12_CLK_DISABLE();
#endif
#ifdef TIM13
if(mask & 1<<12) __HAL_RCC_TIM13_CLK_DISABLE();
#endif
#ifdef TIM14
if(mask & 1<<13) __HAL_RCC_TIM14_CLK_DISABLE();
#endif
}