#define BARO_TAB_SIZE 40
#define UPDATE_INTERVAL 25000 // 40hz update rate (20hz LPF on acc)
void getEstimatedAltitude(){
uint8_t index;
static int16_t BaroHistTab[BARO_TAB_SIZE];
static int8_t BaroHistIdx;
static int8_t fstrun=1;
static int32_t BaroHigh,BaroLow;
static uint32_t deadLine = 0;
int32_t temp32;
int16_t last;
if (newbaroalt==1) // Update only, if new values are available
{
newbaroalt=0; // Reset Boolean
//**** Alt. Set Point stabilization PID ****
//calculate speed for D calculation
last = BaroHistTab[BaroHistIdx]; // Do the magic
BaroHistTab[BaroHistIdx] = BaroAlt/10;
BaroHigh += BaroHistTab[BaroHistIdx];
index = (BaroHistIdx + (BARO_TAB_SIZE/2))%BARO_TAB_SIZE;
BaroHigh -= BaroHistTab[index];
BaroLow += BaroHistTab[index];
BaroLow -= last;
BaroHistIdx++;
if (BaroHistIdx == BARO_TAB_SIZE)
{
BaroHistIdx = 0;
fstrun = 0;
}
}
if (currentTime<deadLine || fstrun==1) return; // Maintain old timing (40Hz)for PID calculation
deadLine = currentTime + UPDATE_INTERVAL;
EstAlt = BaroHigh*10/(BARO_TAB_SIZE/2);
newestalt=1; // Indicate, new EstAlt RDY
BaroPID = 0; // Calculate new PIDs
//D
temp32 = conf.D8[PIDALT]*(BaroHigh - BaroLow) / 40;
BaroPID-=temp32;
temp32 = AltHold - EstAlt;
if (abs(temp32) < 10 && abs(BaroPID) < 10) BaroPID = 0; //remove small D parametr to reduce noise near zero position
//P
BaroPID += conf.P8[PIDALT]*constrain(temp32,(-2)*conf.P8[PIDALT],2*conf.P8[PIDALT])/100;
BaroPID = constrain(BaroPID,-150,+150); //sum of P and D should be in range 150
//I
errorAltitudeI += temp32*conf.I8[PIDALT]/50;
errorAltitudeI = constrain(errorAltitudeI,-30000,30000);
temp32 = errorAltitudeI / 500; //I in range +/-60
BaroPID+=temp32;
}