View previous topic :: View next topic |
Author |
Message |
mrx23
Joined: 24 Jul 2008 Posts: 2
|
RC signal scaling problem |
Posted: Wed Jul 30, 2008 8:29 am |
|
|
Hi,
I have a problem with the following code:
When I move the transmitter stick from center to max (pulse_time will be 1500-2000), the PWM output will look like: 0..255..0..255..0 instead of a Full-scale: 0..255.
I think this is an overflowing somewhere, but I couldn't find the source of this.
Please help me
Code: |
unsigned int16 neutral_pulse = 1500;
unsigned int16 min_pulse = 1000;
unsigned int16 max_pulse = 2000;
unsigned int16 pulse_time = 1500; //init value, will be between 1000-2000
unsigned int32 new_pwm32 = 0; //because worst case: (2000 - 1500)*255 > 65535 (16bit)
unsigned int8 new_pwm8 = 0;
update(pulse_time); //get new pulse
//This is just for Forward motion, when pulse_time > neutral_pulse
new_pwm32 = (pulse_time - neutral_pulse) * 255 / (max_pulse - neutral_pulse);
new_pwm8 = (unsigned int8) new_pwm32; //new_pwm32 will only contain 0..255
set_pwm(new_pwm8);
|
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Jul 30, 2008 12:36 pm |
|
|
This basic issue was discussed in a recent thread:
http://www.ccsinfo.com/forum/viewtopic.php?t=35545
What you learn from that thread is that CCS doesn't do automatic type
promotion. It keeps the original types when it does the math. This is
why you're getting the truncation.
Your comments show that you know there is a possibility of overflow.
The solution is to cast either the first expression or the 255 as an int32.
Then you'll get the correct result.
Code: | (pulse_time - neutral_pulse) * 255 |
Also, your comments day that 'pulse_time' can be as low as 1000.
With 'neutral_pulse' set to 1500, this will give a negative result,
but your variables are all declared as unsigned. This is an additional
thing that needs attention. |
|
|
mrx23
Joined: 24 Jul 2008 Posts: 2
|
|
Posted: Wed Jul 30, 2008 12:45 pm |
|
|
Now it's working.
Code: | new_pwm32 = (pulse_time - neutral_pulse);
new_pwm32 = new_pwm32 * 255 / (max_pulse - neutral_pulse); |
Quote: | //This is just for Forward motion, when pulse_time > neutral_pulse | As I commented there is a reverse function also.
Thank you! |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Jul 30, 2008 12:49 pm |
|
|
Just adding a cast will also fix it:
Quote: | (pulse_time - neutral_pulse) * (int32)255 |
|
|
|
|