Motor Help

Is there a way to reverse the number of pulses that the robot sends out. In other words convert 255 to 0 and everything in between in proportion?


If you are just using radio control, you can invert any channel of the transmitter by following the “Reverse Menu” instructions in the Inventors Guide, Appendix E.

To do this in a program, wherever you set the motor speed to “X”, instead set it to “(255-X)”.


  • Dean

There is another way to do essentially the same thing that Dean said with slightly less processor clocks (like if you’re using a processor-intensive program and want to save time). There is a boolean operand called XOR (exclusive OR) which can compare two bytes and create the result with all of the bits equal to 1 where ONLY one of the original bits was 1. All other bits will be zero. Like so:

0110 XOR 0011 = 0101

The C operand for XOR is the carret (^), so to invert a motor value, you set it equal to the original value XOR’d by 255:

x = x ^ 255;

There is a shorthand version of this:


Again, this is the same result as subtracting x from 255, but a little faster (not usually noticeable unless you’re doing a lot of these), just thought you might find it interesting.

Yep, good point!

The xor operation (x ^= 255) takes a single instruction, whereas the subtraction operation I suggested (x = 255-x) takes three instructions. Another option, one’s complement (x = ~x) takes two instructions.

All three operations yield the same result, but it looks like the xor operation is the winner, since it is pretty hard to beat a single instruction :wink:


  • Dean

Wow thats some in-depth analysis of signal reversal there. Guess I’ll try out xor from now on…

Of course, if you’re only using the drive value in one function (like SetPWM(1, X)), you could save some variable space by running the byte inversion (~) in-line with the function (as in SetPWM(1, ~X)). That takes one instruction, but you’re not saving the value in the variable. If you were to save the value in the variable, the whole process would take two instructions. This is the same as SetPWM(1, 255^X), but in addition to saving processor cycles, it also saves finger cramps, and possibly ROM depending on how the C18 compiler does things.

A lesson I’ve learned while working with VEX - never underestimate the power of underestimating the power of the VEX controller. Always act as if it can’t handle that little extra instruction if you can do it another way. Makes my overly complicated code run like a breeze! That, and the word “unsigned” is your friend.