It is currently Sat Feb 17, 2018 7:12 pm

All times are UTC - 8 hours




 Page 1 of 1 [ 1 post ] 
Author Message
 Post subject: Celsius to Fahrenheit conversion
PostPosted: Mon Oct 15, 2012 1:43 pm 

Joined: Mon Oct 15, 2012 12:55 pm
Posts: 1
In the October PICAXE Primer there are several pages devoted to Celsius to Fahrenheit conversion, with the complexity coming from the need to handle negative numbers. However, applying some simple math can simplify this conversion a great deal.

The trick is to add a "bias" to the Celsius temp returned by the DS18B20 so it is never negative, do the conversion math, and then subtract the bias back out. Since the lowest value is -55, the value 55 would make a good bias value (being divisible by 5 is also important).

The bias needs to be added modulo 256. The easiest way to do this is make the variable a byte:
tempC = tempC + 55  'byte variable, result is 0 - 180

Since the value with the bias is multiplied by 9/5, the bias to remove at the end is 55 * 9 / 5 = 99. So the formula would become (with bias already in tempC):
tempF = tempC * 9 / 5 + 32 - 99

which can be simplified to:
tempF = tempC * 9 / 5 - 67

But to handle the negative Fahrenheit result, a test is needed before we subtract. The whole sequence becomes:
tempC = tempC + 55  'byte variable
tempF = tempC * 9 / 5 - 67
if tempF < 67
  sign = "-"
  tempF = 67 - tempF
else
  sign = " "
  tempF = tempF - 67

Another improvement that can be made is rounding the division. To round a positive number, you add 1/2. When using integer division, x / y + 1/2 = (x + (y / 2)) / y. Fortunately our divisor is a constant 5, so y / 2 = 5 / 2 = 2 using integer division. So to get a rounded result from the division, that line of code would be changed to:
tempF = (tempC * 9 + 2) / 5 - 67

I think maybe no parentheses are needed as the PICAXE evaluates left-to-right without normal precedence.


Offline
 Profile Send private message  
 
Display posts from previous:  Sort by  
 Page 1 of 1 [ 1 post ] 

All times are UTC - 8 hours


Who is online

Users browsing this forum: No registered users and 1 guest


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 post attachments in this forum

Search for:
Jump to: