This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

timer problem again

this is my code:

timerVal.u16 = (((servoHundredEighty - servoZero) * (degreeValue/180)) + servoZero);

if all the variable are declare in unsigned char...this method can be used? or how i need to proceed with this if i would like to calculate certain value and put it into timerVal.u16, those variable will be in decimal eg:(-1000) ...
thanx

Parents
  • I suspect you'll have trouble with truncation in the integer division as written. (degreeValue/180) will be either 0 or 1, using a U8.

    To preserve the precision of the result, you need to postpone the division.

    ((servoHundredEighty - servoZero) * degreeValue) / 180 + servoZero;

    Since this value could potentially reach 359 * 180, you'll need to use 16-bit math. that's probably most easily done just with a cast.

    ((U16)(servoHundredEighty - servoZero) * degreeValue) / 180 + servoZero;

Reply
  • I suspect you'll have trouble with truncation in the integer division as written. (degreeValue/180) will be either 0 or 1, using a U8.

    To preserve the precision of the result, you need to postpone the division.

    ((servoHundredEighty - servoZero) * degreeValue) / 180 + servoZero;

    Since this value could potentially reach 359 * 180, you'll need to use 16-bit math. that's probably most easily done just with a cast.

    ((U16)(servoHundredEighty - servoZero) * degreeValue) / 180 + servoZero;

Children
No data