分享低功耗msp430PID控制电机转速的C程序
#include <msp430x14x.h>
#include <math.h>
#include <stdlib.h>
unsigned int cap_tar,cap_first,cap_last,time,pluse,flag=0,temp1;
float speed,Uk,vis=0,temp2=0;
/*******************************************
函数名称:定时器中断服务函数
功 能:用于捕捉传感器的脉冲信号
参 数:无
返回值 :无
********************************************/
#pragma vector=TIMERA0_VECTOR
__interrupt void timerA0(void)
{
if(cap_tar==0)
{
cap_first=TACCR0;
cap_tar++;
}
else
{
cap_last=TACCR0;
cap_tar++;
flag=1;
}
}
#pragma vector=TIMERA1_VECTOR
__interrupt void timerA1(void)
{
switch(TAIV)
{
case 2:break;
case 4:break;
case 10:
{
if(cap_last>cap_first)
{
if(cap_tar==0)
pluse=0;
else
{
pluse=cap_tar-1;
time=cap_last-cap_first;
cap_tar=0;
}
}
}
break;
}
}
/*******************************************
函数名称:Count_speed
功 能:计算实际转速
参 数:无
返回值 :实际转速
********************************************/
float Count_speed(int pluse,int time)
{
float ActualSpeed;
ActualSpeed = 2682062.0*pluse/time; //基础脉冲一圈一个信号
return ActualSpeed;
}
/*******************************************
函数名称:增量式PID控制程序
功 能:用PID反馈控制输出一个反馈控制量
参 数:无
返回值 :UK控制量
********************************************/
struct _pid{
float SetSpeed;//定义设定值
float ActualSpeed;//定义实际值
float err0,err1,err2; //定义偏差值
float Kp,Ki,Kd;//定义比例、积分、微分系数
float Uk0,Uk1;//控制执行器的变量
}pid;
void PID_init(){
pid.SetSpeed=0.0;
pid.ActualSpeed=0.0;
pid.err0=0.0;
pid.err1=0.0;
pid.err2=0.0;
pid.Uk0=0.0;
pid.Uk1=0.0;
pid.Kp=8;
pid.Ki=3;
pid.Kd=1;
}
float PID_realize(float ActuaSpeed)
{
pid.SetSpeed=3000;
pid.ActualSpeed=ActuaSpeed;
pid.err0 = pid.SetSpeed - pid.ActualSpeed;
pid.Uk0 = pid.Uk1+pid.Kp*(pid.err0-pid.err1)+pid.Ki*pid.err0+pid.Kd*(pid.err0-pid.err1-pid.err1+pid.err2);
if(pid.Uk0>1023)
{
pid.Uk0=1023;
}
if(pid.Uk0<0)
{
pid.Uk0=1;
}
pid.Uk1 = pid.Uk0;
pid.err2 = pid.err1;
pid.err1 = pid.err0;
Uk = pid.Uk0;
return Uk;
}
int main(){
float ActualSpeed=0;
volatile unsigned int i;
P1DIR = 0XFF;P1OUT = 0XFF;
P2DIR = 0XFF;P2OUT = 0XFF;
P3DIR = 0XFF;P3OUT = 0XFF;
P4DIR = 0XFF;P4OUT = 0XFF;
P5DIR = 0XFF;P5OUT = 0XFF;
P6DIR = 0XFF;P6OUT = 0XFF;
WDTCTL = WDTPW + WDTHOLD; //停止看门狗
BCSCTL1 &= ~XT2OFF;
do
{
IFG1 &= ~OFIFG; // Clear OSCFault flag
for (i = 0xFF; i > 0; i--); // Time for flag to set
}
while ((IFG1 & OFIFG));
BCSCTL2 |=SELM_2+ SELS;
TACTL=TASSEL_1+MC_2+TACLR+TAIE;
TACCTL0=CM_1+SCS+CCIS_0+CAP+CCIE;
P1DIR&=~BIT1;
P1SEL|=BIT1;
TBCCTL0 = CCIE; //使能CCR0中断
TBCCR0 = 4;
TBCTL = TBSSEL_1 + ID_3 + MC_1; //定时器A的时钟源选择SMCLK,增计数模式
_EINT();
PID_init();
ActualSpeed=Count_speed(pluse,time);
while(ActualSpeed!=3000.0)
{
float PID_realize(float ActuaSpeed);
BCSCTL1 |= XTS;
BCSCTL2 |= SELM_3; // MCLK=LFXT1
P1DIR |= 0x0C; // P1.2 输出
P1SEL |= 0x0C;
TACTL = TASSEL_1 + MC_1; // ACLK, 增计数模式
CCR0 = 512-1; // PWM 周期
CCTL1 = OUTMOD_7; // CCR1 重置/设置
CCR1 = (int)Uk; // CCR1 PWM占空比
_BIS_SR(LPM0_bits);
ActualSpeed=Count_speed(pluse,time);
}
}
|