What is the syntax in Spin for calculating the average value in a variable array? (If you can only add one element at a time a block of code could get really large).
Is this a trick question or am I missing something?
pub average(p_array, elements) | acc
acc := 0 ' clear accumulator
repeat elements ' total all
acc += long[p_array] ' get one
p_array += 4 ' point to next element
return acc / elements ' return average
If memory serves me, Phil (PhiPi) had some code to do a running average posted a while back -- you might want to do a search for that.
@JonnyMac, it's not a trick question. Thanks for the compliment and the code. I was just studying the "PUB Average" method of an 'ADC' object because what I was thinking would have filled two pages.
@Mike Green, Thanks.
Mike and JonnyMac, thanks again. I haven't tested this but the logic makes sense to me. I'm working on a 'bi-parented, child controlled autonomous navigation robot'. This piece of code has to find the widest path with a servo/ping combination that scans 180° in 20° increments.
VAR
long AveDistance[6], PingDistance[9], Wide_Path, Rotate_Amount
PUB Find_Corridor | i, j
i:= 0
repeat j from 1 to 6
repeat 4
AveDistance[j]+= PingDistance[i]
i++
AveDistance[j]/= 4
i-= 2
repeat j from 1 to 6
if AveDistance[j] > Wide_Path
Wide_Path := AveDistance[j]
Rotate_Amount := j
Comments
If memory serves me, Phil (PhiPi) had some code to do a running average posted a while back -- you might want to do a search for that.
@Mike Green, Thanks.