Jump to content
Sign in to follow this  
petrm

Floating point numbers

Recommended Posts

Hi,

 I need convert number from 10bit A/D (16F819) to voltage, 1023=5.0V,512=2.5V => 1023/204=5.11V; but if I try this:

[AD_Result=245 => 1.20V]

    voltage_t=AD_Result / 204;  // result is 1 - OK
   voltage_o=AD_Result % 204;  // result is 41 ??

 

So why is 245 % 204 = 41 and not 2 ?...... Thx for help. Petr M.

Share this post


Link to post
Share on other sites

Since when is 245 % 204 not 41?  Modulus is essentially the remainder of an integer division.

 

Anyway, the better solution to your problem is:

 

If you make the 10-bit number into a 16-bit number by left-aligning it, you've effectively multiplied it by 64 (6 bit positions).  

 

So, you want (1023*64) = 500 (assuming two decimals of precision).  If you left-align the input bytes and divide by 131 (which is 1023*64/500), you'll come up with nearly 500 as a result.  Stick the decimal in the right place in your BCD/display routines, and you're in business.

 

I think I did that right, but my brain's asleep today.  Been on vacation for a week and a half - not all back home yet.

 

Nathan

Share this post


Link to post
Share on other sites
Guest Dave

Petr,

 

The reason you code is not working is that you the % (modulus) operator produces the remainder that results from the division of the numbers.

 

eg

100 % 50 = 0

101 % 50 = 1

51 % 50 = 1

 

I'm not sure what function you are expecting the % operator to perform.

 

Regards.

Dave

Share this post


Link to post
Share on other sites
Guest J

voltage = (25 * AD_Result) / 51;

gives you 100 * the correct value so display the number and stick a decimal point 2 digits in. Of course 204 isn't exactly correct so error will be introduced at high voltages, probably since you know the max voltage you could probably bodge in compensation.

Share this post


Link to post
Share on other sites

You could multiply by 22, then divide by 45 to get a value that's in the range 0-500.

For example:

245*22/45=119

512*22/45=250

1023*22/45=500

To simulate rounding, add half of the denominator before dividing:

(245*22+23)/45=120

(512*22+23)/45=250

(1023*22+23)/45=500

Share this post


Link to post
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...