Code:
@ __CONFIG _FCMEN_OFF & _HS_OSC & _WDT_OFF & _MCLRE_OFF & _CP_OFF & _IESO_OFF & _BOR_OFF & _PWRTE_OFF
DEFINE OSC 20 ' set Oscillator at 20Mhz.
DEFINE NO_CLRWDT 1 ' PBP doesn't clear WDT automatically
DEFINE HSER_CLROERR 1
DEFINE HSER_TXSTA 24h ' Enable transmit
DEFINE HSER_SPBRG 129 ' set USART to 9600 baud @20Mhz
ANSEL = 0
ANSELH = 0
CounterA var Byte 'A counter for sorting out the erroneous data
DataA var word 'A Variable used in sorting the numbers in the array
RawData var word [6] 'This is the RawData gojng into the array
Averaged var word 'This is used to get the average.
top:
RawData[0] = 300
RawData[1] = 100
RawData[2] = 200
RawData[3] = 600
RawData[4] = 400
RawData[5] = 500
pause 250
hserout [27,91,72] 'home cursor
hserout [27,91,50,74] 'clear screen
next1:
hserout [13,10]
hserout [13,10]
pause 300
hserout ["before....", 13, 10]
hserout [13,10]
hserout [dec rawdata[0],13,10]
hserout [dec rawdata[1],13,10]
hserout [dec rawdata[2],13,10]
hserout [dec rawdata[3],13,10]
hserout [dec rawdata[4],13,10]
hserout [dec rawdata[5],13,10]
hserout [13,10]
hserout [13,10]
pause 2000
CounterA =0
gosub SortArray
gosub Average_data
hserout ["after....", 13, 10]
hserout [13,10]
hserout [dec rawdata[0],13,10]
hserout [dec rawdata[1],13,10]
hserout [dec rawdata[2],13,10]
hserout [dec rawdata[3],13,10]
hserout [dec rawdata[4],13,10]
hserout [dec rawdata[5],13,10]
hserout [13,10]
hserout ["therefore, middle two samples are ", dec rawData[2]," + ", dec rawData[3], 13,10]
pause 500
hserout [13,10]
hserout ["averaged middle two samples = ", dec averaged,13,10]
pause 500
pause 3000
goto top
Average_data:
Averaged = (rawData[2]+rawData[3])/2 ' average the middle two of 6 samples
return
SortArray:
SortLoop:
If RawData(CounterA+1) < RawData(CounterA) then
DataA=RawData(CounterA)
RawData(CounterA)=RawData(CounterA+1)
RawData(CounterA+1+0)=DataA
If CounterA > 0 then CounterA=CounterA-2
endif
CounterA=CounterA+1
If CounterA < 5 then goto SortLoop
Return
end
And it works (basically, the code throws away all but the middle two samples of six & averages those two - ideal if your input data is all over the place.,...eg comparator counts etc!)...
Bookmarks