1

I am using this API function which I can not change:

xMotor.ccw().step(1, function() { /*callback*/ });

It serves to control a stepper motor which should physically turn the motor a certain amount of steps. Now I need to turn this motor until a button physically gets pressed and I want to measure the travelled length. I went about this like so for now:

var length = 0;

async function initialize(){

    while (motor.checkButton(buttonPin)) {
        xMotor.ccw().step(1, function() { /*CALLBACK*/ });
        length++;
        await sleep(10);
    }
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

But since this API function is non-blocking my length variable gets way to many counts. In reality the while loop is way to fast for physically moving the motor one step. I could just increase the sleep value but this really does not seem like a good solution and the movement of the motor gets very jittery.

All I/O signals are running from a Arduino. And I'm using the Johnny-five framework.

Thanks in advance!

FabZbi
  • 508
  • 5
  • 14
  • 1
    See the linked question's answers. Basically, you do the same thing you did with `setTimeout`: Create a wrapper that provides a promise, then `await` it. – T.J. Crowder Jun 20 '19 at 13:07
  • So would this be right? ```function makeOneStep(){ return new Promise(function(){ xMotor.ccw().step(1, function(){ }) }) }``` – FabZbi Jun 20 '19 at 14:08
  • Please see the linked question's answers. – T.J. Crowder Jun 20 '19 at 14:10
  • @T.J.Crowder I did see the linked answer and I did take my solution from the linked answer. I just want to make sure Im understanding it right. Because my API callback function does not have any `err` or `data`parameters, so I am a little confused. – FabZbi Jun 20 '19 at 14:14
  • I suggest really having a good read, you've left out the `resolve` parameter to the promise callback, which you need because that's how you resolve the promise (again, just like your `setTimeout` above). – T.J. Crowder Jun 20 '19 at 14:30

0 Answers0