Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejs
titleSample using "onoff" node js library
collapsetrue
var Gpio = require('onoff').Gpio;
var sleep = require('sleep');

var TRUNK_SENSOR = new Gpio(27, 'in','both');
var DOOR_SENSOR =  new Gpio(6, 'in','both');

var DOOR1 = new Gpio(8,'out');
var DOOR2 = new Gpio(7,'out');
var TRUNK1 = new Gpio(9,'out');
var TRUNK2 = new Gpio(11,'out');

DOOR_SENSOR.watch(function(err,value){
  if(err){
    console.error('There was an error', err); //output error message to console
    return;
  }

  if(value==0){
    DOOR1.writeSync(1);
    DOOR2.writeSync(0);
    sleep.sleep(10); // sleep for ten seconds
    DOOR1.writeSync(0);
    DOOR2.writeSync(0);
  }else{
    DOOR1.writeSync(0);
    DOOR2.writeSync(1);
    sleep.sleep(10); // sleep for ten seconds
    DOOR1.writeSync(0);
    DOOR2.writeSync(0);
  }
});

TRUNK_SENSOR.watch(function(err,value){
  if(err){
    console.error('There was an error', err); //output error message to console
    return;
  }
  if(value==0){
    TRUNK1.writeSync(1);
    TRUNK2.writeSync(0);
    sleep.sleep(10); // sleep for ten seconds
    TRUNK1.writeSync(0);
    TRUNK2.writeSync(0);
  }else{
    TRUNK1.writeSync(0);
    TRUNK2.writeSync(1);
    sleep.sleep(10); // sleep for ten seconds
    TRUNK1.writeSync(0);
    TRUNK2.writeSync(0);
  }
});

function unexportOnClose() { //function to run when exiting program
  TRUNK1.writeSync(0); // Turn off
  TRUNK2.writeSync(0); // Turn off
  DOOR1.writeSync(0); // Turn off
  DOOR2.writeSync(0); // Turn off
  TRUNK1.unexport(); // Unexport GPIO to free resources
  TRUNK2.unexport(); // Unexport GPIO to free resources
  DOOR1.unexport(); // Unexport GPIO to free resources
  DOOR2.unexport(); // Unexport GPIO to free resources
  TRUNK_SENSOR.unexport();
  DOOR_SENSOR.unexport();
};

process.on('SIGINT', unexportOnClose); //function to run when user closes using ctrl+c


Run the Code

> npm sample.js

References

...