DS18B20 TO-92 temperature sensor failing? Write a watchdog

Resolving Instability in DS18B20 TO-92 Temperature Sensors: A Practical Guide Artikel auch auf Deutsch verfügbar In my smart home climate module, I employ a variety of sensors and applications to monitor temperature, humidity, air pressure,

Resolving Instability in DS18B20 TO-92 Temperature Sensors: A Practical Guide

Artikel auch auf Deutsch verfügbar

In my smart home climate module, I employ a variety of sensors and applications to monitor temperature, humidity, air pressure, and air quality. However, a recurring issue with the DS18B20 TO-92 temperature sensor led me to devise a solution for uninterrupted data recording. This article shares my experience, detailing the problem, its impact on data collection, and a simple yet effective fix to ensure stable sensor performance.

Initially, I anticipated a seamless integration of the DS18B20 TO-92 sensor alongside the BME688 sensor readings in my database. Unfortunately, this assumption proved incorrect, as I frequently discovered gaps in recorded data during the mornings. The script responsible for data collection often failed to capture temperature readings for extended periods, posing a consistent annoyance.

In the early stages of encountering this issue, my immediate response was to reboot the system, bringing the sensor back online and restoring script functionality. Recognizing the need for a more sustainable solution, I explored the option of resetting the 1-wire bus, unloading and reloading drivers, and reacquiring the sensor. To my relief, this approach worked seamlessly. By simply unloading and reloading the drivers, the DS18B20 sensor was back online within seconds.

To further safeguard against script failures due to sensor unavailability, I implemented a workaround to allow data writing even when a sensor was offline. Additionally, I developed a small watchdog specifically for DS18B20 sensors. This watchdog continuously checks sensor presence and reinitializes the 1-wire bus to bring sensors back online if needed.

The implementation is straightforward: create a ‘w1watchdog.py,’ add it to ‘/etc/rc.local,’ and let it run in a continuous loop. This Python program resets the sensor, ensuring its consistent operation. Since adopting this solution, all my scripts have been running smoothly and reliably. The program also logs activities into ‘/var/log/w1watchdog.log,’ providing insights into the frequency of resets, a helpful troubleshooting tool for maintaining sensor stability.”

Create a w1watchdog.py, add it to /etc/rc.local

nano w1watchdog.py

Copy these lines and paste them into your file:

import subprocess
import time
import logging
   
def setup_logger():
    # Log-Datei konfigurieren
    logging.basicConfig(
        filename='/var/log/w1watchdog.log',
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
   
def check_sensor(device_id):
    try:
        # Versuche das Gerät zu lesen
        subprocess.check_output(['cat', f'/sys/bus/w1/devices/{device_id}/w1_slave'])
        return True
    except subprocess.CalledProcessError:
        return False
   
def reset_w1_bus():
    try:
        # W1-Bus-Module entfernen und wieder hinzufügen
        subprocess.run(['sudo', 'rmmod', '-f', 'w1_gpio'], check=True)
        subprocess.run(['sudo', 'rmmod', '-f', 'w1_therm'], check=True)
        subprocess.run(['sudo', 'modprobe', 'w1_gpio'], check=True)
        subprocess.run(['sudo', 'modprobe', 'w1_therm'], check=True)
    except subprocess.CalledProcessError as e:
        logging.error(f"Fehler beim Zurücksetzen des W1-Bus: {e}")
        raise
   
def main():
    setup_logger()
    device_id = '28-3ce1d443d02b'  # Ersetze durch die tatsächliche Device-ID deines DS18B20-Sensors
   
    while True:
        try:
            if not check_sensor(device_id):
                error_message = f"Sensor {device_id} nicht gefunden. W1-Bus wird zurückgesetzt."
                logging.error(error_message)
                print(error_message)
                reset_w1_bus()
            else:
                logging.info(f"Sensor {device_id} gefunden.")
   
            time.sleep(300)  # Warte 5 Minuten, bevor der nächste Check durchgeführt wird
   
        except Exception as e:
            # Behandle unerwartete Ausnahmen und protokolliere den Fehler
            error_message = f"Unerwarteter Fehler: {str(e)}"
            logging.error(error_message)
   
if __name__ == "__main__":
    main()

Please change your sensor ID here! You find yours here:

ls -la /sys/bus/w1/devices

open /etc/rc.local in a text editor

nano /etc/rc.local

and add the following line to it

python /home/axel/dev/bme688screen/w1watchdog.py

This runs the w1watchdog Python program in a continous loop and resets the sensor and brings it back online. All my scripts run smooth and stable since then. The file also stores a log into /var/log/w1watchdog.log and I can see that it has to be reset several times per day:

2023-12-05 09:26:20 - INFO: Sensor 28-3ce1d443d02b gefunden.
2023-12-05 09:31:21 - INFO: Sensor 28-3ce1d443d02b gefunden.
2023-12-05 09:36:21 - INFO: Sensor 28-3ce1d443d02b gefunden.
2023-12-05 09:41:21 - ERROR: Sensor 28-3ce1d443d02b nicht gefunden. W1-Bus wird zurückgesetzt.
2023-12-05 09:46:22 - INFO: Sensor 28-3ce1d443d02b gefunden.
2023-12-05 09:51:23 - INFO: Sensor 28-3ce1d443d02b gefunden.
2023-12-05 09:56:24 - INFO: Sensor 28-3ce1d443d02b gefunden.
2023-12-05 10:01:25 - INFO: Sensor 28-3ce1d443d02b gefunden.
2023-12-05 10:06:26 - INFO: Sensor 28-3ce1d443d02b gefunden.

By following these steps and incorporating the ‘w1watchdog.py’ solution, you can enhance the stability and reliability of DS18B20 TO-92 temperature sensors in your smart home setup. With consistent sensor operation, you can trust your data collection processes to run seamlessly, eliminating the frustration of missing crucial temperature readings. Best of luck with your sensors, and I hope you won’t find the need for this watchdog in your system!

Leave a Reply

Your email address will not be published. Required fields are marked *