赞
踩
定时器基本不使用DMA方式
定时器中断处理通用函数
HAL_TIM_IRQHandler
时钟树配置
PF9 改为tim14CH1
tim14配置
开启tim14全局中断 更改中断优先级
/* USER CODE BEGIN 2 */
lcd_init();
HAL_TIM_Base_Start_IT(&htim14);
HAL_TIM_PWM_Start_IT(&htim14, TIM_CHANNEL_1);
/* USER CODE END 2 */
/* USER CODE BEGIN 0 */
uint8_t pulseChangeDirection = 1;
uint16_t pulseWidth = 50;
/* USER CODE END 0 */
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) { if (htim->Instance != TIM14) { return; } if (pulseChangeDirection) { pulseWidth++; if (pulseWidth >= 95) { pulseWidth = 95; pulseChangeDirection = 0; } } else { pulseWidth--; if (pulseWidth <= 5) { pulseWidth = 5; pulseChangeDirection = 1; } } __HAL_TIM_SET_COMPARE(&htim14, TIM_CHANNEL_1, pulseWidth); }
时钟树配置
定时器tim14设置
定时器tim9设置
打开tim9中断
/* USER CODE BEGIN Includes */
#include "lcd.h"
#include "keyled.h"
#include <stdio.h>
/* USER CODE END Includes */
/* USER CODE BEGIN 2 */ lcd_init(); lcd_show_str(0, 0, 16, "Demo10_3:PWM Input", RED); lcd_show_str(0, 20, 16, "TIM14 generate PWM on PF9(LED1)", RED); lcd_show_str(0, 40, 16, "TIM9 measure PWM on PE5", RED); lcd_show_str(0, 60, 16, "Please connect PE5 and PF9 by line", RED); lcd_show_str(0, 80, 16, "[1]KeyLeft to decrease pulse width", RED); lcd_show_str(0, 100, 16, "[2]KeyRight to increase pulse width", RED); HAL_TIM_Base_Start(&htim14); HAL_TIM_Base_Start(&htim9); HAL_TIM_IC_Start_IT(&htim9, TIM_CHANNEL_1); HAL_TIM_IC_Start_IT(&htim9, TIM_CHANNEL_2); HAL_TIMEx_PWMN_Start(&htim14, TIM_CHANNEL_1); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { KEYS curKey = ScanPressedKey(KEY_WAIT_ALWAYS); uint32_t CCR = __HAL_TIM_GET_COMPARE(&htim14, TIM_CHANNEL_1); if (curKey == KEY_LEFT) { __HAL_TIM_SET_COMPARE(&htim14, TIM_CHANNEL_1, CCR - 5); } else if (curKey == KEY_RIGHT) { __HAL_TIM_SET_COMPARE(&htim14, TIM_CHANNEL_1, CCR + 5); } HAL_Delay(300); /* USER CODE END WHILE */
/* USER CODE BEGIN 4 */ void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) { uint16_t IC1_Width = __HAL_TIM_GET_COMPARE(&htim9, TIM_CHANNEL_1); uint16_t IC2_Pulse = __HAL_TIM_GET_COMPARE(&htim9, TIM_CHANNEL_2); if ((IC1_Width == 0) || (IC2_Pulse == 0)) { return; } char str[40]; sprintf(str, "PWM width = %d", IC1_Width); lcd_show_str(0, 120, 16, str, RED); sprintf(str, "Pulse width = %d", IC2_Pulse); lcd_show_str(0, 140, 16, str, RED); } /* USER CODE END 4 */
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。