1. Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.
    Dismiss Notice

A routine to limit range of 16bit variable

Discussion in 'Code Repository' started by Lourens, Jun 3, 2012.

  1. Lourens

    Lourens Member

    Joined:
    Apr 30, 2010
    Messages:
    102
    Likes:
    4
    Location:
    Roodepoort, South Africa
    I am sure there are many more interesting pieces of code out there.... This one is for PIC18's to limit 16bit signed variables to a spesific range. Note that if the least significant byte is located at n then the most significant is at n+1.
     
  2. secretagent

    secretagent New Member

    Joined:
    Mar 20, 2012
    Messages:
    69
    Likes:
    0
    Location:
    Mission, CA
    Code (text):
    if(var>567){var=567;}
    This will make sure var is never over 567. If you want it never over 567 and never under 235

    Code (text):
    if(var>567){var=567;}
    if(var<235){var=235;}
    Is this what you were looking for?

    I am not sure what it is exactly in asm but if you know C this may help you :)
     
  3. Lourens

    Lourens Member

    Joined:
    Apr 30, 2010
    Messages:
    102
    Likes:
    4
    Location:
    Roodepoort, South Africa
    Hi secretagent, i was not particularly looking for ways to limit a variable, this was rather aimed at the (older like me?) assembler users that require a fast way to limit a variable to a particular range, which was the case in my pid routine . Thanks for the comment.
     
  4. dave

    Dave New Member

    Joined:
    Jan 12, 1997
    Messages:
    -
    Likes:
    0


     
  5. WTP Pepper

    WTP Pepper Active Member

    Joined:
    Jan 24, 2012
    Messages:
    648
    Likes:
    41
    Location:
    UK

    Old thread I know, but if you can choose your range sensibly like between 512 & 256 then in assembler language it's just a case of clearing (in this case) all bits above bit 9
     
  6. Lourens

    Lourens Member

    Joined:
    Apr 30, 2010
    Messages:
    102
    Likes:
    4
    Location:
    Roodepoort, South Africa
    Hi WTP, you are correct. In many a case i want to make full use of the 16 bits because of accuracy (and when using fixed point). Some values (can be + or - ) in a calculation can however upset things if they are out of a particular range. This routine is then handy to keep things within limits.
    Glad there are still some assembler programmers out there!
     

Share This Page