Shop OBEX P1 Docs P2 Docs Learn Events
Working with logic functions and negative numbers — Parallax Forums

Working with logic functions and negative numbers

FranciscoTavaresFranciscoTavares Posts: 27
edited 2012-06-01 22:40 in BASIC Stamp
I´m working with Parallax MMA7455 3-Axis Accelerometer Module and a BS2P module calculating positioning.
During acceleration processing I need to know it a value is inside a "window" (this is actually a mechanical noise filter).
The logic is quite simple and uses "AND" logic. If an acceleration value is less or iqual than an upper value "AND" greater or equal than a lower value then the acceleration is "inside the window".
This logic should work for positive and for negative values.
However it works only for positive values. For negative values I had to change "AND" for "OR", which is not logically correct but produces the desired values.
Has anyone faced this issue?
I attached a software that demonstrates this behaviour.
If all number as negative ones, "AND" works fine. The problem appears when there are negative and positves numbers.

Comments

  • Tracy AllenTracy Allen Posts: 6,664
    edited 2012-06-01 14:40
    One simple way to deal with that is to add an offset so that all numbers come out positive.
    [SIZE=1][FONT=courier new]offset CON 10000
    
    IF sample+offset <= highlimit+offset AND sample+offset >= lowlimit+ offset THEN
      ' ...[/FONT][/SIZE]
    
  • FranciscoTavaresFranciscoTavares Posts: 27
    edited 2012-06-01 18:29
    Ok this works for now.
    I noticed that PBASIC has difficult to work with negative numbers.
    Even a simple test IF -3 < 0 does not work
    Again this test works if both number are negative or positive. If on of them is negative, than this test doesn't work
    The best way to figure out if a number is negative is by testing bit15.
    Thanks for your answer.


    ' {$STAMP BS2p}
    ' {$PBASIC 2.5}


    test VAR Word
    test=-3


    IF test < 0 THEN
    DEBUG "test less than 0",CR
    ELSE
    DEBUG "test greater or equal to 0",CR
    ENDIF


    DEBUG CR
    IF test.BIT15 THEN
    DEBUG "test less than 0"
    ELSE
    DEBUG "test greater or equal to 0"
    ENDIF
    STOP

    One simple way to deal with that is to add an offset so that all numbers come out positive.
    [SIZE=1][FONT=courier new]offset CON 10000
    
    IF sample+offset <= highlimit+offset AND sample+offset >= lowlimit+ offset THEN
      ' ...[/FONT][/SIZE]
    
  • SapphireSapphire Posts: 496
    edited 2012-06-01 22:40
    You can also use the ABS function to test for negative numbers:
    IF ABS test = test THEN
      DEBUG "Positive"
    ELSE
      DEBUG "Negative"
    ENDIF
    
Sign In or Register to comment.