sandy70
Posts: 14
Joined: Tue Apr 05, 2022 3:08 pm

DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 4:28 pm

I have a raspberry pi B running the following python program to get the temperature from a DS18B20 Temperature Sensor and when I run it I get the following error message after a few readings, it could be 1 or the most I have had are 9.

The temperature is 21.0625 celsius
The temperature is 21.0625 celsius
The temperature is 21.0625 celsius
The temperature is 21.0625 celsius
Traceback (most recent call last):
File "w2.py", line 9, in <module>
temperature = sensor.get_temperature()
File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/core.py", line 328, in get_temperature
value = self.raw_sensor_count
File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/core.py", line 264, in raw_sensor_count
bytes = self.raw_sensor_strings[1].split()
File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/core.py", line 243, in raw_sensor_strings
if data[0].strip()[-3:] != "YES":
IndexError: list index out of range


Here is the code I am running.

Code: Select all

# ds18b20 sensor
import time
from time import sleep
from w1thermsensor import W1ThermSensor
sensor = W1ThermSensor()

while True:

    temperature = sensor.get_temperature()
    print("The temperature is %s celsius" % temperature)
    time.sleep(1)

GPIO.cleanup()
If I run python3 w2.py I get a completely different error message.

python3 w2.py
Traceback (most recent call last):
File "w2.py", line 9, in <module>
temperature = sensor.get_temperature()
File "/usr/local/lib/python3.7/dist-packages/w1thermsensor/core.py", line 267, in get_temperature
raw_temperature_line = self.get_raw_sensor_strings()[1]
File "/usr/local/lib/python3.7/dist-packages/w1thermsensor/core.py", line 250, in get_raw_sensor_strings
raise SensorNotReadyError(self)
w1thermsensor.errors.SensorNotReadyError: Sensor 6f73831e64ff is not yet ready to read temperature

Any suggestions to solve this?

User avatar
B.Goode
Posts: 14602
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 4:51 pm

sandy70 wrote:
Thu Oct 06, 2022 4:28 pm


Any suggestions to solve this?

I don't know whether it will 'solve' it, but you might learn something by leaving longer between readings?

(The datasheet for your sensor may have a precise specification for how frequently it can be read reliably.)

sandy70
Posts: 14
Joined: Tue Apr 05, 2022 3:08 pm

Re: DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 4:57 pm

I don't know whether it will 'solve' it, but you might learn something by leaving longer between readings?
I have tried with longer times between readings

I also have a version of the code that saves the readings and the times to a data file and flashes a LED so I can see if it is still running.

It eventually fails..

Code: Select all

import time
from time import sleep
import datetime
from datetime import date
from w1thermsensor import W1ThermSensor
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
sensor = W1ThermSensor()


GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(12, GPIO.OUT, initial=GPIO.LOW) # Set pin 19 to be an output pin and set initial value to low (off)

while True:
    
    currentimemili = datetime.datetime.now()
    currenttimesecs = currentimemili - \
    datetime.timedelta(microseconds=currentimemili.microsecond)
    print("at the current date and time ")
    print(currenttimesecs.strftime('%d-%m-%Y %H:%M:%S'))
    
    temperature = sensor.get_temperature()
    print("The temperature is %s celsius" % temperature)
    GPIO.output(12, GPIO.HIGH) # Turn on
    sleep(.1) # Sleep for 1 second
    GPIO.output(12, GPIO.LOW) # Turn off
    time.sleep(1)
    
    with open("/var/www/html/ds18.txt", 'a') as f:
        f.write(str(temperature) + " " + "\n")
        f.write(currenttimesecs.strftime('%d-%m-%Y %H:%M:%S' + "  "))
     
GPIO.cleanup()

User avatar
rpiMike
Posts: 2231
Joined: Fri Aug 10, 2012 12:38 pm
Location: Cumbria, UK

Re: DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 5:20 pm

You could at least put a try except around your temp reading code:

Code: Select all

try:
    # read temp
except Exception as e:
    print('Error:',str(e))

User avatar
B.Goode
Posts: 14602
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 5:32 pm

My suggestion for now is to focus your attention on the Python3 version.


Because of this: https://www.python.org/doc/sunset-python-2/



I still suggest stretching the time to longer than the revised 1.1 seconds

Does the error message persist in saying "SensorNotReadyError: Sensor 6f73831e64ff is not yet ready to read temperature"


Is the sensor appropriately cabled to your RPi board, with the right cabling and pullup resistor?


Debugging and troubleshooting is a matter of personal taste, but I preferred the original code you posted. The call to W1ThermSensor.get_temperature() seems to be the only significant issue to resolve.

MiscBits
Posts: 1110
Joined: Wed Jan 27, 2021 12:48 pm

Re: DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 8:15 pm

You could also look to drop the conversion resolution down to 9-bits if you really need to read quickly and only have access to these chips.

I've found reading less than every 5 seconds problematic even with the original chips (i.e. direct from Maxim via approved supplier) with odd data reads outside 'norm' being returned and having to filter them out.

My requirements where odd (tracking temperature patterns across a single pallet of goods) but delivered thousands of data points in an hour with well over a four 9s consistency.

User avatar
bensimmo
Posts: 5747
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 8:36 pm

The sleep time shouldn't alter anything, they take 750ms or so and block the code and should happily trigger again straight after.

I have a few setups doing that for many years now (not on a Pi4 though) one triggering a few at the same time.

Use Python3. As w1thermsensor dropped python2 a year or so back (at release 2.0 of the w1thermsensor module)

Something isn't right with your setup, check cables, resistors etc.
Looks like it can see it but...

Pictures....

What is probably happening is at boot the DS is seen and then dropped (power, dodgy, connection, resistor...) and then you get the ID as a ghost and it is not really there
Similar can happen of you pull it out, W1thermsensor is just telling you that.

trejan
Posts: 5137
Joined: Tue Jul 02, 2019 2:28 pm

Re: DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 10:27 pm

How long is the wire between the Pi and the DS18B20? Do you have the pull-up resistor or are you relying on the internal GPIO pull-up?

sandy70
Posts: 14
Joined: Tue Apr 05, 2022 3:08 pm

Re: DS18B20 Temperature Sensor Index Out of Range

Thu Oct 06, 2022 11:49 pm

this is the output I am getting now with

try:
# read temp
except Exception as e:
print('Error:',str(e))


as you can see it appears to be random.

24.437
24.437
Error: list index out of range
24.5
24.5
24.5
24.5
24.5
24.562
Error: list index out of range
24.625
24.625
24.625
24.625
24.625
24.625
24.687
24.687
24.687
24.687
24.687
24.687
24.687
24.687
Error: list index out of range
Error: list index out of range
24.75
Error: list index out of range
24.75
24.75
24.75
24.75
24.75
24.75
24.75
24.75
24.75
24.75
24.75
Error: list index out of range

User avatar
rpiMike
Posts: 2231
Joined: Fri Aug 10, 2012 12:38 pm
Location: Cumbria, UK

Re: DS18B20 Temperature Sensor Index Out of Range

Fri Oct 07, 2022 8:24 am

If you are sure your wiring is correct, maybe you have a fake DS18B20, did you buy it from a reputable electronics supplier?

How often do you actually need temperature readings?

sandy70
Posts: 14
Joined: Tue Apr 05, 2022 3:08 pm

Re: DS18B20 Temperature Sensor Index Out of Range

Fri Oct 07, 2022 2:26 pm

Re: DS18B20 Temperature Sensor Index Out of Range
Quote rpiMike
by rpiMike » Fri Oct 07, 2022 9:24 am



If you are sure your wiring is correct, maybe you have a fake DS18B20, did you buy it from a reputable electronics supplier?
Ebay, where else.

If I understand this site correctly

https://github.com/cpetrich/counterfeit_DS18B20

If the ROM does not follow the pattern 28-xx-xx-xx-xx-00-00-xx then the DS18B20 sensor is a clone [5].

mine is 28-6f73831e64ff

mine is a fake.

User avatar
scruss
Posts: 5150
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON

Re: DS18B20 Temperature Sensor Index Out of Range

Fri Oct 07, 2022 7:28 pm

as a (very recently) former electronics retailer, the majority of OneWire-compatible sensors available today are not made by Maxim/Dallas, so could be classed as fakes. Unfortunately, because OneWire is such an incredibly complex protocol, all the code implementations follow the Maxim/Dallas spec to the letter. Some of the third party sensors might be a fraction slower, or not quite clear/set all the bits correctly, but the library code is not forgiving of this.

Compare with the DHT11/DHT22 sensors, where all the available code is from reverse-engineering the output. These can randomly fail to give a reading, so library documentation usually says to allow for failures. It would be nice if the OneWire code were rewritten to be forgiving, or at least document the possibility of failures.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.
Pronouns: he/him

sandy70
Posts: 14
Joined: Tue Apr 05, 2022 3:08 pm

Re: DS18B20 Temperature Sensor Index Out of Range

Fri Oct 07, 2022 11:01 pm

Re: DS18B20 Temperature Sensor Index Out of Range
Quote scruss
by scruss » Fri Oct 07, 2022 8:28 pm

as a (very recently) former electronics retailer, the majority of OneWire-compatible sensors available today are not made by Maxim/Dallas, so could be classed as fakes. Unfortunately, because OneWire is such an incredibly complex protocol, all the code implementations follow the Maxim/Dallas spec to the letter. Some of the third party sensors might be a fraction slower, or not quite clear/set all the bits correctly, but the library code is not forgiving of this.

Compare with the DHT11/DHT22 sensors, where all the available code is from reverse-engineering the output. These can randomly fail to give a reading, so library documentation usually says to allow for failures. It would be nice if the OneWire code were rewritten to be forgiving, or at least document the possibility of failures.
So is there anything I can add to my python code to resolve the error I am getting other than ignoring the error?

User avatar
rpiMike
Posts: 2231
Joined: Fri Aug 10, 2012 12:38 pm
Location: Cumbria, UK

Re: DS18B20 Temperature Sensor Index Out of Range

Sat Oct 08, 2022 1:30 pm

Why not just ignore it? You haven’t told us how often you actually need temp readings?

sandy70
Posts: 14
Joined: Tue Apr 05, 2022 3:08 pm

Re: DS18B20 Temperature Sensor Index Out of Range

Sat Oct 08, 2022 2:03 pm

Why not just ignore it?
Because it annoys me.

[quote You haven’t told us how often you actually need temp readings?[/quote]

It makes no difference to how often there is between readings the program still fails.

At present there is 10 seconds between readings and this is the output.



(19.875, 67.775)
('Error:', 'list index out of range')
('Error:', 'list index out of range')
(19.937, 67.8866)
('Error:', 'list index out of range')
(19.937, 67.8866)
('Error:', 'list index out of range')
('Error:', 'list index out of range')
(19.937, 67.8866)
('Error:', 'list index out of range')
(19.937, 67.8866)
('Error:', 'list index out of range')
('Error:', 'list index out of range')
(19.937, 67.8866)
(19.937, 67.8866)
('Error:', 'list index out of range')
('Error:', 'list index out of range')
(19.937, 67.8866)
('Error:', 'list index out of range')
(19.937, 67.8866)
(19.937, 67.8866)
('Error:', 'list index out of range')
(19.937, 67.8866)
(19.937, 67.8866)
(19.937, 67.8866)

User avatar
rpiMike
Posts: 2231
Joined: Fri Aug 10, 2012 12:38 pm
Location: Cumbria, UK

Re: DS18B20 Temperature Sensor Index Out of Range

Sat Oct 08, 2022 4:05 pm

If you only need a temp value every minute, you have plenty of data, just remember the last valid reading.

User avatar
scruss
Posts: 5150
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON

Re: DS18B20 Temperature Sensor Index Out of Range

Sat Oct 08, 2022 5:19 pm

Some other things you can try:
  • check your wiring. Use the wiring described here: w1thermsensor: Hardware-connection. The pull-up resistor (and having it make a reliable connection*) is really important. I wouldn't attempt to use parasitic power (where the sensor's powered from the data line) as only some OneWire sensors support this.
  • drop your sensor resolution down to 9 bits, as the default 12-bit resolution can be very slow. Before your while loop, add in the line sensor.set_resolution(9). Note that to do this, this requires root privileges. There is a way to run this once (as root/sudo) and save the resolution in the sensor's EEPROM if you don't want to run the main script as root. See the persist=True option in the last link. 9 bits will still give you better than 0.5 °C resolution over the whole range of the sensor.
  • the fact that the Python 3 version won't even run at all suggests there may be a problem with your setup, kernel modules, etc.
  • Use the last valid reading if the `try` fails.
It seems that many of the "fake" DS18B20 sensors have entirely legit Galaxy-CAS Gx18b20 sensors inside, but someone, somewhere has relabelled them as DS18B20 to make a few more cents. There's an interesting teardown of the two sensors, with microscope pictures of the circuits inside: Real vs fake DS18B20.

---
*: if you're using a breadboard, most resistor leads are too thin to make a good connection and can glitch out. Thick-lead resistors are much more reliable. Soldering or mechanical crimping (not both) is the most reliable of all, though
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.
Pronouns: he/him

Return to “Beginners”