tyhenry / CheapStepper

Arduino library for the cheap but decent 28BYJ-48 5v stepper motor with ULN2003 board
GNU General Public License v3.0
122 stars 46 forks source link

newMoveToDegree Int overflow in toStep variable #17

Open drp0 opened 4 years ago

drp0 commented 4 years ago

int toStep = deg * totalSteps / 360 does not create correct value Solved using:

void CheapStepper::newMoveToDegree (bool clockwise, int deg){

    // keep to 0-359 range
    if (deg >= 360) deg %= 360;
    else if (deg < 0) {
        deg %= 360; // returns negative if deg not multiple of 360
        if (deg < 0) deg += 360; // shift into 0-359 range
    }
    float f = totalSteps / 360.0; // drp
    int toStep = 0.5 + deg * f;
    newMoveTo (clockwise, toStep);
}

David

mrv96 commented 4 years ago

If i well understand, your code in practise rounds the float result before the int convertion. Right?

drp0 commented 4 years ago

float f = totalSteps/360.0 forces a float result deg *f therefore produces float 0.5 +float does indeed round the float to nearest integer David

mrv96 commented 4 years ago

Well. I will update my fork asap and i will open a pull request.

I have also to see if i have to add this rounding code in other methods. I suppose that newMoveToDegree() isn't the only one that should be updated.