Median16s(), Median16u()

Median is a number, in the middle of a row of numbers, sorted by value. Can be used as a Median filter to process Input data (Rank order filter). Voltage readings of an ADC are much more stable using Median because variations are much smaller.

Two types are defined for 16-Bit values. With and without taking the sign into account.

Syntax: word = Median16u( valuesAddr as word, valueCount as byte )
Syntax: integer = Median16s( valuesAddr as word, valueCount as byte ) (Signed value)

The parameter expects a memory address (example an Array), and the number of values. The input values are temporarily pushed on the stack. Take this into account when sizing the stack.

Example

const F_CPU=20000000
avr.device = atmega16
avr.clock  = F_CPU
avr.stack = 64
 
uart.baud = 19200
uart.recv.enable
uart.send.enable
 
dim i as byte
dim b(4) as word
dim mv as long
 
print 12;"median example"
print
wait 1
 
'Input data
b(0) = 55
b(1) = 99
b(2) = 44
b(3) = 22
b(4) = 11
 
print
print "Median() = ";str(Median16u( b().Addr, b().Ubound+1 ))
print
 
print "Median manually:"
'Sort input data in ascending order
b().Sort
'Display it
for i=0 to b().Ubound
  print "b(";str(i);") = ";str(b(i))
next
print
i = b().Ubound/2 ' the middle element is the Median
mv = b(i)
'There is no middle element when the number of elements is even. The Low- and High-Median will be averaged.
if even(b().Ubound+1) then
  mv = (mv + b(i+1)) / 2
end if
 
print "Median() = ";str(mv)
print
print "ready"
do
loop