firmata / firmata.js

JavaScript implementation of the Firmata protocol
711 stars 147 forks source link

board.reportDigitalPin(digitalPinNumber, 0) has no effect #185

Open pichlermi opened 6 years ago

pichlermi commented 6 years ago

From the Documentation:

To stop reporting digital values for a pin, call board.reportDigitalPin(digitalPinNumber, 0). To restart, call digitalRead(pin,callback) or use board.reportDigitalPin(digitalPinNumber, 1) if you don't want to call digitalRead again. <<

Reproduce the Error:

board.pinMode( 2, board.MODES.INPUT );
board.digitalRead(2, function(value) {
  console.log("The value of digital pin 2 changed to: " + value);
});
board.reportDigitalPin(2, 0);

The log message is still written to the console, when Pin 2 is toggled.

Hack:

board.pinMode( 2, board.MODES.INPUT );
cb = function(value) {
  console.log("The value of digital pin 2 changed to: " + value);
}
board.digitalRead(2, cb);
board.removeListener( "digital-read-2", cb )

Now, no message is written.

lilliesAndRoses commented 6 years ago

Are you trying to read the value of a pin infrequently using analogRead or digitalRead, and do not want the callbacks there after?

I was trying to do that and made my code look as follows

function readPin(pinId) {
    board.pinMode( pinId, board.MODES.INPUT );
    board.digitalRead(pinId, function(value) {
       console.log("The value of digital pin changed to: " + value);
       board.reportDigitalPin(pinId, 0);
 });
}

With this change, I got warning of maxEventListeners after calling the function readPin 10 times.

I think there is a need of analogReadOnce and digitalReadOnce type of functions. The code there can simply call "this.once" instead of "this.addListener" so that the above code would work and user would not need to tamper with the listeners directly.

Board.prototype.analogReadOnce = function(pin, callback) {
  this.reportAnalogPin(pin, 1);
  this.once("analog-read-" + pin, callback);
};
rwaldron commented 6 years ago

The log message is still written to the console, when Pin 2 is toggled.

When you observe this, do you mean that it logs once, or continuously? I can reproduce the behavior in which a single report still occurs, but not continuous reports.

lilliesAndRoses commented 6 years ago

@rwaldron Thanks. The commits that you made also help solve the problem. The only change I made to my code is moved the reportDigitalPin(pinId, 0) as the first thing to do in the callback.

function readPin(pinId) {
    board.pinMode( pinId, board.MODES.INPUT );
    board.digitalRead(pinId, function(value) {
       board.reportDigitalPin(pinId, 0);
       console.log("The value of digital pin changed to: " + value);
 });
}