Thread: PWM Speed
View Single Post
  #3   Spotlight this post!  
Unread 18-02-2008, 17:09
slavik262's Avatar
slavik262 slavik262 is offline
We do what we must because we can.
AKA: Matt Kline
FRC #0537 (Charger Robotics)
Team Role: Alumni
 
Join Date: Jan 2007
Rookie Year: 2007
Location: Sussex, WI
Posts: 310
slavik262 is a splendid one to beholdslavik262 is a splendid one to beholdslavik262 is a splendid one to beholdslavik262 is a splendid one to beholdslavik262 is a splendid one to beholdslavik262 is a splendid one to beholdslavik262 is a splendid one to behold
Send a message via AIM to slavik262
Re: PWM Speed

Quote:
Originally Posted by psy_wombats View Post
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:

Code:
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:

Code:
#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:

Code:
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.
__________________