[STM32F103C8T6]PWM呼吸灯

[STM32F103C8T6]PWM呼吸灯_第1张图片

[STM32F103C8T6]PWM呼吸灯_第2张图片

[STM32F103C8T6]PWM呼吸灯_第3张图片

  通过数据手册可知,PB8对应的是TIM4,3通道

[STM32F103C8T6]PWM呼吸灯_第4张图片

pwm周期与频率的公式:

Tout = {(Prescaler+1) * (Counter Period+1)}/Tclk 

假设频率为2kHZ 因为Tclk = 72MHZ,所以Prescaler = 71,Counter Period = 499

[STM32F103C8T6]PWM呼吸灯_第5张图片

PWM有两种模式:

模式1,模式2

[STM32F103C8T6]PWM呼吸灯_第6张图片

模式1:当pwmVal大于CCRx为无效电平,小于CCRx为有效电平

模式2:当pwmVal大于CCRx为有效电平,小于CCRx为无效电平 

HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_3);//启动PWM函数
//修改占空比函数
	__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,pwmVal);//修改pwmVal的值来修改占空比

 实现呼吸灯关键函数

int main(void)
{
  HAL_Init();
	uint16_t pwmVal = 0;
	uint8_t dir     = 1;//dir:1:越来越亮,0:越来越暗

  SystemClock_Config();
  MX_GPIO_Init();
  MX_TIM4_Init();
	HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_3);//启动PWM函数
  while (1)
  {
		HAL_Delay(1);//必须延时一下,否则灯不会亮
	__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,pwmVal);//修改pwmVal的值来修改占空比
		if(dir){
			pwmVal++;
		}else{
			pwmVal--;
		}
		
		if(pwmVal > 500){
			dir = 0;
		}else if(pwmVal == 0){
			dir = 1;
		}
  }
}
  1. __HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,pwmVal);//修改pwmVal的值来修改占空比

  2. HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_3);//启动PWM函数

SG90舵机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_TIM4_Init();
  /* USER CODE BEGIN 2 */
	HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_3);//启动PWM函数
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
			HAL_Delay(1000);//必须延时否则不会动
		__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,5);//改变占空比
			HAL_Delay(1000);
		__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,10);
			HAL_Delay(1000);
		__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,15);
			HAL_Delay(1000);
		__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,20);
			HAL_Delay(1000);
		__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,25);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

你可能感兴趣的:(stm32,嵌入式硬件,单片机)