{"id":42,"date":"2005-10-17T16:08:57","date_gmt":"2005-10-17T21:08:57","guid":{"rendered":"http:\/\/www.tigoe.com\/pcomp\/code2\/category\/uncategorized\/42"},"modified":"2013-04-21T13:34:22","modified_gmt":"2013-04-21T18:34:22","slug":"averaging-and-finding-the-median","status":"publish","type":"post","link":"https:\/\/www.tigoe.com\/pcomp\/code\/arduinowiring\/42\/","title":{"rendered":"Averaging and Finding the Median"},"content":{"rendered":"<p>Here&#8217;s how to find the average of 9 samples, or the median number of a sorted list of samples. Arduino\/Wiring and PicBasic Pro examples follow.<\/p>\n<p>Thanks to Zach Layton for correcting my bubble sort code and Zach Lieberman for the correction.<\/p>\n<p><!--more--><\/p>\n<p><a name=\"more\"><\/a><\/p>\n<p>Written in Wiring, tested on an Arduino board:<\/p>\n<pre>\/*\r\n  Analog median and average\r\n by Tom Igoe\r\n\r\n This program reads an analog input and gives the average of 9 readings,\r\n and sorts the list of readings and delivers the median number.\r\n\r\n Created 17 October 2005\r\n Updated 7 August 2007\r\n\r\n *\/\r\nint numReadings = 9; \/\/ number of samples to take\r\nint median = 0;      \/\/ median of the sorted samples\r\nint readingNumber;   \/\/ counter for the sample array\r\n\r\n\/\/ variables for subroutines:\r\nbyte i = 0;\r\nbyte j = 0;\r\nbyte position = 0;\r\nint analogValues[9]; \r\n\r\n\/\/function prototypes:\r\nvoid bubbleSort();\r\nint  averageArray();\r\n\r\nvoid setup() {\r\n  Serial.begin(9600);\r\n}\r\n\r\nvoid loop() {\r\n  for (readingNumber = 0; readingNumber &lt; numReadings; readingNumber++) {\r\n    \/\/get the reading:\r\n    analogValues[readingNumber] = analogRead(0);\r\n    \/\/ increment the counter:\r\n    readingNumber++;\r\n  }\r\n  \/\/ sort the array using a bubble sort:\r\n  bubbleSort();\r\n\r\n  \/\/ get the middle element:\r\n  median = analogValues[numReadings \/ 2]; \r\n\r\n  \/\/ print the results:\r\n  \/\/ print the array, nicely ASCII-formatted:\r\n  Serial.print(\"Array: [\");\r\n  for (j = 0; j &lt; numReadings; j++) {\r\n    Serial.print(analogValues[j], DEC);\r\n    Serial.print (\", \");\r\n  }\r\n  Serial.print(\"]\\r\\n\");\r\n  \/\/ average the array:\r\n  Serial.print(\" Average = \");\r\n  Serial.print(averageArray(), DEC);\r\n  Serial.print(\"\\tMedian = \");\r\n  Serial.print(median, DEC);\r\n  Serial.print(\"\\r\\n\");\r\n}\r\n\r\n\/\/ average the values in the array:\r\nint  averageArray() {\r\n  int total = 0;\r\n  int average = 0;\r\n  for (i = 0; i&lt; numReadings; i++) {\r\n    total = total + analogValues[i];\r\n  }\r\n  average = total\/(numReadings + 1);\r\n  return average;\r\n}\r\n\r\nvoid bubbleSort() {\r\n  int out, in, swapper;\r\n  for(out=0 ; out &lt; numReadings; out++) {  \/\/ outer loop\r\n    for(in=out; in&lt;(numReadings-1); in++)  {  \/\/ inner loop\r\n      if( analogValues[in] &gt; analogValues[in+1] ) {   \/\/ out of order?\r\n        \/\/ swap them:\r\n        swapper = analogValues[in];\r\n        analogValues [in] = analogValues[in+1];\r\n        analogValues[in+1] = swapper;\r\n      }\r\n    }\r\n  }\r\n}<\/pre>\n<p>Written in PicBasic Pro, tested on a PIC 18F252:<\/p>\n<pre>'  Analog median and average\r\n' by Tom Igoe\r\n\r\n' This program reads an analog input and gives the average of 9 readings,\r\n' and sorts the list of readings and delivers the median number.\r\n\r\n' Created 17 October 2005\r\n' Updated \r\n\r\n  ' Define ADCIN parameters\r\nDEFINE  ADC_BITS        10     ' Set number of bits in result\r\nDEFINE  ADC_CLOCK       3     \t' Set clock source (3=rc)\r\nDEFINE  ADC_SAMPLEUS    50    \t' Set sampling time in uS\r\n\r\nTRISA = %11111111       ' Set PORTA to all input\r\nADCON1 = %10000010      ' Set PORTA analog and right justify result\r\n\r\nnumReadings con 9 ' number of samples to take\r\nmedian var byte   ' median of the sorted samples\r\nreadingNumber var byte     ' counter for the sample array\r\n' serial variables and constants:\r\ntx var portc.6\r\nrx var portc.7\r\ninv9600 con 16468\r\n\r\n'  variables for subroutines:\r\n i var byte\r\n j var byte\r\n position var byte\r\n analogValues var word[numReadings]\r\n total var word\r\n average var word\r\n out var byte\r\n in var byte\r\n swapper var word\r\n\r\nmain:\r\n  for readingNumber = 0 to (numReadings - 1)\r\n    ' get the reading:\r\n    adcin 0,analogValues[readingNumber]\r\n    '  increment the counter:\r\n    readingNumber = readingNumber + 1\r\n  next\r\n  '  sort the array using a bubble sort:\r\n  gosub bubbleSort\r\n\r\n  '  get the middle element:\r\n  median = analogValues[numReadings \/ 2] \r\n\r\n  '  print the results:\r\n  '  print the array, nicely ASCII-formatted:\r\n  serout2 tx, inv9600,[\"Array: [\"]\r\n  for j = 0 to (numReadings - 1)\r\n    serout2 tx, inv9600, [DEC analogValues[j], \", \"]\r\n  next\r\n  serout2 tx, inv9600,[\"]\", 10, 13]\r\n  '  average the array:\r\n  gosub averageArray\r\n  serout2 tx, inv9600, [\"Average: \", DEC average, 10, 13]\r\n  serout2 tx, inv9600, [\"Median: \", DEC median, 10, 13]\r\nGOTO MAIN\r\n\r\n'  average the values in the array:\r\naverageArray:\r\n   total = 0\r\n   average = 0\r\n  for i = 0 to (numReadings - 1)\r\n    total = total + analogValues[i]\r\n  next\r\n  average = total\/numReadings\r\nRETURN\r\n\r\nbubbleSort:\r\n  for out = 0  to (numReadings - 2)  '  outer loop\r\n    for in = out+1 to (numReadings - 1)    '  inner loop\r\n        if analogValues[out] &gt; analogValues[in] then  'out of order?\r\n            swapper = analogValues[out]\r\n            analogValues [out] = analogValues[in]\r\n            analogValues[in] = swapper\r\n        endif\r\n    next\r\n  next\r\nreturn<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Created 17 October 2005 Updated 7 August 2007 *\/int numReadings = 9; \/\/ number of samples to takeint median = 0; \/\/ median of the sorted samplesint readingNumber; \/\/ counter for the sample array\/\/ variables for subroutines: byte i = 0;byte j = 0;byte position = 0;int analogValues[9]; \/\/function prototypes:void bubbleSort(); int averageArray();void setup() { Serial.begin(9600);}void loop() { for (readingNumber = 0; readingNumber &lt; numReadings; readingNumber++) { \/\/get the reading: analogValues[readingNumber] = analogRead(0); \/\/ increment the counter: readingNumber++; } \/\/ sort the array using a bubble sort: bubbleSort(); \/\/ get the middle element: median = analogValues[numReadings \/ 2]; \/\/ print the results: \/\/ print the array, nicely ASCII-formatted: Serial.print(&#8220;Array: [&#8220;); for (j = 0; j &lt; numReadings; j++) { Serial.print(analogValues[j], DEC); Serial.print (&#8220;, &#8220;); } Serial.print(&#8220;]\\r\\n&#8221;); \/\/ average the array: Serial.print(&#8221; Average = &#8220;); Serial.print(averageArray(), DEC); Serial.print(&#8220;\\tMedian = &#8220;); Serial.print(median, DEC); Serial.print(&#8220;\\r\\n&#8221;);}\/\/ average the values in the array: int averageArray() { int total = 0; int average = 0; for (i = 0; i&lt; numReadings; i++) { total = total + analogValues[i]; } average = total\/(numReadings + 1); return average;}void bubbleSort() { int out, in, swapper; for(out=0 ; out &lt; numReadings; out++) { \/\/ outer loop for(in=out; in&lt;numReadings; in++) { \/\/ inner loop if( analogValues[in] &gt; analogValues[in+1] ) { \/\/ out of order?<\/p>\n<p>&#8230;&#8217; Set sampling time in uSTRISA = %11111111 &#8216; Set PORTA to all inputADCON1 = %10000010 &#8216; Set PORTA analog and right justify resultnumReadings con 9 &#8216; number of samples to takemedian var byte &#8216; median of the sorted samplesreadingNumber var byte &#8216; counter for the sample array&#8217; serial variables and constants:tx var portc.6rx var portc.7inv9600 con 16468&#8242; variables for subroutines: i var byte j var byte position var byte analogValues var word[numReadings] total var word average var word out var byte in var byte swapper var wordmain: for readingNumber = 0 to (numReadings &#8211; 1) &#8216; get the reading: adcin 0,analogValues[readingNumber] &#8216; increment the counter: readingNumber = readingNumber + 1 next &#8216; sort the array using a bubble sort: gosub bubbleSort &#8216; get the middle element: median = analogValues[numReadings \/ 2] &#8216; print the results: &#8216; print the array, nicely ASCII-formatted: serout2 tx, inv9600,[&#8220;Array: [&#8220;] for j = 0 to (numReadings &#8211; 1) serout2 tx, inv9600, [DEC analogValues[j], &#8220;, &#8220;] next serout2 tx, inv9600,[&#8220;]&#8221;, 10, 13] &#8216; average the array: gosub averageArray serout2 tx, inv9600, [&#8220;Average: &#8220;, DEC average, 10, 13] serout2 tx, inv9600, [&#8220;Median: &#8220;, DEC median, 10, 13]GOTO MAIN&#8217; average the values in the array: averageArray: total = 0 average = 0 for i = 0 to (numReadings &#8211; 1) total = total + analogValues[i] next average = total\/numReadingsRETURNbubbleSort: for out = 0 to (numReadings &#8211; 2) &#8216; outer loop for in = out+1 to (numReadings &#8211; 1) &#8216; inner loop if analogValues[out] > analogValues[in] then &#8216;out of order?<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9,10],"tags":[],"class_list":["post-42","post","type-post","status-publish","format-standard","hentry","category-arduinowiring","category-picbasic-pro"],"_links":{"self":[{"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/posts\/42","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/comments?post=42"}],"version-history":[{"count":3,"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/posts\/42\/revisions"}],"predecessor-version":[{"id":1158,"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/posts\/42\/revisions\/1158"}],"wp:attachment":[{"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/media?parent=42"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/categories?post=42"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tigoe.com\/pcomp\/code\/wp-json\/wp\/v2\/tags?post=42"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}