Search code examples
node.jsloopsraspberry-pidelay

Node.js: how can I delay (not sleep) from one line to another to pulse stepper motor in a loop


I'm controlling a stepper motor with onoff in a Raspberry Pi 3B+ and want to delay between setting pulse high and then low within a loop.

for (i=0; i < steps; i++) {
  pinPul.writeSync(1);
  delay here 10 milliseconds
  pinPul.writeSync(0);
  delay another 10 milliseconds
}

I don't want to stop the execution of any of the other stuff that's going on in the program during the delay.


Solution

  • Node.js uses a event loop. And you want to use sync functions that waits.

    The default approach in js/node is using setTimeout() but it relies on callbacks and cannot be used on a for loop. To fix this you need to use the modern async/await.

    async function sleep(ms) {
      return new Promise(resolve => {
        setTimeout(resolve, ms);
      });
    }
    
    async function ledLoop() {
      for (i=0; i < steps; i++) {
        pinPul.writeSync(1);
        await sleep(10);
        pinPul.writeSync(0);
        await sleep(10);
      }
    }
    
    ledLoop();
    

    Just a comment. 10ms is too fast for the human eye. Change to 1000ms for better testing.