实现LED呼吸灯效果
1.查看数据手册,使用TIM1_CHI1
TIM1有点墨迹,使用下面两个短接PA8
预分频84-1,最后低电平有效
启动定时器
while循环添加两种代码,下面一种更简洁。
uint16_t pwmVal=0; //PWM占空比
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_1);
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
while (pwmVal< 500)
{
pwmVal++;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwmVal); //修改比较值,修改占空比
// TIM3->CCR1 = pwmVal; 与上方相同
HAL_Delay(1);
}
while (pwmVal)
{
pwmVal--;
__HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, pwmVal); //修改比较值,修改占空比
// TIM3->CCR1 = pwmVal; 与上方相同
HAL_Delay(1);
}
HAL_Delay(200);
/* USER CODE END 3 */
}
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_1);
while (1)
{
for(int i = 0;i<100;i++){
__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_1,i);
HAL_Delay(1);
}
for(int i = 0;i<100;i++){
__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_1,100-i);
HAL_Delay(1);
}
HAL_Delay(100);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
【STM32】HAL库 STM32CubeMX教程七---PWM输出(呼吸灯)_stm32 hal pwm-CSDN博客
STM32F405RGT6只有这么个I2C3,所以使用I2C3不能使用PA8的LED功能。使用PD2
驱动电机:
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_1);
motor.c与motor.h
#include "tim.h"
#include "motor.h"
void SetSpeed(int8_t speed){
if (speed>=0){
HAL_GPIO_WritePin(GPIOA, PA4_Motor_Pin, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOA, PA4_Motor_Pin, GPIO_PIN_RESET);
__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_1,speed);
}
else{
HAL_GPIO_WritePin(GPIOA, PA4_Motor_Pin, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOA, PA4_Motor_Pin, GPIO_PIN_SET);
__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_1,-speed);
}
}
#ifndef __motor_H
#define __motor_H
void SetSpeed(int8_t speed);
#endif