Using function() within a function node

I'm trying to read data from a BH1750 i2c light intensity sensor. There is no node-red node for it, so I'm using a node.js module and trying to access it from within a function node in node-red. However anything that is in a function() code seems not to be executed. I used one function node to initialise the module

var BH1750 = global.get('BH1750');
var ls1 = new BH1750();
flow.set('ls1', ls1)
return msg;

and another one, from an example to read the value:

var ls1 = flow.get('ls1');
ls1.readLight(function(err, value){
if (err) {
msg.payload = err;
throw err;
} else {
msg.payload = value;
}
});

I'm not a programmer and I don't understand the nameless function() construct .... Is there a way around it?

Thanks

Hi @Max95

for future reference, please wrap your code blocks in ``` so they format correctly.

var ls1 = flow.get('ls1');
ls1.readLight(function(err, value){
  if (err) {
    msg.payload = err;
    throw err;
  } else {
    msg.payload = value;
  }
});

You are providing a callback function to the readLight function. Within that callback, you set msg.payload to a value, but then do nothing else.

So as written, that callback won't do anything to send on a message or notify you in any way that it has been called.

You need to use the node.send function to send on the msg from within the callback, as described here - https://nodered.org/docs/writing-functions#sending-messages-asynchronously

I'd also suggest you add some node.warn("hello"); type statements within the callback so you can see what is happening - those warn messages will appear in the debug sidebar.

Hi @knolleary.

Thank you very much for you quick and helpful reply. This has been the best forum experience of my life!

Hi max95, I hope you found the way to reach your goal. Would you mind to provide the solution that worked for you? Any help even little is appreciated. Thank you!

Have a look at this post: