Shop OBEX P1 Docs P2 Docs Learn Events
negative number calculation — Parallax Forums

negative number calculation

edited 2007-01-29 20:16 in BASIC Stamp
Hello,

I have the next problem:

I'm using a gyroscope and accelerometer input. Both are a pulse width modulation signal. To see the actual difference, I substract the read value of the reference value (which is the neutral signal for both sensors). This has as result that when the sensors are turned one way, I become a value between 0 and 575. When turned the other way I get a value between 0 and -575. When using this negative value in a calculation, the BS2px sees this value as a positive value much higher then the actual value... Can anybody tell me which kind af variable I need to use? For the moment I'm using a "word", but apparently this is only able to have a positive value.

thanks,

Philip

Comments

  • Martin HebelMartin Hebel Posts: 1,239
    edited 2007-01-29 19:54
    Word is the right size. If you DEBUG/SEROUT, use SDEC instead of DEC.

    Some math operations, such as / and // do not work on signed values.

    I do this (not tested here, but gives you the idea)

    b = value.bit15 ' get bit 15, 1 = negative
    y = abs( value) / 20
    if b= 1 then y = y * -1 ' re-apply sign

    -Martin

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    StampPlot - GUI and Plotting, and XBee Wireless Adapters
    Southern Illinois University Carbondale, Electronic Systems Technologies
  • stamptrolstamptrol Posts: 1,731
    edited 2007-01-29 19:55
    Could you always add 575 to each value and work with a number from 0 to +1150?

    Cheers,

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tom Sisk

    http://www.siskconsult.com
    ·
  • Tracy AllenTracy Allen Posts: 6,662
    edited 2007-01-29 19:57
    In DEBUG statements, use the SDEC modifier to see the value as signed twos complement:
    DEBUG SDEC value


    Arithmetic works fine on those twos complement values for addition, subtraction and multiplication. If your algorithm needs division, you will need to use some tricks, which basically means saving the sign, doing the division using the absolute value, and then restoring the sign.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tracy Allen
    www.emesystems.com
  • edited 2007-01-29 20:16
    Thanks. I think I will need Martins trick.
Sign In or Register to comment.