Prvi primer:
Moj input: write c function for stm32f051 that initializes TIM1 channel 1 in pwm mode with frequency of 1kHz
- Koda: Izberi vse
#include "stm32f0xx.h"
void init_tim1_ch1_pwm(void)
{
// Enable the clock for TIM1 and GPIOA
RCC->APB2ENR |= RCC_APB2ENR_TIM1EN | RCC_APB2ENR_GPIOAEN;
// Set PA8 (TIM1_CH1) to alternate function mode
GPIOA->MODER |= GPIO_MODER_MODER8_1;
// Set PA8 (TIM1_CH1) to alternate function 1 (TIM1_CH1)
GPIOA->AFR[1] |= 0x1;
// Set the prescaler value to 48000, which will give a 1 kHz PWM frequency
// with a 48 MHz system clock
TIM1->PSC = 48000;
// Set the auto-reload value to 1000, which will give a 1 kHz PWM frequency
TIM1->ARR = 1000;
// Set the output compare value to 500, which will give a 50% duty cycle
TIM1->CCR1 = 500;
// Enable output compare channel 1
TIM1->CCER |= TIM_CCER_CC1E;
// Set the output compare mode to PWM mode 1
TIM1->CCMR1 |= TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1;
// Enable the TIM1 counter
TIM1->CR1 |= TIM_CR1_CEN;
}
Moj input: use HAL
- Koda: Izberi vse
#include "stm32f0xx_hal.h"
void init_tim1_ch1_pwm(TIM_HandleTypeDef *htim)
{
// Enable the clock for TIM1 and GPIOA
__HAL_RCC_TIM1_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
// Configure PA8 (TIM1_CH1) as an alternate function
GPIO_InitTypeDef gpio_init;
gpio_init.Pin = GPIO_PIN_8;
gpio_init.Mode = GPIO_MODE_AF_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init.Alternate = GPIO_AF1_TIM1;
HAL_GPIO_Init(GPIOA, &gpio_init);
// Initialize the TIM1 handle
htim->Instance = TIM1;
htim->Init.Prescaler = 48000; // Set the prescaler value to 48000
htim->Init.Period = 1000; // Set the auto-reload value to 1000
htim->Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim->Init.CounterMode = TIM_COUNTERMODE_UP;
htim->Init.RepetitionCounter = 0;
HAL_TIM_PWM_Init(htim);
// Configure TIM1 channel 1 as a PWM output
TIM_OC_InitTypeDef tim_oc_init;
tim_oc_init.OCMode = TIM_OCMODE_PWM1;
tim_oc_init.Pulse = 500; // Set the output compare value to 500
tim_oc_init.OCPolarity = TIM_OCPOLARITY_HIGH;
tim_oc_init.OCNPolarity = TIM_OCNPOLARITY_HIGH;
tim_oc_init.OCFastMode = TIM_OCFAST_DISABLE;
tim_oc_init.OCIdleState = TIM_OCIDLESTATE_RESET;
tim_oc_init.OCNIdleState = TIM_OCNIDLESTATE_RESET;
HAL_TIM_PWM_ConfigChannel(htim, &tim_oc_init, TIM_CHANNEL_1);
// Start the PWM output
HAL_TIM_PWM_Start(htim, TIM_CHANNEL_1);
}
Kode nisem testiral, ampak
