|
|
View previous topic :: View next topic |
Author |
Message |
lgeorge123
Joined: 05 Dec 2004 Posts: 31
|
float to int16 |
Posted: Sun Nov 28, 2010 9:14 am |
|
|
I have the following code to convert float to int16 array. The code compiles successfully, but after simulation the array value is not correct. Can someone help me???
Code: |
#include <18F452.h>
#include <math.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=40000000)
main()
{
unsigned int16 m,a;
int16 buffer[520];
for (m = 0; m < 520; m++)
{
buffer[m] = (int16)150 *sin(( 2 * 3.14159 * m * 3500) / 100000);
}
} |
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19498
|
|
Posted: Sun Nov 28, 2010 11:32 am |
|
|
Your code, casts '150' to an integer, which it already is.....
As written, for a value of (say) 10, you will evaluate:
sin(( 2 * PI * 10 * 3500)/100000) = 0.809
*150 = 121.3
And put 121 into buffer[10]
You don't need to cast anywhere. A float is automatically converted to an int, if you assign it to an integer variable. However the question is what values you expect to get?.
Also as a comment, reduce the operations. It costs nothing for you to precalculate 2*pi*3500/100000, as 0.2199115, and just have:
m*0.2199115
Remember multiplications solve much faster than divisions, so 'pre-solving' the arithmetic, reduces errors and increases speed.
My guess though would be that you don't actually want the 2*pi. Normally you divide a angle in degrees by 2*pi, to convert it to radians. Multiplying by 2*pi, is used to convert an angle in radians to degrees. C, calculates sin, and the other angular functions for an angle in radians already, so if your calculation expects sin to work in degrees, this would be where the error lies......
I think you are trying to calculate sins for 520 points round 180 degrees. If so, the formula would be:
buffer[m] = sin(m*0.00604152);
Best Wishes |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|