#include "stm32f1xx_hal.h"
TIM_HandleTypeDef htim3;
static void Gpio_Init(void);
static void Tim3_Init(void);
static void setPWM(TIM_HandleTypeDef, uint32_t, uint16_t, uint16_t);
int main(void)
{
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Initialize all configured peripherals */
Gpio_Init();
Tim3_Init();
HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
/* Infinite loop */
while (1)
{
for(int i=0; i<256; i++){
setPWM(htim3, TIM_CHANNEL_1, 255, i);
HAL_Delay(1);
}
}
}
/* Systick handler */
void SysTick_Handler(void)
{
HAL_IncTick();
}
void Gpio_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct ={0};
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
/* Timer init function */
void Tim3_Init(void)
{
__HAL_RCC_TIM3_CLK_ENABLE();
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
htim3.Instance = TIM3;
htim3.Init.Prescaler = 8-1;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 4095;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
HAL_TIM_Base_Init(&htim3);
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig);
HAL_TIM_PWM_Init(&htim3);
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig);
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1);
}
void setPWM(TIM_HandleTypeDef timer, uint32_t channel, uint16_t period, uint16_t pulse)
{
HAL_TIM_PWM_Stop(&timer, channel); // stop generation of pwm
TIM_OC_InitTypeDef sConfigOC;
timer.Init.Period = period; // set the period duration
HAL_TIM_PWM_Init(&timer); // reinititialise with new period value
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = pulse; // set the pulse duration
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
HAL_TIM_PWM_ConfigChannel(&timer, &sConfigOC, channel);
HAL_TIM_PWM_Start(&timer, channel); // start pwm generation
}