vshymanskyy / blynk-library-js

Blynk library for JS. Works with Browsers, Node.js, Espruino.
https://blynk.io/
MIT License
215 stars 67 forks source link

digitalWrite GPIO pins with code #43

Closed dataplayer12 closed 6 years ago

dataplayer12 commented 6 years ago

Hi, I know the library auto-detects GPIO read/write without having to write code, but I would like to set a GPIO pin on a raspberry pi high/low using code. Is there a way to do it? @vshymanskyy

gablau commented 6 years ago

Hello, you have to create your own board, for example see in the blynk-node.js file the onoff board:

exports.BoardOnOff = function() {
  var self = this;
  var Gpio;
  try {
    Gpio = require('onoff').Gpio;
    console.log("OnOff mode");
  } catch (e) {
    // Workaround for Omega
    Gpio = require('/usr/bin/onoff-node/onoff').Gpio;
    console.log("OnOff-Omega mode");
  }

  this.init = function(blynk) {
    self.blynk = blynk;
  };
  this.process = function(values) {
    switch(values[0]) {
      case 'pm':
        break;
      case 'dw':
        var pin = new Gpio(parseInt(values[1]), 'out');
        pin.write(parseInt(values[2]));
        break;
      case 'dr':
        var pin = new Gpio(values[1], 'in');
        pin.read(function(err, value) {
          if (!err) {
            self.blynk.sendMsg(MsgType.HW, ['dw', values[1], value]);
          }
        });
        break;
      case 'ar':
      case 'aw':
        break;
      default:
        return false;
    }
    return true;
  };
};

Then you have to load it in the library blynk.js find the array with the boards and insert it as first:

// Auto-detect board
  if (options.board) {
    this.board = options.board;
  } else if (isEspruino()) {
    this.board = new BoardEspruinoPico();
  } else if (isBrowser()) {
    this.board = new BoardDummy();
  } else {
    [
        bl_node.BoardYOURBOARD, // <-- Your new custom board
        bl_node.BoardMRAA,
        bl_node.BoardOnOff,
        BoardDummy
    ].some(function(b){
      try {
        self.board = new b();
        return true;
      }
      catch (e) {
        return false;
      }
    });
  }
self.board.init(self);

Of course, then share your implementation with us. Thank you!

dataplayer12 commented 6 years ago

Thanks @gablau for the tips. Since I am new to JS, I have used a simple workaround for the moment.

var ledpin = 8;
var gpio = require('onoff').Gpio;
const led = new gpio(ledpin, 'out');
v2=blynk.VirtualPin(2);

//v2 is connected to a button on the app
v2.on('write',function(param){
led.writeSync(param);
});

I believe this manipulation is easier to understand and perhaps more efficient. Although this works for now, this is my first project in JS so I highly appreciate any comments about doing it this way v/s what you suggested.