Skip to content
This repository has been archived by the owner on Apr 2, 2023. It is now read-only.

Commit

Permalink
Add PWM frequency & Duty Cycle offset
Browse files Browse the repository at this point in the history
  • Loading branch information
ziteh committed Oct 5, 2021
1 parent 451ad22 commit d1024bc
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
11 changes: 7 additions & 4 deletions lib/f103rb_pwm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,25 +93,28 @@ namespace F103RB
TIM_Cmd(_Timer, DISABLE); // The specified TIM peripheral
}

void PWM::Set_Frequency(uint16_t frequency)
void PWM::Set_Frequency(uint16_t value)
{
/**
* TIM_Period = ((System_Frequency / TIM_Prescaler) / PWM_Frequency) - 1
*
* The Maximum of System_Frequency is 72MHz (STM32F103RB)
*/
float frequency = value + this->FrequencyOffset;

_TIM_TimeBaseStructure.TIM_Prescaler = 100;
_TIM_TimeBaseStructure.TIM_Period = ((this->_RCC_Clocks.SYSCLK_Frequency / _TIM_TimeBaseStructure.TIM_Prescaler) / frequency) - 1;

this->Init_Timer();
}

void PWM::Set_DutyCycle(uint16_t dutyCycle)
void PWM::Set_DutyCycle(uint16_t value)
{
if (_TIM_OCInitStructure.TIM_Pulse != this->ConvertDutyCycleToPulse(dutyCycle))
uint16_t targetDutyCycle = this->ConvertDutyCycleToPulse(value) + this->DutyCycleOffset;

if (_TIM_OCInitStructure.TIM_Pulse != targetDutyCycle)
{
_TIM_OCInitStructure.TIM_Pulse = this->ConvertDutyCycleToPulse(dutyCycle);
_TIM_OCInitStructure.TIM_Pulse = targetDutyCycle;
this->Init_Timer();
}
}
Expand Down
5 changes: 4 additions & 1 deletion lib/f103rb_pwm.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ namespace F103RB
uint16_t ConvertDutyCycleToPulse(uint16_t dutyCycle);

public:
float FrequencyOffset = 0.0;
float DutyCycleOffset = 0.0;

PWM(GPIO_PortPinTypeDef portPin,
TIM_TypeDef *Timer,
PWM_TimerChannelTypeDef channel);
Expand All @@ -45,7 +48,7 @@ namespace F103RB
void Disable(void);

void Set_Frequency(uint16_t frequency);
void Set_DutyCycle(uint16_t dutyCycle);
void Set_DutyCycle(uint16_t value);

uint16_t Get_Frequency(void);
uint16_t Get_DutyCycle(void);
Expand Down

0 comments on commit d1024bc

Please sign in to comment.