-
接线图:
2 :实验目的:
利用pwm实现呼吸灯。
关键PWM定时器设置:
代码部分:
int main(void)
{
/* USER CODE BEGIN 1 */
/* 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_TIM2_Init();
/* USER CODE BEGIN 2 */
// start timer2 pwm
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); // start pwm on channel 1 of timer 2
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
// for breath led, change duty cycle of pwm, from 0 to 100% and back to 0
for (int i = 0; i < 500; i++)
{
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, i); // set duty cycle of pwm
HAL_Delay(10);
}
//delay 500ms
HAL_Delay(200);
for (int i = 500; i > 0; i--)
{
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, i); // set duty cycle of pwm
HAL_Delay(10);
}
//delay 200ms
HAL_Delay(200);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
-
ps:pwm说明:
输出比较、CNT、CRR的概念:
pwm概念: