4——我使用的是stmf103精英版
pwm——定时器3产生pwm,至于pwm的初始化没啥可说的,就是直接套用原子的pwm初始化;
TIM3_PWM_Init(199,7199); //频率是50Hz 1/50=0.02 周期计算公式为:周期=(arr+1)*(psc+1)/CLK
需求1:利用定时器控制舵机从0--180(尽可能的到达舵机的极限),刚开始想利让一度一度的转,舵机没啥反应;
解决:利用定时器4定时,至于为什么定时4(后面说);
TIM4_Int_Init(79,71); ////80*72/72=80us=0.08ms //定时时间计算 time=clk/((arr+1)(psc+1))
定时器的初始化也是改了原子定时器3的实验
#include "time.h"
#include "stdio.h"
int i=0,flag=0;
double maikuan ,date;
void TIM4_Int_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //时钟使能
//定时器TIM3初始化
TIM_TimeBaseStructure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
TIM_TimeBaseStructure.TIM_Prescaler =psc; //设置用来作为TIMx时钟频率除数的预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); //根据指定的参数初始化TIMx的时间基数单位
TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE ); //使能指定的TIM3中断,允许更新中断
//中断优先级NVIC设置
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn; //TIM3中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3; //先占优先级0级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //从优先级3级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
NVIC_Init(&NVIC_InitStructure); //初始化NVIC寄存器
TIM_Cmd(TIM4, ENABLE); //使能TIMx
}
void TIM4_IRQHandler(void) //TIM4中断
{
if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET) //检查TIM4更新中断发生与否
{
i++;
if(flag==0)
{
maikuan=i*1.85/9.0; // (1.85*i*0.1/180)*200
date=195.0-maikuan;
TIM_SetCompare2(TIM3, date);
//printf("%lf\n\n",date);
}
if(flag==1)
{
maikuan=i*1.85/9.0;
date=175.0+maikuan;
TIM_SetCompare2(TIM3, date);
//printf("%lf\n\n",date);
}
if(i>250)//理论值计算完的结果是100 但是无法到达最值点
//150
//175
//200
//205
{
i=0;
flag=1;
}
TIM_ClearITPendingBit(TIM4, TIM_IT_Update ); //清除TIMx更新中断标志
}
}
|