Menu

Math equation issue

Help
ToniG
2022-12-30
2022-12-30
  • ToniG

    ToniG - 2022-12-30

    Starting a new thread...

    The compiler seems to have trouble with the equation below for SpdRngPC when input is variables or from calculated constants.
    No_Var gives correct result = 64

      SpdRngPC = (Motor_Spd*(MaxPC-MinPC)/100)+MinPC ' Scale & offset integer %calc
           No_Var = (80*(78-9)/100)+9
    

    If I break it up then it calculates correct, Temp3 = 64.

     Temp1 = (Motor_Spd*(MaxPC-MinPC))
     Temp3 = Temp1/100+MinPC
    

    Tried both PIC & AVR, on simulator & real hardware.

     
  • Anobium

    Anobium - 2022-12-30

    Please try changing the code to use a [CAST] as follows:

    SpdRngPC = ([WORD]Motor_Spd*(MaxPC-MinPC)/100)+MinPC

    This reason a cast is required is the range of the result of the calculation is 255 to 650.

    When
    Motor_Spd 255
      MaxPC 255
      MinPC 0
    = 650 Result is 650 so therefore a WORD cast is required.

    When
    Motor_Spd 0
      MaxPC 0
      MinPC 255
    = 255

    and, further proof - the calc (Motor_Spd*(MaxPC-MinPC)) would overflow the temp variable unless you cast the temp variable result. The max result of this calc is 65025... a word.

     

    Last edit: Anobium 2022-12-30
  • ToniG

    ToniG - 2022-12-30

    That works. Thanks
    I was misunderstanding that if I had a word variable (SpdRngPC) the calculation would be done as word.
    because this worked Temp1 = (Motor_Spd*(MaxPC-MinPC)) = 5520 I wrongly assumed the full calc was the same.
    I will be limiting the input values 0 - 100 %
    Liv&Lern

     
  • Anobium

    Anobium - 2022-12-30

    No problem.

     
  • Anobium

    Anobium - 2022-12-30

    Actually, the reliable coding would be:

    SpdRngPC = ([WORD]Motor_Spd*[INTEGER](MaxPC-MinPC)/100)+MinPC ' Scale & offset integer %calc
    

    As MaxPC-MinPC could be a negative, in theory. So, the extra cast would increase realibiilty but a check of the variables prior to the calculation would be faster to execute - then, you could remove the [INTEGER].

    :-)

     

Log in to post a comment.