View previous topic :: View next topic |
Author |
Message |
davidd
Joined: 30 Sep 2010 Posts: 38
|
create int16 from float |
Posted: Fri Dec 21, 2012 7:19 am |
|
|
hello,
Im trying to create a function that creates int16 from float. Is this correct?
Im sorry I meant to post this code
Code: |
void Set_Duty_Cycle(int8 DC, int16 Width)
{
int16 PW_ON, PW_OFF;
float DC_percent;
dc_percent = (float)DC / 100;
pw_ON = dc_percent * Width; //length of ON time
pw_OFF = Width-pw_ON; //length of OFF time
return;
}
} |
Last edited by davidd on Fri Dec 21, 2012 7:42 am; edited 1 time in total |
|
|
Mike Walne
Joined: 19 Feb 2004 Posts: 1785 Location: Boston Spa UK
|
|
Posted: Fri Dec 21, 2012 7:31 am |
|
|
What are the ranges of your integer variables DC and Width?
Why convert to float?
What's wrong with int32?
For instance, when DC = 20, do you really mean 20%?
I suggest you plug some numbers in to see what happens.
Mike |
|
|
davidd
Joined: 30 Sep 2010 Posts: 38
|
|
Posted: Fri Dec 21, 2012 7:44 am |
|
|
yes my goal is to set 16-bit timer values from integer 0 to 100% |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19535
|
|
Posted: Fri Dec 21, 2012 8:32 am |
|
|
Remember if you multiply first, then you could stick with integers all the way....
Lots faster, and smaller.
Best Wishes |
|
|
Mike Walne
Joined: 19 Feb 2004 Posts: 1785 Location: Boston Spa UK
|
|
Posted: Fri Dec 21, 2012 8:32 am |
|
|
OK. you've changed the question.
Again. Why convert to float.
Floats take a long time and can have rounding-off issues.
Depending on your range of values you may get away with int16 rather than int32.
This avoids floats:-
Code: | pw_ON = (DC * Width) /100; |
You'll need to check there's no overflow problem with the intermediate results. You may need to cast to get it to work properly.
Mike |
|
|
asmboy
Joined: 20 Nov 2007 Posts: 2128 Location: albany ny
|
|
Posted: Fri Dec 21, 2012 9:57 am |
|
|
For completeness and reliability you might check the CASE sensitivity of
PW_ON, PW_OFF; in your code.
It seems never the same capitalization twice.
Not to mention that you make no external use of those local VARS.
And lastly as written, the constellation of resultant floats is still only 1 of 255 values ......
From dc_percent = (float)DC / 100;
Ttelmahs advice was awfully good - i can see it would be simple and much faster to stay with unsigned INT16 vars as your working VAR type and you would benefit from more resolution in DC - -
SO--
where does "DC" come from ? 8 bit A/D ? 10Bit A/d ? 12bit A/D ? more bits ?? it surely is not one part in 100 if its an ADC value is it ?? |
|
|
|