} // End of backward


// PRIVATE: Setup for continuous rotation at given speed.
function move() {
  if (this._usePWM) {
    // PWM clock is 0.1ms
    // PWM range must be stepDelay * 10 and PWM value must be 1/2 of PWM range
    var range = this._stepDelay * 10
    wpi.pwmSetRange(range);
    wpi.pwmWrite(this._stepPin, range/2);
    return;
  }
  //console.log("Step number: %d", this._stepNumber);
  stepMotor.call(this);
  this._moveTimeoutId = setTimeout(move.bind(this), this._stepDelay);
} // End of move
exports.setupDigital = function(stepsPerRevolution, stepPin, directionPin, usePWM) {
  var context = {
    step: step,         // Function
    setSpeed: setSpeed, // Function
    forward: forward,   // Function
    backward: backward, // Function
    stop: stop,         // Function
    halt: halt,         // Function
    
    _stepDelay:          60*1000/stepsPerRevolution, // Set the default step delay to 1 rpm.
    _direction:          FORWARD, // Motor direction.
    _timerId:            null, // Interval object for stepping fixed number of steps.
    _moveTimeoutId:      null, // Timeout object for continuous rotation
    _motorIndex:         motorIndex, // The index of the motor used for debugging purposes.
    _stepPin:            stepPin, // The pin used to step via a pulse
    _directionPin:       directionPin, // The direction to rotate
    _stepsPerRevolution: stepsPerRevolution, // Total number of steps for this motor.
    _isDigital:          true, // Is this a digital controller?
    _usePWM:             usePWM // Use pwm for timing?
  };
  motorIndex++; // Increment the global motorIndex count (used for debugging).

  wpi.pinMode(directionPin, wpi.OUTPUT);
  
  // If we are using PWM, then set the step pin to be PWM and set its
  // initial value to zero.
  if (usePWM) {
    wpi.pwmSetMode(wpi.PWM_MODE_MS);
    wpi.pwmSetClock(1920);
    wpi.pwmSetRange(10); // Some value
    wpi.pinMode(stepPin, wpi.PWM_OUTPUT);
    wpi.pwmWrite(stepPin, 0);
  } else {
    wpi.pinMode(stepPin, wpi.OUTPUT);
  }
  return context;
}