Skip to main content
3 of 4
added 34 characters in body
ratchet freak
  • 3.3k
  • 1
  • 13
  • 13

you can use a different method, you keep the current average and then do

average = (weight1*average+weight2*new_value)/(weight1+weight2);

it's not a true rolling average and has different semantics, but it may fit your needs nonetheless

for a more efficient calculation method for your 9 bits per value solution you could keep the 8 highest bits of the values in an array and separate out the least significant bits:

uint8_t[28] highbits;
uint32_t lowbits;

to set a value you need to split it out

void getvalue(uint8_t index, uint16_t value){
    highbits[index] = value>>1;
    uint32_t flag = (value & 1)<<index;
    highbits|=flag;
    highbits&=~flag;
}

resulting in 2 shifts an AND and an OR and a not

to calculate the average you can use various bit tricks to speed it up:

uint16_t getAverage(){
    uint16_t sum=0;
    for(uint8_t i=0;i<28;i++){
        sum+=highbits[i];
    }
    sum<<=1;//multiply by 2 after the loop
    sum+=bitcount(lowbits);
    return sum/28;
}

you can use an efficient parallel bitcount for the bitcount()

ratchet freak
  • 3.3k
  • 1
  • 13
  • 13