You are reading a single comment by @Gordon and its replies. Click here to read the full conversation.
  • Hi,

    Rather than polling, this is where you want to use callback functions...

    You can call a function that will handle your serial data when it is received, for example:

    Serial1.on("data",function(data) {
      buffer += data;
      var i = buffer.indexOf("\r");
      while (i>=0) {
        dataReceived(buffer.substr(0,i)); // <-------  
        buffer = buffer.substr(i+1);
        i = buffer.indexOf("\r");          
        comState = 2;
      }
    });
    
    function dataReceived(str) {
      var a = Number(str);
      if(a==12.3) {LED1.write(1);} else {LED1.write(0);}
      if(a==23.4) {LED2.write(1);} else {LED2.write(0);}
      if(a==34.5) {LED3.write(1);} else {LED3.write(0);}
    }
    
    function getTemp(arg){
      Serial1.print("NTC,"+arg+"\r");
    };
    
    setInterval(getTemp, 1000); // ask for temperature every second
    

    It'll be much more power efficient, since the board is only waking up when it has something to do. Generally you shouldn't ever really need a loop function in Espruino.

    Hope that helps! In the code above, it'll ask for temperature every 1 second regardless of whether there was a response - but often this is a good idea. If the temperature sensor doesn't respond (or doesn't get the data) for whatever reason, you don't want the Espruino board to stay waiting for it!

About

Avatar for Gordon @Gordon started