-
@tage Hi, I implemented your example code and wow, my readings have stabilized quite nicely. I also tweaked the code to get degrees Celsius and degrees Fahrenheit. My original code was returning a temperature of about 80 F, but that was with only 20 samples. Now I am taking 200 samples every 3 seconds and the temp using the new code is at approximately
Temp: 77.86076511596 Fixed Temp: 77.9
which I understand is due to usingtoFixed(1)
The more samples that I take the 'more accurate' my readings become. I wonder how many samples I can take before I notice a lag between readings.@Manxome Thank you for your code recommendations. Accuracy for the temp sensor is:
± 1°CI checked my room thermostat and it says 77 F and my temp sensor says 78.1 so it's 'not off by much'. The sensor is encapsulated in epoxy and a stainless steal tube which is probably the cause of the 1 degrees difference.
Code:
function CompareForSort(a,b) { if (a == b) return 0; if (a < b) return -1; else return 1; } function MedianRead(n, tempType) { var myarr = []; for(i=0; i<n; i++){ var vOut = E.getAnalogVRef() * analogRead(A0); // if you attached VOUT to Ao var vZero = 0.4; var tCoeff = 19.5 / 1000; var tempinc = (vOut - vZero) / tCoeff; var tempinf = tempinc * (9 / 5) + 32; switch(tempType) { case 'c': myarr[i] = tempinc; break; case 'f': myarr[i] = tempinf; break; default: myarr[i] = tempinc; } } //console.log(myarr); myarr.sort(CompareForSort); myarr.splice(n-2,2); myarr.splice(0,2); //console.log(myarr); m=myarr.length; var sum=myarr.reduce(function(a,b) { return a+b; }); var temp = sum/m; var tempFixed = temp.toFixed(1); console.log("Temp: " + temp + " Fixed Temp: " + tempFixed); console.log(tempFixed); } var ph = new Sensor("ph", 0x63); var phDisplay = new s7s("ph", 0x71); var resTempDisplay = new s7s("res", 0x40); setInterval(function (e) { //var t = getResTempValue(100, 'C'); MedianRead(200, 'f'); //resTempDisplay.sendValue(t, "c"); //console.log(t); }, 3000);
There will always be noise in analog readings. Taking a number of readings and calculating the average is an often used method. But it can still take a large number of readings to get a stable display.
A better way is to take a number of readings and throw away the highest and lowest values and average the rest. Perhaps someone has even better methods to share.
Take n readings and save the data in an array.
Sort the readings from lowest to highest.
Throw away the two highest and the two lowest readings.
Calculate the sum of the remaining values in the array and divide by the number of data points to get the average.
Run the code by typing in "MedianRead(n,Pin);" to capture five readings from pin A1,
or type in "MedianRead(10,A0);" to capture ten readings from pin A0. Use a minimum of five samples. The original samples will be printed, then the remaining and sorted samples, and finally the result. ( a return statement should be added).