You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

84 lines
2.7 KiB

#include "ztim.hpp"
#include "irq_dispatcher/ztim_irq_dispatcher.hpp"
using namespace iflytop;
void ZTIM::initialize(zchip_tim_t *htim, mode_t mode) {
m_htim = htim;
m_mode = mode;
if (m_mode == ktm_pwm) {
ZEARLY_ASSERT(m_htim->Init.AutoReloadPreload == TIM_AUTORELOAD_PRELOAD_ENABLE);
ZEARLY_ASSERT(m_htim->Init.CounterMode == TIM_COUNTERMODE_UP);
ZEARLY_ASSERT(m_htim->Channel)
}
}
ZTIM::mode_t ZTIM::getMode() { return m_mode; }
/******************************************************
* kTimMode_timer *
******************************************************/
/**
* @brief startTimer
*
* @param periodus 定时器周期
* @param onirq 回调函数,如果为null,则使用上次注册的回调函数
*/
void ZTIM::simpleTimer_startByPeriod(uint32_t periodus) { simpleTimer_startByFreq(1000000.0 / periodus); }
void ZTIM::simpleTimer_startByFreq(float freq) {
ZEARLY_ASSERT(m_htim->Init.AutoReloadPreload == TIM_AUTORELOAD_PRELOAD_ENABLE)
m_timer_start = true;
uint32_t prescaler = 0;
uint32_t autoreload = 0;
uint32_t timClkFreq = chip_get_timer_clock_sorce_freq(m_htim);
ZEARLY_ASSERT(chip_calculate_prescaler_and_autoreload_by_expect_freq(timClkFreq, freq, &prescaler, &autoreload));
__HAL_TIM_SET_AUTORELOAD(m_htim, autoreload);
__HAL_TIM_SET_PRESCALER(m_htim, prescaler);
HAL_TIM_Base_Start_IT(m_htim);
ZIRQDispatcher::instance().regListener([this](zchip_tim_t *tim) {
if (tim != m_htim) return;
if (m_timer_start && m_simpleTimer_cb) m_simpleTimer_cb();
});
}
void ZTIM::simpleTimer_stop() {
m_timer_start = false;
HAL_TIM_Base_Stop(m_htim);
}
void ZTIM::setPWMFreq(float freq) {
uint32_t prescaler = 0;
uint32_t autoreload = 0;
uint32_t timClkFreq = chip_get_timer_clock_sorce_freq(m_htim);
ZEARLY_ASSERT(chip_calculate_prescaler_and_autoreload_by_expect_freq(timClkFreq, freq, &prescaler, &autoreload));
__HAL_TIM_SET_AUTORELOAD(m_htim, autoreload);
__HAL_TIM_SET_PRESCALER(m_htim, prescaler);
}
void ZTIM::setPWMPolarity(uint32_t Channel, uint32_t Polarity) { m_timpwmPolarity[Channel] = Polarity; }
void ZTIM::startPWM(uint32_t Channel, float duty) {
/**
* @brief
*/
TIM_OC_InitTypeDef sConfigOC = {0};
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = duty / 100.0 * __HAL_TIM_GET_AUTORELOAD(m_htim);
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if (HAL_TIM_PWM_ConfigChannel(m_htim, &sConfigOC, TIM_CHANNEL_4) != HAL_OK) {
Error_Handler();
}
HAL_TIM_PWM_Start(m_htim, Channel);
}
void ZTIM::stopPWM(uint32_t Channel) { startPWM(Channel, 100); }