Update: Raspberry Pi Temperature Display

With the cooler outdoor temperatures, a bug in my original code for the temperature display has cropped up:

IMG_6295

The DS18B20 returns temperatures with up to three decimal places, with the decimal point omitted, therefore a temperature of 10oC would be shown as 10000 by the sensor. To deal with this and for the display to show the temp to one decimal, I used this code:

        temperature1a = str (tempdata1[2:-3])

temperature1b = str (tempdata1[4:-2])

temperature1 = str ((temperature1a) + ‘.’ + temperature1b))

Here the value is essentially split in two, the number before the decimal and the number after, then the third line of code joins them back together with the decimal point in place. This is achieved by reading the value, then chopping off a number of characters using the [2:-3], this would chop off 2 characters at the start of the string, and 3 from the end.

The bug arises when the ambient temperature falls below 10oC as the sensor will output a 4 integer value as opposed to 5. This in turn will cause the cropping function to read incorrect values as its operation depends on a constant integer length.

As a result, the code will still function, but lower temperature values would be displayed without any decimalisation. Not happy with this I worked on another solution:

First Attempt

Referencing back to the original post on REUK, the code floated the text value into and integer, then a division of the value by 1000 gave the value a decimal point. Expanding on this I thought to keep the value as an integer to add the decimal, then convert to a string to allow the chopping off of the extra decimal places.

On testing however, I was getting inconsistent values, some values displayed with a decimal, others without.

I discovered that the DS18B20 would output a constant 5 or 6 figure value, however when floating to an integer, any trailing zeros after the first decimal place is removed. Therefore the snipping could again corrupt the output.

Result

Until I can find a better solution, it is better to keep it as simple as possible and display the temperature values intact, except the division by 1000 to add the decimal. Luckily the 20×4 LCD display is large enough to accommodate this, with only minor layout tweaks.

IMG_6303

For those interested, here is the amended code to read the sensor and output the value:

        tempfile1 = open(“/sys/bus/w1/devices/28-000007f34893/w1_slave”)

temptext1 = tempfile1.read()

tempfile1.close()

tempdata1 = temptext1.split(“\n”)[1].split(” “)[9]

temperature1 = float(tempdata1[2:])

temperature1 = temperature1 / 1000