I was debugging some code on the Basic Stamp Autopilot this evening, trying to figure out why the navigation function isn't working right. The debug results were mystifying--variables that should have been +-128 were giving crazy values like 64526.
And then it hit me: The Basic Stamp doesn't really know the difference between an unsigned word variable (all 16 bits used) and a signed word (first bit is the +/- bit). You can adjust your debug displays to compensate for that (using SDEC --signed decimal-- format rather than DEC), but in other cases you just need avoid signed integers. For instance, it can't do comparisons ("if x < y") with signed variables when the value is less than 0. That's because it sees something like -30 (which should be less than 0) as 65432 [or whatever], which is more than 0.
I'm sure there's some clever work-around on this, but that explains why all the math is funky in the navigation routine--I ported it over from C, where variables are handled properly, and forgot that Basic Stamps can really only handle operations on positive integers correctly.
I think the solution is probably to add 256 or something to all data so that all the results of our calculations will be in positive territory, and then subtract 256 at the end to make it all right again, but I'll have to work it out on paper before I can be sure.
If I were to do the Basic Stamp autopilot all over again, I'd do it on the Arduino, which has no trouble with proper variables, floating point math and everything else (in fact, I may port it over to Arduino soon). I know Basic Stamp is a great hardware platform for learning embedded programming, but its limited variable space and bare-bones programming language is showing its age.
For those of you who have been frustrated with my Basic Stamp code, my apologies. It's going to take me another week or two to fix this.