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!

 

Aug 142016
 

When you have a microcontroller which can connect to the network and it has a RGB LED, the logical step is to make this LED controllable via a web browser.

The list of issues faced is numerous:

  • NodeMCU does not handle websockets natively
  • Thus a bridge between normal TCP sockets used by NodeMCU and WebSockets used by the web browser is needed: ws-tcp-bridge does that
  • ws-tcp-bridge defaults to binary blobs which the browser cannot handle. Switching the websocket’s binaryType to arraybuffer fixes this
  • Sending data too fast to a just created websocket which has its binaryType not yet changed to arraybuffer breaks ws-tcp-bridge with a fatal error:
    TypeError: “list” argument must be an Array of Buffers
  • NodeMCU uses Lua, the browser JavaScript. The langages are quite similar! See below for an example.

Code is at https://github.com/haraldkubota/rgbled-websocket

Interesting is the comparison of Lua and JavaScript variable names are the same):

JavaScript Lua
for (c of s.split('')) {

  if (c>='0' && c<='9') {
    if (state==1)
      value=10*value+c.charCodeAt()-48;

    } else {
      if (state==1) {
        setOneColor(color, value);
        state=0;
      }
      if (c=='R' || c=='G' || c=='B') {
        color=c;
        value=0;
        state=1;
      }
   }
}
for n=1,s:len(),1 do
   c=s:sub(n, n)
   if c>='0' and c<='9' then
     if state==1 then
       value=value*10+c:byte(1)-48
     end
   else
     if state==1 then
       setOneColor(color, value)
       state=0
     end
     if c=='R' or c=='G' or c=='B' then
       color=c
       value=0
       state=1
     end
   end
 end