Oct 162016
 
Node-RED: Functions

My light sensor (actually just a LDR connected to the single ADC pin on the ESP8266) tends to be a bit jumpy and the graphs looked anything but smooth. Quick fix: averaging samples. Node-RED has functions for this. And here is one to average 4 samples:

// jshint esversion: 6

const oldDataMax=4;
let lastData;
let count = context.get('count')||0;
let oldData = context.get('oldData')||[];

// Need to shift all numbers one left if array full
// Circular buffer would be nice, but overly complex for such small buffers

if (count==oldDataMax) {
 for (let i=1; i<oldDataMax; ++i) {
 oldData[i-1]=oldData[i];
 }
 lastData=oldDataMax-1;
} else {
 lastData=count++; 
}
oldData[lastData]=parseInt(msg.payload);

// Calculate the average

let avg=0;
for (let i=0; i<=lastData; ++i) {
 avg+=oldData[i];
 }
avg=avg/(lastData+1);

context.set('count', count);
context.set('oldData', oldData);

let avgMsg = { payload: ""+avg };

return [ msg, avgMsg ];

Much less jumpy graphs now!