目录
CubeMX配置
调试配置
时钟配置
定时器配置
测已知周期的占空比,我们要读取的PWM周期是20ms,于是我设计预分频系数是72-1,自动重装载系数是40000-1,周期是40ms,存在两个完整的周期,所以一定会存在一个上升沿后跟着下降沿,这个时间差就是高电平时间,再除以整个周期的时间就是占空比。
打开定时器捕获中断
代码
readpwm.h
#ifndef __readpwm_H__
#define __readpwm_H__
extern unsigned int read_pwm[2];
void readpwminit();
#endif
readpwm.c
#include "readpwm.h"
#include "tim.h"
int32_t time_rising[2];
int32_t time_falling[2];
int32_t read_pwm_temp[2];
uint32_t read_pwm[2];//1000-2000
void readpwminit(){
HAL_TIM_IC_Start_IT(&htim1, TIM_CHANNEL_1);
HAL_TIM_IC_Start_IT(&htim1, TIM_CHANNEL_2);
HAL_TIM_IC_Start_IT(&htim1, TIM_CHANNEL_3);
HAL_TIM_IC_Start_IT(&htim1, TIM_CHANNEL_4);
}
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == TIM1)
{
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
{
time_rising[0] = (int32_t) HAL_TIM_ReadCapturedValue(&htim1, TIM_CHANNEL_1);
}
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
{
time_falling[0] = (int32_t) HAL_TIM_ReadCapturedValue(&htim1, TIM_CHANNEL_2);
}
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3)
{
time_rising[1] = (int32_t) HAL_TIM_ReadCapturedValue(&htim1, TIM_CHANNEL_3);
}
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4)
{
time_falling[1] = (int32_t) HAL_TIM_ReadCapturedValue(&htim1, TIM_CHANNEL_4);
}
read_pwm_temp[0] = (time_falling[0] - time_rising[0]);
read_pwm_temp[1] = (time_falling[1] - time_rising[1]) ;
if (read_pwm_temp[0] >= 0) {read_pwm[0] = read_pwm_temp[0];}
if (read_pwm_temp[1] >= 0) {read_pwm[1] = read_pwm_temp[1];}
}
}
标签:STM32F103,PWM,HAL,read,TIM,time,pwm,CHANNEL
From: https://blog.csdn.net/w111155855/article/details/139818940