板子:STM32F103C8 仿真软件:Proteus 8 软件平台:cubemx+keil
1 新建STM32CubeMX工程
1.1 配置系统时钟RCC
1.2 配置定时器
这里用的PB3和PA15一对
在TIM2
中,时钟源选择内部时钟Internal Clock
,通道1选择PWM输出PWM Generation CH1 通道2选择PWM输出
PWM Generation CH2
2 代码
2.1 定义变量
uint16_t pulse=0; /*占空比,重装载值设置为999*/ uint8_t flag=1; /*LED标志位,用于判断是渐亮还是渐灭*/
2.2 mian函数
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 */ //启动定时器2通道1的PWM HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_1); //启动定时器2通道2的PWM HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_2); uint16_t pulse=0; /*占空比,重装载值设置为999*/ uint8_t flag=1; /*LED标志位,用于判断是渐亮还是渐灭*/ /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ 这里下面是while 没复制 就复制到这
while中代码编写
while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ if (flag==1) /*执行LED渐亮*/ { if (pulse<1000) { pulse+=50; /*占空比增大*/ __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,pulse); /*修改占空比*/ HAL_Delay(100); } else flag=0; /*切换为渐灭模式*/ } else /*执行LED渐灭*/ { pulse-=50; /*占空比减小*/ __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,pulse); /*修改占空比*/ HAL_Delay(100); if (pulse==0) { flag=1; /*切换为渐亮模式*/ } } }
完事
标签:BEGIN,CODE,HAL,STM32,USER,END,PWM From: https://www.cnblogs.com/hack747/p/18508491