Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am writing a node.js app for to help automate some of my home brewery. One of the modules I am using is a PID algorithm to control outputs so that they maintain certain setpoints. I am currently doing this via a while loop, but am thinking that this code will be blocking. Any help making this more effecient and asynchronous would be greatly appreciated. Here is my control loop:

device.prototype.pid_on = function(){
    while(this.isOn){
        this.pid.set_target(this.target); // make sure that the setpoint is current
        var output_power = this.pid.update(this.current_value); // gets the new output from the PID
        this.output.set_power(output_power);
    };
};

I have changed it a little for readability, but that is basically it. It will just loop, adjust the output, then feedback the new input value. I want the loop to continue to run until the device is turned off.

Obviously, I need this to be non-blocking so that I can continue to control other devices while the pid is running.

Currently, i just call the equivalent of device.pid_on(); in my code.

One idea I had is to use an empty callback, would that make this non blocking?

device.prototype.pid_on(calback){
    while (this.isOn){...};
    callback();
};

//call later in code
device.pid_on(function(){});

Thanks for any/all help!

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

It is better to avoid the while loop.

device.prototype.pid_on = function() {
  var that = this;
  if ( this.isOn ) {

    ... do stuff

    process.nextTick(function() {
      that.pid_on();
    });
  }
};

Or

device.prototype.pid_on = function() {
  var that = this;
  if ( this.isOn ) {

    ... do stuff

    setTimeout(function() {
      that.pid_on();
    }, 0);
  }
};
share|improve this answer
 
Yeah, I thought about that as well. I just refactored the code so that if the device is on, the pid_on is called whenever a new input value is recieved. This takes out the loop and should help with cpu load as the pid code is only ran when the input is changed. Thanks for the help! –  JoshPeltier Sep 23 '13 at 21:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.