Domanda

I'm new to node.js, I'm trying to determine the elapsed time between an on and an off event of a switch (using BeagleBone Black), the script works, somewhat with .getTime() however from what I read it's not particularly accurate. So I did some research and attempted to use console.time, however from what I read there is no way to export the time value into a variable in this particular application.

I'm trying to write a script that times valve open and close events for an engine, so accuracy is paramount. The only input is a reed switch that is triggered by a passing magnet attached to a rotating flywheel.

More concisely, is there a way to time on/off events accurately in node.js?

var b = require('bonescript');

b.pinMode('P8_19', b.INPUT);
b.pinMode('P8_17', b.OUTPUT);
b.pinMode('USR3', b.OUTPUT);

b.attachInterrupt('P8_19', true, b.CHANGE, interruptCallback);

var cycle = 0;
//var t = 0;
var start, end;


function interruptCallback() {
     if (b.digitalRead('P8_19') == 1)
     {
    console.log('Magnetic field present!');
    cycle=cycle+1;
    console.log ('cycle: ' + cycle);
     }

    else
    {
    //console.time('t');
    start = (new Date()).getTime();
    }
    //console.timeEnd('t');
    //console.log(t);
    end = (new Date()).getTime();
    console.log('elapsed time: ' + (end - start));
}

This is the full code that I'm currently using. Note: I've also displayed how I attempted to use console.time.

Thank you for your help!

È stato utile?

Soluzione

For the most accurate time measure possible, use process.hrtime(). From the documentation:

Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array. It is relative to an arbitrary time in the past. It is not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals.

The function returns a two-element array that contains the count of seconds and count of nanoseconds. Passing one time object into another will return the difference between the two objects.

For your case:

function interruptCallback() {
  if (b.digitalRead('P8_19') == 1) {
    cycle = cycle + 1;
  } else {
    start = process.hrtime();
  }
  end = process.hrtime(start);
  console.log('elapsed time: ' end[0] + ' seconds and ' + end[1] + 'nanoseonds.');
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top