Timer & PWM Exercise 2

1. Create a new project and use software to generate relevant codes

Select a good chip, create a new project, and the next step is to configure

1. Configure RCC

as the picture shows:
insert image description here

2. Configure SYS

as shown in the picture
insert image description here

3. Configure timer 2

Configure as shown
insert image description here
insert image description here

4. Clock configuration

As shown in the figure, it is the same configuration as the previous experiment
insert image description here

5. Complete the file creation

insert image description here
insert image description here
After everything is ready, you can save the generated code

Two, keil code operation

Open the newly generated code, find and open the main.c file, and add the code here.
insert image description here
The code is as follows:

uint16_t duty_num = 10;

It means to define a variable to store the duty cycle.
Then add the following code in the position shown in the figureinsert image description here

HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_2);

It means to start channel 2 of TIM2 and output PWM.
Next, find the location shown in the figure
insert image description here
and add the code:

HAL_Delay(50);
		duty_num = duty_num + 10;
		if(duty_num > 500)
		{
    
    
			duty_num = 0;
		}
		__HAL_TIM_SetCompare(&htim2,TIM_CHANNEL_2,duty_num);

After the modification is completed, save and debug to generate a hex file, and then burn the file through the serial port assistant, and the experiment is completed.

3. Reference

http://www.mcublog.cn/stm32/2021_01/stm32cubemx-pwm-huxideng/

Guess you like

Origin blog.csdn.net/qq_54761976/article/details/127597919
Recommended