Stacking serial1.on("data", ..)

Posted on
  • Hi All,

    It seems if you call

    Serial1.on("data",function(data) {console.log(data);});
    

    multiple times, the function is called multiple times. I guess that makes sense but I cannot unbind this function. Shouldn't there be a Serial1. off?

    Regards,

    Alex

  • Try Serial1.removeAllListeners() - that should do the trick.

  • Thanks! I'll try that. On a sidenote, why are there so many linebreaks in the data that is printed?

  • It's because each time console.log is called, it adds a line break... and the data handler is called as soon as possible after data comes in so it tends to be called with only a few characters at a time (unless Espruino is very busy).

    You could use USB.write to write data without line breaks, but it would interfere with the console. If you're expecting line breaks then best way is often to just buffer the data until you get one:

    var buffer = "";
    Serial1.on("data",function(data) {
      buffer += data;
      var i = buffer.indexOf("\n");
      while (i>=0) {
        console.log(buffer.substr(0,i));
        buffer = buffer.substr(i+1);
        i = buffer.indexOf("\n");
      }
    });
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Stacking serial1.on("data", ..)

Posted by Avatar for Alex @Alex

Actions