减法要用 signed 型

  今天调试一个程序,因为Feedback是电流采样值,Setpoint是PWM值,这两个不可能是负值。所以以为Setpoint和Feedback这两个变量都可以设置为u16型(unsigned int),结果悲催了,CPU总是跑飞。导致LED暴亮,差点烧掉。。。

  原因是两个unsigned型数据相减后不能为负值。如: PIdata->Setpoint - PIdata->Feedback

所以,要保证其中有一个是signed 型,系统就默认相减的结果为signed型,程序可以正常运行。

typedef struct {
    u16        Kp;
    u16        Ki;
    u8        OutMax;
    signed long    Setpoint; 
    u16            Feedback;
    signed long            Error;
    signed long            Integral;
    signed long            Output;
    u8                Saturated;
    }tPIParams;

tPIParams    Current;

 

void CalcPI(tPIParams *PIdata)
{    
    PIdata->Error = PIdata->Setpoint - PIdata->Feedback;
    // Deadband -- If the magnitude of the error is less than a limit,
    // then don't calculate the PI routine at all.  This saves
    // processor time and avoids oscillation problems.
    if((PIdata->Error > 2) || (PIdata->Error < -2))
    {
        // Now, calculate the actual PI function here.
        PIdata->Output += (PIdata->Error * PIdata->Kp )/10;

        // Perform boundary checks on the PI controller output.  If the
        // output limits are exceeded, then set output to the limit
        // and set flag.    
        if(PIdata->Output > PIdata->OutMax)
        {
            PIdata->Output = PIdata->OutMax;    
        }else if(PIdata->Output < 0)
        {
            //PIdata->Saturated = 1;
            PIdata->Output = 0;    
        }
    }    
}

 

posted on 2017-02-24 17:24  liushao  阅读(372)  评论(0)    收藏  举报

导航