DS18B20 problem with Python

Hi guys,
Strange problem Id like some thoughts on / help with.

I have one of these:

For the last few years its been connected to a Pi Zero along with a 7 segment display. It sits on my desk and displays the time and then refreshes to show the temperature before going back to show the time. It also pushes out the temp via MQTT to my MQTT broker where HomeAssistant picks the data up.

Its been working 100% for a few years.

Recently (for the last week or two) its started showing the temperature around 127^C. Its not always 127, it does go up and down.

The project is in a box so I havent knocked any wires etc. Ive also rebooted the device and pulled the power out etc.

I have done a:

sudo apt-get update && sudo apt-get upgrade -y

Still its reading wrong.

Any thoughts?

Thanks
Jon

1 Like

Hey Jon,

That seems very odd, that sensor should be reliable for an extended period of time. Is there any chance there is corrosion at play here? Can you have a look at the sensor and see if there may be any physical signs of an issue?

The most likely culprit is corrosion or the sensor being exposed to excessive heat or moisture, that can commonly damage the sensor.

How long has it been on for? Some components can fail if the use is constant over a long period of time.

Cheers,
Blayden

1 Like

Hi Jon,

A few things come to mind:

  • Have you run a OneWire scan on the Pi? ls /sys/bus/w1/devices/ should do the trick
  • What code are you using to read the sensor?
  • Do you have a spare sensor? I used several of these in a temperature monitoring project and unfortunately about half failed over a matter of months, I assumed it was lightning or something like that.
  • 127 seems like a power of 2, so maybe something internal has gotten “stuck” and a bit is permanently flipped.
1 Like

Hi Blayden

You are kidding right !!! If this is the case the component should not be used, even sold. An MTBF figure would be interesting.

James.

Going on Blayden’s statement it was probably crap devices.
Cheers Bob

Running the above presents:

pi@clock:~ $ ls /sys/bus/w1/devices/
28-0000098e2f18  w1_bus_master1
pi@clock:~ $ 

The device lives in an modified iphone box and sits on my office desk… Shouldnt be getting wet!!

If I had to guess, its been running 24x7 for about 3 years.



I could probably find a spare DBS18B20 / one of the weather proof varients to test, but I thought these should just about last forever!

This is the sensor reading code:

      tempStore = open("/sys/bus/w1/devices/28-0000098e2f18/w1_slave")  #change this number to the Device ID of your sensor
      time.sleep(0.5)
      data = tempStore.read()
      time.sleep(0.5)
      tempStore.close()
      tempData = data.split("\n")[1].split(" ")[9]
      degrees = float(tempData[2:])
      degrees = degrees/1000
      print (data)
      print (degrees)

This is the output from the above:

ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937

This is my complete code:

#!/usr/bin/env python3.7

import time
import datetime
import board
import busio
from Adafruit_LED_Backpack import SevenSegment
import mysql.connector as mariadb       # For conencting to MariaDB Server
time.sleep(30)				# This delay is required to allow the machine to boot up before it tries to connect to the SQL server

# Clock & Temp Display on 1.2" Seven Segment Display
# ===========================================================================
#
# The program uses Adafruit's LED Backpack and BMP280 driver.
#
# Every 10s the time is removed from the screen and the temperature
#  displayed, returning back to the time 5s later.
#
# Every 60 minutes the current temperature is then sent to the SQL Server
# (MariaDB installed on Laguna_NAS).
#
#
# Install Notes:
# 1. Ensure I2C is enabled in raspi-config
# 1a. Update pi:
#          sudo apt-get update
#          sudo apt-get upgrade
# 1b. When installing on Raspberry LITE OS (No GUI), need to install PIP for Python (sudo apt-get install python3-pip)
#          sudo apt install python3-pip
# 1c. Install i2c tools
#          sudo apt-get install -y python3-smbus
#          sudo apt-get install -y i2c-tools
# 1d. Install other dependancies
#          sudo apt-get install git
#          sudo apt-get install python3-pil
# 2. Install Adafruit LED Backpack Python Tools & Drivers
#    This is the link to the Adafruit website that details the LED BAckpack - https://learn.adafruit.com/led-backpack-displays-on-raspberry-pi-and-beaglebone-black/usage
#    These are the lines to install from Terminal:
#          git clone https://github.com/adafruit/Adafruit_Python_LED_Backpack.git
#          cd Adafruit_Python_LED_Backpack
#          sudo python3 setup.py install
# 4. Install the MySQL Connector for Python3:
#          sudo pip3 install mysql-connector-python
# 5. Create the directory for the Time & Temp Python Code:
#          cd ~/
#          mkdir Python
#          cd Python
#          mkdir Code
# 6. Copy the Python Code from computer to the RaspberryPi
#          scp clock_sql.py pi@rpi_hostname:/home/pi/Python/Code/
# 7. Add the line below into /etc/rc.local so that the clock starts as soon as the Pi is started.
#    The line must be added above the last line (exit 0) and it must have the & at the end of the line:
#      sudo python3 /home/pi/Python/Code/clock_sql.py &
# 8. Make sure the  python code is in the /home/pi/Python/Code folder.
#
# ===========================================================================
#
#
# Initialise & Start the Seven Segment Display
segment = SevenSegment.SevenSegment(address=0x70)
segment.begin()
#
# Connect to MariaDB Server on Laguna_NAS
HOST = "192.168.1.6"				# Server IP Address
PORT = "3306"					# MariaDB Port number
DATABASE = "weather"				# Database we want to connect to
USER = "pi"
PASSWORD = "xxxxxxxxxxx"
db_connection = mariadb.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD, port=PORT)
print("Connected to:", db_connection.get_server_info())


t=time.time()					# This establishes a base from which we can count 10s before flicking to the temperature display
exp_t=t						# This establishes a copy of the time base so we can continue to count to 60 mins (3600s) before uploading the temperature to the SQL Server (MariaDB)
print ("Press CTRL+C to exit")
segment.set_brightness(10)			# Set display brightness, range from 1 to 15
remote_id = 2					# ID value to allow data to be isolated in SQL datbase as coming from Laguna Office
filteredVal = 20				# Arbitrary Temperature from which to start as a 95% confidence temp value
alpha = 0.95					# This is the low pass filter, used to level out any invalid temperature readings

try:						# Continually update the time on a 4 char, 7-segment display
  while(True):
    if time.time()-t>10:
      tempStore = open("/sys/bus/w1/devices/28-0000098e2f18/w1_slave")	#change this number to the Device ID of your sensor
      time.sleep(0.5)
      data = tempStore.read()
      time.sleep(0.5)
      tempStore.close()
      tempData = data.split("\n")[1].split(" ")[9]
      degrees = float(tempData[2:])
      degrees = degrees/1000
#      print (data)
#      print (degrees)
#      time.sleep(1)
      filteredVal = ((filteredVal * alpha) + ((1 - alpha) * degrees))


      segment.clear()
      segment.write_display()
      segment.print_float(int(filteredVal), decimal_digits=0, justify_right=False)
      segment.set_fixed_decimal(True)		# Turn on the 'degrees' symbol on the display
      segment.print_hex(12)			# Prints 'C' on the right most segment
      segment.write_display()
      time.sleep(5)
      t=time.time()
    if time.time()-exp_t>3600:
      try:
#        # Now we have to write the temperature to the SQL Server.
         cur = db_connection.cursor()
         sql = "INSERT INTO WEATHER_MEASUREMENT (REMOTE_ID, AMBIENT_TEMPERATURE, GROUND_TEMPERATURE, AIR_QUALITY, AIR_PRESSURE, HUMIDITY, WIND_DIRECTION, WIND_SPEED, WIND_GUST_SPEED, RAINFALL) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
         val = (remote_id, filteredVal, 0, 0, 0, 0, 0, 0, 0, 0)
         cur.execute(sql, val)
         db_connection.commit()
         cur.close()
#         print(f"Last Inserted ID: {cur.lastrowid}")
         exp_t=time.time()
      except db_connection.Error as e:
         print(f"Error: {e}")
    time.sleep(1)
# Back to the main code to constantly update the time in the display
    now = datetime.datetime.now()
    hour = now.hour
    minute = now.minute
    second = now.second

    segment.clear()
    # Set hours
    segment.set_digit(0, int(hour / 10))     # Tens
    segment.set_digit(1, hour % 10)          # Ones
    # Set minutes
    segment.set_digit(2, int(minute / 10))   # Tens
    segment.set_digit(3, minute % 10)        # Ones
    # Toggle colon
    segment.set_colon(second % 2)            # Toggle colon at 1Hz
    # Write the display buffer to the hardware.  This must be called to update the actual display LEDs.
    segment.write_display()
    # Wait a quarter second (less than 1 second to prevent colon blinking)
    time.sleep(0.25)

except KeyboardInterrupt:
  db_connection.close()				# Close connection to database before quitting.
  segment.clear()
  segment.write_display()
2 Likes

Hi Jon,

Cheers for posting that info. If you run that scan command multiple times (watch can be used for this), does the sensor appear and disappear? Definitely odd that it appears on the bus OK, but reports the wrong temp, that’s different to my issue as sensors just stopped reporting on the bus.

127 degrees is actually out of range for these sensors, and the temperature data has an ff in it (first 2 bytes are 2’s complement 12-bit temperature data), does the 07 ever change?

1 Like

ok, here is a quick capture of the repeated output.


127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
50 05 4b 46 7f ff 0c 10 1c : crc=1c YES
50 05 4b 46 7f ff 0c 10 1c t=85000

85.0
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
50 05 4b 46 7f ff 0c 10 1c : crc=1c YES
50 05 4b 46 7f ff 0c 10 1c t=85000

85.0
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937

127.937
ff 07 4b 46 7f ff 01 10 2f : crc=2f YES
ff 07 4b 46 7f ff 01 10 2f t=127937


I also had a thought that the resistor maybe incorrectly resisting… But it measures 4.68k, so close enough to the 4.7 it should be.

Interesting the data coming back is almost always 127.937, but occasionally there is an 85.0 creeps in…

1 Like

Just looking at thid again James, when an 85 degree temp is shown the ff and 07 change.

Jon

1 Like

Well there goes my theory about bits being stuck, but either way it looks like you may just need to bite the bullet and go for a replacement.

Maybe some screw terminals could make this an easier replacement down the line if you find another one fails?

If you’re after a Pi-compatible, incredibly accurate sensor, the TMP117 would be my pick:

I don’t have much longevity data for it, just that we haven’t had any RMAs for them in their whole life (over a year now), and that one of my projects has 4 of these running every minute for 3mo with no issues.

2 Likes

Please check the sensor separately. Preferably with an arduino uno and DallasTemperature library.

1 Like