ds18b20 readinig error

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
icebreaker
Posts: 4
Joined: Tue Feb 01, 2022 8:35 pm

ds18b20 readinig error

Post by icebreaker » Tue Feb 01, 2022 8:53 pm

Hi all

I'm running micropython v1.17 on a Wemos D1 mini 4MiB flash.

I have created a little script originaly in C with Arduino and have ported this to micropython, as I wanted to try something new. Now the script is running fine for a couple of hours or sometimes even days, befor the sensor is not found anymore. The only thing which works is, to reset the board. The same code in C is running for years without any issues. This brings me a bit to a software related issue, as it's the same esp, the same sensor and wiring.

I have captured the the result form the ds.scan() which looks like this when it works and when it's not working anymore:

Code: Select all

Found DS devices:  [bytearray(b'(\x86\xady\x97\x06\x03\xb8')]
Found DS devices:  []
I guess its probably the best when I share my code, maybe someone can spot something or has an idea where that could come from.

Code: Select all

import time
from umqtt.simple import MQTTClient
import urequests
import network
import onewire
import ds18x20
import machine

ssid = '****'
password = '*****'
mqtt_server = '*****'
client_id = 'esp8266'

dat = machine.Pin(2)
ds = ds18x20.DS18X20(onewire.OneWire(dat))
relay = machine.Pin(4, machine.Pin.OUT)
tempsoll = 26
url = "http://*****:8086/write?db=aquarium"

# Relay Test
relay.on()
time.sleep(2)
relay.off()


ap_if = network.WLAN(network.AP_IF)
ap_if.active(False)
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
if not sta_if.isconnected():
    print('connecting to network...')
    sta_if.connect(ssid, password)
    while not sta_if.isconnected():
        pass
print('Connection successful:', sta_if.ifconfig())

def connect_mqtt():
    global client_id, mqtt_server
    client = MQTTClient(client_id, mqtt_server)
    client.connect()
    print('Connected to MQTT broker %s ' % (mqtt_server))
    print('Connected as %s' % (client_id))
    return client

def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(5)
    machine.reset()

def read_ds():
    roms = ds.scan()
    print('Found DS devices: ', roms)
    ds.convert_temp()
    time.sleep_ms(750)
    for rom in roms:
        temp = ds.read_temp(rom)
        if isinstance(temp, float):
            temp = round(temp, 2)
            # print(temp, end=' ')
            # print()
        return temp
    return '0'
    # machine.reset()  # little workaround

try:
    client = connect_mqtt()
except OSError as e:
    restart_and_reconnect()

while True:
    messung = read_ds()
    messung_json = '{"temperatur":%s}' % messung
    print(messung_json)
    # client.publish(b'fisch', b'%s' % messung_json)
    # daten = "data temperatur=%s" % messung
    # urequests.post(url, data = daten)
    if (messung > tempsoll):
        # print("bad")
        relay.on()
    elif (messung <= tempsoll):
        # print("good")
        relay.off()
    time.sleep(5)

davef
Posts: 811
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

Re: ds18b20 readinig error

Post by davef » Wed Feb 02, 2022 3:20 am

My suggestion is to try to catch the error:

Code: Select all

     #  read 1-wire HWT temperature
        try:
            ds2.convert_temp()
        except onewire.OneWireError as error:
            try:
                with open('errors.txt', 'a') as outfile:
                    outfile.write('HWT temp ' + str(error) + '\n')
            except OSError:
                pass


        utime.sleep_ms(1000) #  min of 750ms for 1wire conversion

        try:
            HWT_temp = ds2.read_temp(bytearray(b'( ^A\x0c\x00\x00K'))
        except Exception as error:
            try:
                with open('errors.txt', 'a') as outfile:
                    outfile.write('HWT ' + str(error) + '\n')
            except OSError:
               pass
I had one DS18B20 that would occasionally throw an error but at least the above didn't crash the program.

Good luck!

icebreaker
Posts: 4
Joined: Tue Feb 01, 2022 8:35 pm

Re: ds18b20 readinig error

Post by icebreaker » Wed Feb 02, 2022 7:22 pm

I had that in the orginal code, but when I comes in the state of an error (like it can't find a sensor), it would return 0.
Or in my case then reset the whole esp. Because when it can't find a sensor, the next time it will not find it either and so on. Only a reset helps the find it again. But in my opinion, that's not an answer more a workaround.

I have flash again my C code onto the esp, and for the past 4 weeks, there was not a single hickup.

I wanted to give it a try with micropython, but so it's a bit hard (and I don't know any other waterproof sensors).

icebreaker
Posts: 4
Joined: Tue Feb 01, 2022 8:35 pm

Re: ds18b20 readinig error

Post by icebreaker » Tue Feb 15, 2022 6:41 pm

So I was finally able to capture the error, while let it running connected to Thonny.

I used the following code:

Code: Select all

import time
from umqtt.simple import MQTTClient
import urequests
import network
import onewire
import ds18x20
import machine

ssid = '*****'
password = '*****'
mqtt_server = '****'
client_id = 'esp8266'

dat = machine.Pin(2)
ds = ds18x20.DS18X20(onewire.OneWire(dat))
relay = machine.Pin(4, machine.Pin.OUT)
tempsoll = 26
url = "http://*****/write?db=aquarium"

last_message = 0
message_interval = 180
c = 0

ap_if = network.WLAN(network.AP_IF)
ap_if.active(False)
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
if not sta_if.isconnected():
    print('connecting to network...')
    sta_if.connect(ssid, password)
    while not sta_if.isconnected():
        pass
print('Connection successful:', sta_if.ifconfig())

def connect_mqtt():
    global client_id, mqtt_server
    client = MQTTClient(client_id, mqtt_server)
    client.connect()
    print('Connected to MQTT broker %s ' % (mqtt_server))
    print('Connected as %s' % (client_id))
    return client

def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(5)
    machine.reset()

def read_ds():
    roms = ds.scan()
    print('Found DS devices: ', roms)
    ds.convert_temp()
    time.sleep(1)
    for rom in roms:
        temp = ds.read_temp(rom)
        if isinstance(temp, float):
            temp = round(temp, 2)
            # print(temp, end=' ')
            # print()
        return temp
    return '0'
    # machine.reset()

try:
    client = connect_mqtt()
except OSError as e:
    restart_and_reconnect()

while True:
    try:
        messung = read_ds()
        messung_json = '{"temperatur":%s}' % messung
        print(messung_json)
        client.publish(b'test', b'%s' % messung_json)
        #daten = "data temperatur=%s" % messung
        #urequests.post(url, data = daten)
        if (messung > tempsoll):
            #print("bad")
            relay.on()
        elif (messung <= tempsoll):
            #print("good")
            relay.off()
        c += 1
        print(c)
        time.sleep(180)
    except OSError as e:
        restart_and_reconnect()
which had through an error after a bit more than 7 days with this error:

Code: Select all

Found DS devices:  [bytearray(b'(\x86\xady\x97\x06\x03\xb8')]
{"temperatur":23.62}
3690
Found DS devices:  [bytearray(b'(\x86\xady\x97\x06\x03\xb8')]
Traceback (most recent call last):
  File "<stdin>", line 76, in <module>
  File "<stdin>", line 59, in read_ds
  File "ds18x20.py", line 40, in read_temp
  File "ds18x20.py", line 30, in read_scratch
Exception: CRC error
Anybody an idea why this is happening?

davef
Posts: 811
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

Re: ds18b20 readinig error

Post by davef » Tue Feb 15, 2022 7:23 pm

Try another DS18B20. Then Google <fake ds18b20> . Just to clarify ... as well as catching the error your program keeps running now.

User avatar
scruss
Posts: 360
Joined: Sat Aug 12, 2017 2:27 pm
Location: Toronto, Canada
Contact:

Re: ds18b20 readinig error

Post by scruss » Tue Feb 15, 2022 10:00 pm

davef wrote:
Tue Feb 15, 2022 7:23 pm
Try another DS18B20. Then Google <fake ds18b20> . ...
I'm not sure blaming fake ds18b20s is all that helpful. Most of the sensors sold as DS18B20 aren't real Dallas/Maxim parts. Even ones got from reliable resellers can't be guaranteed to legit, so the end user can't be expected to know what they've got. It would be nice if libraries were less strict about CRC checking.

It's a bit like the FTDI serial chip stramash from a few years ago: you can get a real one, or you can get a cheap one. But you can't get a cheap, real one.

davef
Posts: 811
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

Re: ds18b20 readinig error

Post by davef » Tue Feb 15, 2022 11:27 pm

I was impressed by the amount of effort this guy went to try to understand some of the problems people were seeing with this device.
https://github.com/cpetrich/counterfeit_DS18B20.

All I am suggesting is that you don't seem to be able to rely on getting DS18B20s that behave exactly like Maxim designed.

User avatar
scruss
Posts: 360
Joined: Sat Aug 12, 2017 2:27 pm
Location: Toronto, Canada
Contact:

Re: ds18b20 readinig error

Post by scruss » Wed Feb 16, 2022 3:14 am

I'm an electronics distributor. I can't guarantee the ones I source are legit, even from trustworthy sources. That website is a pain in the neck, 'cos we get people complaining we sold them counterfeits. Heck, I used to complain about counterfeits until I started in the distribution chain.

We need more forgiving code, or we're going to have pissed-off users.

icebreaker
Posts: 4
Joined: Tue Feb 01, 2022 8:35 pm

Re: ds18b20 readinig error

Post by icebreaker » Wed Feb 16, 2022 8:04 pm

I have tried two different sensors, which show the same behaviour.
I got waterproof ones in a stainless steel enclosure, so no idea what is inside them..

From my expirience with the arduino code, I had seen similar thing, but in arduino it returns -127 as value. In my cases, when this happend a few times, the sensor was at his end of lifetime. The reason is, a reboot would not bring it back as it does with micropython.

So I still believe, that this is a library "issue"

I'm with scruss, that this will put new people in micropython quick off, as it's a pretty basic sensor with a builtin library. You won't expect having too much truble with it.

davef
Posts: 811
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

Re: ds18b20 readinig error

Post by davef » Wed Feb 16, 2022 11:29 pm

the sensor was at his end of lifetime
I know al things will fail if given enough time but this sounds like there is some "known lifetime issue".

Another suggestion:
I have found that using Robert-HH's 1-wire lib to be more successful
https://github.com/robert-hh/Onewire_DS18X20
I found it easier to add in exception handling.

Post Reply