代码示例:
int main(void)
{
/* USER CODE BEGIN 1 */
uint8_t pwm_value=0; //PWM占空比
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_TIM1_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_1); //使能TIM1的PWM Channel1 输出
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
while (pwm_value < 500)
{
pwm_value++;
__HAL_TIM_SetCompare(&htim1, TIM_CHANNEL_1, pwm_value); //修改比较值,修改占空比
// TIM1->CCR1 = pwm_value; //与上方作用相同,直接修改寄存器
HAL_Delay(1);
}
while (pwm_value)
{
pwm_value--;
__HAL_TIM_SetCompare(&htim1, TIM_CHANNEL_1, pwm_value); //修改比较值,修改占空比
// TIM1->CCR1 = pwmVal; //与上方作用相同,直接修改寄存器
HAL_Delay(1);
}
HAL_Delay(200);
}
/* USER CODE END 3 */
}
|