PWM Speed

This is our first year and we are having some problems with the programming. We need to set a lower maximum value for the PWM02 motor. Something like 200. We are using the default code. How would this be achieved?

You would probably want to scale the precision of whatever control mechanism or joystick you are using to get the full scale of motion, so this should graph that to the new maximum:


long answer; //Must be long to hold precise values
if (p1_x > 127){ //Or whatever joystick
answer = p1_x * 200 / 255;
pwm02 = (unsigned char)answer; //Cast this to the proper type
} else {
pwm02 = p1_x;
}

While the above code would work, you don’t need to use a long variable, which I’m assuming you’re using to prevent overflow. Another approach would be to just cast the result:


#define MAX_VALUE 200 //Replace 200 with whatever you want your max value to be

Put the #define at the top of your file. On compile, the compiler will insert 200 (or whatever you decide you want your value to be) wherever you write MAX_VALUE. This way, if you want to change what the max value is later, you can simply change it at the top of the file instead of fishing through your code. This is especially useful if you use it more than once.

Then, the actual solution:


if(p1_x > 127) //Replace p1_x with whatever joystick and axis you want
     pwm02 = (unsigned char)((long)p1_x * MAX_VALUE / 255);

else
     pwm02 = p1_x;

This code first casts the expression as a long so that overflow doesn’t occur, then casts it back to an unsigned char so it can be assigned to pwm02. No variables are used.