digitalRead/digitalWrite in node.js

Hey guys,

I’m sure I’m missing something pretty basic, but I can’t seem, for the life of me, to use digitalRead and digitalWrite in my node.js program.

I’m on a Raspberry Pi B+, and things are working fine in general (I can pass virtual values around, I’ve hard-wired a button to a GPIO pin and it works etc).

Thing is, I’d like to send a message to my LCD widget (via virtualWrite) once a digital pin goes high. I thought I’d use digitalRead for this, but I’m failing miserably. Here are the pertinent parts of my code:

#!/usr/bin/env node

var Blynk = require('/usr/local/lib/node_modules/blynk-library');

// various init stuff cut from here

//V0 is tied to the LCD (simple mode) with refresh 1sec
v0.on('read', function(param) {
        var check = digitalRead(2);

When run, this fails with the following message:

        var check = digitalRead(2);
ReferenceError: digitalRead is not defined
    at null.<anonymous> (/home/pi/blynk/homeControl.js:43:14)
    at emit (events.js:104:17)
    at Blynk.onReceive (/usr/local/lib/node_modules/blynk-library/blynk.js:466:27)
    at null.<anonymous> (/usr/local/lib/node_modules/blynk-library/blynk.js:532:50)
    at emit (events.js:107:17)
    at Socket.<anonymous> (/usr/local/lib/node_modules/blynk-library/blynk-node.js:50:14)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:538:20)

I’ve tried all the permutations I could think of, like digitalRead(“2”), digitalRead(“D2”), blynk.digitalRead(2) etc…

I’m obviously missing something. What? :slight_smile:

So I got it to work using the onoff library…

var Gpio = require('/usr/local/lib/node_modules/onoff').Gpio,
  heat = new Gpio(2, 'out');


That works and it does what I want it to do (returns a 1 or 0 depending on whether the pin is high or low). Still, is this the right way to go about that? I would think digitalRead/Write to be part of the Blynk library, making use of each pin’s setup (in/out) etc. Thoughts?

1 Like

In general, if you have installed onoff, blynk tries to use it. Just need to select Digital pin in Widget setting.

Hi. Yeah, clearly, I understand that. But I’m talking about working from within the .js script itself. In the docs, you mention that we can use digitalRead and digitalWrite to directly access digital pins.

On the Pi and in the node.js environment, that doesn’t seem to be the case, that’s all I’m saying. Example scenario: Check the status of a digital pin in the timer loop (interval) of the .js script, in order to then virtualWrite to a virtual pin.

Am I right assuming that the digitalRead/digitalWrite use would have to be substituted by the use of the onoff library in my environment?

Thanks for your help!

1 Like