Maker Pro
Maker Pro

DS18B20 AVR Math Trick

Fish4Fun

So long, and Thanks for all the Fish!
Aug 27, 2013
475
Joined
Aug 27, 2013
Messages
475
I am not certain how the C libraries handle converting C to F ... hopefully not by using floating point libraries ... but here is a quick trick to get 1 decimal precision for a display with very little math routine overhead ...

The Math:
Code:
((20.5C * 9)/5) + 32 = 68.9F 
or
(20.5C * 1.8) + 32 = 68.9F
or 
(20.5C * 18) + 320 = 689F << Simply adjust the decimal one to the left ...

I use a lookup table like this for the decimal values:
dbDecimal_CtF:
.db 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17

(The Decimal is represented by the number of 16ths, so 0.5 = 8, position 8 in the table = 9)

(20C * 18) + 320 + 9 = 689F << Simply adjust the decimal one to the left ...

This approach uses simple byte multiplication (3 clocks if the device has a hardware multiplier, otherwise 40 to 80 clocks for an assembler routine), a lookup for the decimal (7 clocks) and then 16-bit addition (2 clocks) ...

For 2 Digit precision simply multiply TempC by 180 and add 3200, change the decimal table to:

.db 0, 11, 23, 34, 45, 56, 68, 79, 90, 101, 113, 124, 135, 146, 158, 169

Of course move the decimal 2 places to the left

Hope it Helps!

Fish
 

Harald Kapp

Moderator
Moderator
Nov 17, 2011
13,632
Joined
Nov 17, 2011
Messages
13,632
Looks basically like fixed point arithmetic to me - with a twist.
I like your trick with the lookup table for the decimals. It avoids the overflow that would occur if one were to do the math fully in fixed point arithmetic:
Code:
205 × 180 + 32000 = 68900 <- adjust the decimal 2 places to the left
-> overflow when using 16 bit integers!
 
Top