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

which can be simplified to:

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:

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