PDA

View Full Version : negative number calculation



Philip Verspreeuwen
01-30-2007, 02:30 AM
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

Martin Hebel
01-30-2007, 02:54 AM
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 (http://www.selmaware.com/)
Southern Illinois University Carbondale, Electronic Systems Technologies (http://www.siu.edu/~isat/est)

stamptrol
01-30-2007, 02:55 AM
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 Allen
01-30-2007, 02:57 AM
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 (http://www.emesystems.com)

Philip Verspreeuwen
01-30-2007, 03:16 AM
Thanks. I think I will need Martins trick.