Celsius to Fahrenheit conversion

Hosted by Ron (JR) Hackett, this forum is for all you PICAXE fans out there. Ron has over 35 years experience as an educator, author and programmer. IF you want to talk PICAXE, this is the place.

Moderator: RonHackett

Post Reply
DosMan
Posts: 1
Joined: Mon Oct 15, 2012 1:55 pm
Contact:

Celsius to Fahrenheit conversion

Post by DosMan » Mon Oct 15, 2012 2:43 pm

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:

Code: Select all

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):

Code: Select all

tempF = tempC * 9 / 5 + 32 - 99
which can be simplified to:

Code: Select all

tempF = tempC * 9 / 5 - 67
But to handle the negative Fahrenheit result, a test is needed before we subtract. The whole sequence becomes:

Code: Select all

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:

Code: Select all

tempF = (tempC * 9 + 2) / 5 - 67
I think maybe no parentheses are needed as the PICAXE evaluates left-to-right without normal precedence.

Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests