Coder Social home page Coder Social logo

timofurrer / w1thermsensor Goto Github PK

View Code? Open in Web Editor NEW
493.0 48.0 113.0 366 KB

A Python package and CLI tool to work with w1 temperature sensors like DS1822, DS18S20 & DS18B20 on the Raspberry Pi, Beagle Bone and other devices.

License: MIT License

Python 100.00%
python w1-therm-sensor temperature sensor beaglebone raspberrypi gpio hardware ds18b20 ds18s20

w1thermsensor's Introduction

W1ThermSensor

Gitter

Get the temperature from your w1 therm sensor in a single line of code!
It's designed to be used with the Rasperry Pi hardware but also works on a Beagle Bone and others.


CI PyPI version codecov.io Code style: black

Raspberry Pi: this package is available in Raspbian as python-w1thermsensor and python3-w1thermsensor.

Python 2 drop: all w1thermsensor releases from 2.0 are Python 3.5+

Supported devices

The following w1 therm sensor devices are supported:

  • DS18S20
  • DS1822
  • DS18B20
  • DS28EA00
  • DS1825/MAX31850K

Setup

The following hardware is needed:

  • w1 therm compatible sensor (some of them can be bought here: Adafruit: DS18B20)
  • wires to connect the sensor to your board (you might need a breadboard, too)
  • a board like the Raspberry Pi or the Beagle Bone

On the Raspberry Pi, you will need to add dtoverlay=w1-gpio (for regular connection) or dtoverlay=w1-gpio,pullup="y" (for parasitic connection) to your /boot/config.txt. The default data pin is GPIO4 (RaspPi connector pin 7), but that can be changed from 4 to x with dtoverlay=w1-gpio,gpiopin=x.

After that, don't forget to reboot.

Hardware-connection

Raspi VCC (3V3) Pin 1 -----------------------------   VCC    DS18B20
                                               |
                                               |
                                               R1 = 4k7 ...10k
                                               |
                                               |
Raspi GPIO 4    Pin 7 -----------------------------   Data   DS18B20
       (BCM)    (BOARD)

Raspi GND       Pin 6 -----------------------------   GND    DS18B20

Soft-pull-up

Alternatively to the hardware pull-up made by a physical resistor, or to the above mentioned software configuration dtoverlay=w1-gpio,pullup="y" in /boot/config.txt, the following soft pull-up can be used:

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP)

When using this software pull-up, 1-Wire devices will be visible to the kernel only while the program pulls the GPIO pin up.

Hw device connection verification

Run the following command:

ls -l /sys/bus/w1/devices

You should check the availability of one or more filenames starting with "28-".

Filenames starting with "00-" possibly mean that the pull-up resistor is missing.

1-Wire devices can be plugged in dynamically and are visible to the kernel driver just after their hw connection.

To test reading the temperature, issue the following command:

for i in /sys/bus/w1/devices/28-*; do cat $i/w1_slave; done

Installation

From PIP

This possibility is supported on all distributions:

pip install w1thermsensor

Note: maybe root privileges are required

Use the async extra to add support for asyncio and AsyncW1ThermSensor:

pip install w1thermsensor[async]

On Raspbian using apt-get

If you are using the w1thermsensor module on a Rasperry Pi running Raspbian you can install it from the official repository:

sudo apt-get install python3-w1thermsensor

Note: For older versions of this package you might get the following error: ImportError: No module named 'pkg_resources' which indicates that you need to install python-setuptools or python3-setuptools respectively.

Manually build and install the debian package

debuild -us -uc
dpkg -i ../python3-w1thermsensor_*.deb

Usage as python package

The usage is very simple and the interface clean.. All examples are with the DS18B20 sensor - It works the same way for the other supported devices.

Basic usage with one sensor (implicit)

from w1thermsensor import W1ThermSensor, Unit

sensor = W1ThermSensor()
temperature_in_celsius = sensor.get_temperature()
temperature_in_fahrenheit = sensor.get_temperature(Unit.DEGREES_F)
temperature_in_all_units = sensor.get_temperatures([
    Unit.DEGREES_C,
    Unit.DEGREES_F,
    Unit.KELVIN])

The need kernel modules will be automatically loaded in the constructor of the W1ThermSensor class.
If something went wrong an exception is raised.

The first found sensor will be taken

Basic usage with one sensor (explicit)

The DS18B20 sensor with the ID 00000588806a will be taken.

from w1thermsensor import W1ThermSensor, Sensor

sensor = W1ThermSensor(sensor_type=Sensor.DS18B20, sensor_id="00000588806a")
temperature_in_celsius = sensor.get_temperature()

Multiple sensors

With the get_available_sensors class-method you can get the ids of all available sensors.

from w1thermsensor import W1ThermSensor

for sensor in W1ThermSensor.get_available_sensors():
    print("Sensor %s has temperature %.2f" % (sensor.id, sensor.get_temperature()))

Only sensors of a specific therm sensor type:

from w1thermsensor import W1ThermSensor, Sensor

for sensor in W1ThermSensor.get_available_sensors([Sensor.DS18B20]):
    print("Sensor %s has temperature %.2f" % (sensor.id, sensor.get_temperature()))

Set sensor resolution

Some w1 therm sensors support changing the resolution for the temperature reads. w1thermsensor enables to do so with the W1ThermSensor.set_resolution() method:

sensor = W1ThermSensor(sensor_type=Sensor.DS18B20, sensor_id="00000588806a")
sensor.set_resolution(9)

If the persist argument is set to False this value is "only" stored in the volatile SRAM, so it is reset when the sensor gets power-cycled.

If the persist argument is set to True the current set resolution is stored into the EEPROM. Since the EEPROM has a limited amount of writes (>50k), this command should be used wisely.

sensor = W1ThermSensor(sensor_type=Sensor.DS18B20, sensor_id="00000588806a")
sensor.set_resolution(9, persist=True)

Note: this is supported since Linux Kernel 4.7
Note: this requires root privileges

Disable kernel module auto loading

Upon import of the w1thermsensor package the w1-therm and w1-gpio kernel modules get loaded automatically. This requires the python process to run as root. Sometimes that's not what you want, thus you can disable the auto loading and load the kernel module yourself prior to talk to your sensors with w1thermsensor.

You can disable the auto loading feature by setting the W1THERMSENSOR_NO_KERNEL_MODULE environment variable to 1:

# set it globally for your shell so that sub-processes will inherit it.
export W1THERMSENSOR_NO_KERNEL_MODULE=1

# set it just for your Python process
W1THERMSENSOR_NO_KERNEL_MODULE=1 python my_awesome_thermsensor_script.py

Every other values assigned to W1THERMSENSOR_NO_KERNEL_MODULE will case w1thermsensor to load the kernel modules.

Note: the examples above also apply for the CLI tool usage. See below.

Correcting Temperatures / Sensor Calibration

Calibrating the temperature sensor relies on obtaining a measured high and measured low value that have known reference values that can be used for correcting the sensor's readings. The simplest way to do this is to measure the melting point and boiling point of water since those values are known. This method will only work with waterproof sensors - you will need a different mechanism for obtaining measured values if you are not using a waterproof sensor.

In order to obtain the measured_low_point, fill a container to 80% with ice and add water to the ice until the ice is floating and water is at the surface. Submerse your sensor in the ice water, ensuring it does not touch the container. Wait 5 minutes for the temperature to stabilize in the container and then once the sensor readings have stabilized for approximately 30 seconds (readings remain consistent), record the value as the measured_low_point

In order to obtain the measured_high_point, bring a pot of water to a rapid boil. Place your sensor in the boiling water, ensuring that it does not touch the pot. Allow the sensor to come up to temperature and once it has stabilized for approximately 30 seconds (readings remain consistent), record the value as the measured_high_point

Generally speaking, the reference_low_point should be left at 0.0 unless you have some special situation that changes the melting point of water. Because melting does not involve a gaseous phase change, the effects of air pressure and altitude on the melting point are minimal.

The reference_high_point on the other hand is greatly impacted by air pressure (and thus altitude). For example, the boiling point of water is 100.0C at sea level, and is approximately 72C at the summit of Mount Everest (8848m above sea level). While air pressure is what actually dictates boiling point, generally speaking altitude is a close enough approximation for most use cases. Engineering Toolbox has a page that gives you the boiling point of water at different altitudes.

This method is derived from this Instructable.

from w1thermsensor.calibration_data import CalibrationData
from w1thermsensor import W1ThermSensor, Unit

calibration_data = CalibrationData(
        measured_high_point=measured_high_point,
        measured_low_point=measured_low_point,
        reference_high_point=reference_high_point,
        reference_low_point=reference_low_point, # optional, defaults to 0.0
    )
sensor = W1ThermSensor(calibration_data=calibration_data)

corrected_temperature_in_celsius = sensor.get_corrected_temperature()
corrected_temperature_in_fahrenheit = sensor.get_corrected_temperature(Unit.DEGREES_F)
corrected_temperature_in_all_units = sensor.get_corrected_temperatures([
    Unit.DEGREES_C,
    Unit.DEGREES_F,
    Unit.KELVIN])

Async Interface

The w1thermsensor package implements an async interface AsyncW1ThermSensor for asyncio.

The following methods are supported:

  • get_temperature()
  • get_temperatures()
  • get_resolution()

For example:

from w1thermsensor import AsyncW1ThermSensor, Unit

sensor = AsyncW1ThermSensor()
temperature_in_celsius = await sensor.get_temperature()
temperature_in_fahrenheit = await sensor.get_temperature(Unit.DEGREES_F)
temperature_in_all_units = await sensor.get_temperatures([
    Unit.DEGREES_C,
    Unit.DEGREES_F,
    Unit.KELVIN])

Usage as CLI tool

The w1thermsensor module can be used as CLI tool since version 0.3.0.
Please note that the CLI tool will only get installed with the Raspbian Python 3 package (sudo apt-get install python3-w1thermsensor)

List sensors

List all available sensors:

$ w1thermsensor ls
$ w1thermsensor ls --json  # show results in JSON format

List only sensors of a specific type:

$ w1thermsensor ls --type DS1822
$ w1thermsensor ls --type DS1822 --type MAX31850K  # specify multiple sensor types
$ w1thermsensor ls --type DS1822 --json  # show results in JSON format

Show temperatures

Show temperature of all available sensors: (Same synopsis as ls)

$ w1thermsensor all --type DS1822
$ w1thermsensor all --type DS1822 --type MAX31850K  # specify multiple sensor types
$ w1thermsensor all --type DS1822 --json  # show results in JSON format

Show temperature of a single sensor:

$ w1thermsensor get 1  # 1 is the id obtained by the ls command
$ w1thermsensor get --hwid 00000588806a --type DS18B20
$ w1thermsensor get 1  # show results in JSON format

Show temperature of a single sensor in the given resolution

$ w1thermsensor get 1 --resolution 10
$ w1thermsensor get --hwid 00000588806a --type DS18B20 --resolution 11

Change temperature read resolution and write to EEPROM

# w1thermsensor resolution 10 1
# w1thermsensor resolution --hwid 00000588806a --type DS18B20 11

Note: this requires root privileges

Contribution

I'm happy about all types of contributions to this project! 🍻


This project is published under MIT.
A Timo Furrer project.
- 🎉 -

w1thermsensor's People

Contributors

bggardner avatar brettlounsbury avatar bschick avatar claws avatar erolfr avatar framer99 avatar gitter-badger avatar hbradio avatar ianmtaylor1 avatar ircama avatar jakeler avatar jamesmyatt avatar jasonehines avatar jogi-k avatar jonte avatar klaushuber avatar oderik avatar payne92 avatar pintman avatar rcpeters avatar rgbkrk avatar senden9 avatar thijstriemstra avatar timofurrer avatar xecdesign avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

w1thermsensor's Issues

Beaglebone Black compatibility (Debian, 3.8 Kernel)

I've gotten this library to work on my beaglebone, but I had to manually load a custom device tree overlay before importing this library. Otherwise, the way this module checks for properly loaded module silently fails.
This module checks for existence of a folder as a proxy for module being loaded, but on beaglebone, the folder exists regardless, so this is why it silently does not work. Manually loading your own dto will solve problem and code works fine after that. I can supply additional details if anyone wants, but I'm too busy at the moment. I didn't have experience with device tree overlays before this, so it was quite the learning experience, but honestly the fix is easy now that I know what to do.

Cannot load w1 therm kernel modules on Raspberry Pi

On Raspbian Stretch, i am facing this issue.

Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170124] on linux2
Type "help", "copyright", "credits" or "license" for more information.

from w1thermsensor import W1ThermSensor
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/init.py", line 7, in
from .core import W1ThermSensor # noqa
File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/core.py", line 316, in
load_kernel_modules()
File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/core.py", line 310, in load_kernel_modules
raise KernelModuleLoadError()
w1thermsensor.errors.KernelModuleLoadError: Cannot load w1 therm kernel modules

Onion.io compatibility

Nice library, what would i need to do to make this compatible with an onion.io board? Or would it be compatible out the box? Unsure how it handles the lowest level interactions with gpio

CLI not installed?

Hello everyone. I tried to install w1thermsensor on my Raspberry Pi 3 with both apt-get install python-w1thermsensor and pip install w1thermsensor but it seems that che CLI utility doesn't get installed on my Pi. Launching it always yields me a "command not found" error.

Am I missing something?

async support

Would be nice to use the async support in python 3.5/3.6.

ImportError: cannot import name Sensor

Hello,

I've just installed the code according to the guide and without any problems on an updated Raspian and the program manages to read both of my sensors, but when I try to use the code to change the resolution, I receive this error:

Traceback (most recent call last):
File "Test.py", line 2, in
from w1thermsensor import W1ThermSensor, Sensor
ImportError: cannot import name Sensor

This is my code:

from w1thermsensor import W1ThermSensor, Sensor

sensor = W1ThermSensor(Sensor.DS18B20, "0301a279fa6e")
sensor.set_resolution(9)

Thanks in advance for your help.

Error: no such option --precision

Hi, thanks for the great lib, but I get the Error:

w1thermsensor get 1 --precision 10
Error: no such option: --precision

Sensor details:

w1thermsensor ls
Found 1 sensors:

  1. HWID: 000008fdb09d Type: DS18B20

also

w1thermsensor get --hwid 000008fdb09d --type DS18B20 --precision 11

as well as the example code from python doesn't work for setting the precision.

System info:

raspberrypi 3
uname -a
Linux raspberrypi 4.9.24-v7+ #993 SMP Wed Apr 26 18:01:23 BST 2017 armv7l GNU/Linux

Rasbian apt-get install not working(?)

I'd rather not install pip if I don't have to. I'm trying to keep my SD image slim by using Minibian. I've run sudo apt-get install python-w1thermsensor and it seems to have installed just fine, but there's no w1thermsensor command available. I'm just getting -bash: w1thermsensor: command not found. python-w1thermsensor also doesn't work. I also tried reloading bash and rebooting.

Huge delay on CLI

I have a Pi 1, so I'm not sure if this is the cause, but when using the CLI there is a 10-20 second delay on every command. Is this normal? The command output is normal, but the delay seems insane.

Resolution = Precision ?

In order to change sensor resolution, the documentation refers to
sensor.set_resolution() (Python case)
w1thermsensor --resolution (CLI case)

But it does not work : the rights syntax seems to be
sensor.set_precision() (Python case)
w1thermsensor --precision (CLI case)

Side note : root is required for such resolution change, I think this may be written in the doc also.

w1thermsensor

Hello,
Great library. I have used it successfully for groups of sensors.
Something I have noticed and been unable to resolve:

from w1thermsensor import W1ThermSensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
while True:
    for sensor in W1ThermSensor.get_available_sensors():
        print("Sensor %s has temperature %.2f" % (sensor.id, sensor.get_temperature()))
   time.sleep(10)

the above works fine and if I run the program with 3 sensors I get a line for each.
If I then stop the program and remove a sensor and run it again it returns this message :
"w1thermsensor.core.SensorNotReadyError: Sensor is not yet ready to read temperature"

What do I need to do to clear the old list of sensors and start over. ?

thanks

get_temperature does not raise raw_sensor_count exception

Calling get_temperature never gives ResetValueError.

Within the method get_temperature there is a check whether the sensor is in reset phase which should raise a ResetValueError however the check is made on the raw data rather than the refactored data hence is never 85.0. The check probably be done on the value returned by raw_sensor_count with appropriate value.

Unable to get Python 3 W1ThermSensor work with RPi 1-Wire Pi Plus adapter card

I have been trying to get DS18B20 1-Wire temperature sensors to work with Raspberry Pi 2, with the 1-Wire Pi Plus adapter card installed, as in article https://www.abelectronics.co.uk/p/60/1-wire-pi-plus.
To proceed, I have followed the guidelines in this article https://www.abelectronics.co.uk/kb/article/1/i2c--smbus-and-raspbian-linux.
To get a Python 3 compatible library to read the sensors, I also installed the W1ThermSensor, as in article https://pypi.org/project/w1thermsensor.
Essentially, here I ran the following command: sudo apt-get install python3-w1thermsensor.

However, when I ran the following Python demo script:

import time
from w1thermsensor import W1ThermSensor
sensor = W1ThermSensor()
tempr = sensor.get_temperature()

with the Thonny Python IDE, I end up with the following error message:

Python 3.5.3 (/usr/bin/python3)

%Run testi-2018-12a.py
PROBLEM WITH THONNY'S BACK-END:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 1164, in _execute_prepared_user_code
exec(statements, global_vars)
File "/home/pi/Honka/testi-2018-12a.py", line 3, in
sensor = W1ThermSensor()
File "/usr/lib/python3/dist-packages/w1thermsensor/core.py", line 118, in init
raise NoSensorFoundError("Unknown", "")
w1thermsensor.errors.NoSensorFoundError: No Unknown temperature sensor with id '' found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 1141, in execute_source
return self._prepare_hooks_and_execute(bytecode, None, global_vars)
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 1156, in _prepare_hooks_and_execute
return self._execute_prepared_user_code(statements, expression, global_vars)
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 1173, in _execute_prepared_user_code
return {"user_exception": self._vm._prepare_user_exception()}
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 1029, in _prepare_user_exception
"stack": self._export_stack(last_frame),
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 932, in _export_stack
locals=self.export_variables(system_frame.f_locals),
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 886, in export_variables
result[name] = self.export_value(variables[name], 100)
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 876, in export_value
rep = repr(value)
File "/usr/lib/python3/dist-packages/w1thermsensor/core.py", line 150, in repr
self.class.name, self.type, self.id)
AttributeError: 'W1ThermSensor' object has no attribute 'type'

So it seems that the W1ThermSensor library is unable to enumerate any of the (two) DS18B20 sensors that are connected.

Troubleshooting steps that I did:

  1. When using the (Python2 only) owfs library, as in article https://www.abelectronics.co.uk/kb/article/3/owfs-with-i2c-support-on-raspberry-pi,
    and ran the python example code listed in it, both of the DS18B20 sensors enumerate OK.
    So it seems that the sensor and adapter card connections are working as intended.

  2. When executed this command: i2cdetect -y 1, as in article https://raspberryblog.de/?p=2293, the "18" is shown as adviced.

  3. This command: lsmod | grep i2c, the listing is as follows:
    i2c_bcm2835 16384 0
    i2c_dev 16384 0
    (so, instead of listing this: "i2c_bcm2708", as in some articles, like here: https://www.abelectronics.co.uk/forums/thread/113/1-wire-plus-is-not-being-seen-with-i2cdetect)

  4. I also reinstalled the RPi from scratch, as in article https://www.imore.com/how-get-started-using-raspberry-pi,
    plus installed the guizero, i2c-tools, and python3-w1thermsensor, etc. needed modules (no any owfs installs however), but with same results.


I wouldn't want to switch to owfs library, because AFAIK is is only available for Python2.
For example, the guizero library only works in Python3, so that's why I try to target the Python3.

What to do to get the W1ThermSensor work here?

Wiring Diagram suggestion

The wiring diagram appears to show a pull down resistor, connecting the signal line to ground. This should be, IMHO, a pull-up resistor connected to the supply line.
...but thanks for publishing a brilliant library that makes a very complex interface really easy to implement.
Dave

RPi, which input to use?

Hi,
me again!
Just trying to familiarise myself with this library, but getting no sensor found error, which input should the sensor be connected to on an rpi zero? Is there any way to change that pin?
Thanks

Conversion time delay

I reduced the resolution to 9 bits in order to be able to acquire all my data (temperature, photovoltaic power and an image) at 1Hz, but I'm still getting what seems to be a 750 ms conversion time., 900+ ms total reading time.

Below is my test code and result:

from w1thermsensor import W1ThermSensor
import time

sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "04168613d9ff")

t1 = time.perf_counter()
temp = sensor.get_temperature()
t2 = time.perf_counter()

print(t2-t1)
print(temp)
(py3cv4gpio_mestrado) pi@GBSky:~/mestrado $ python w1thermtest.py
0.920645008000065
72.5

Drop pre-release version numbering?

Question
The only v2.x release on PyPI is a pre-release version. This means that pip won't install it without setting --pre. Your README says to install the package using pip install w1thermsensor, which will only ever install 1.3.0 while 2.x is pre-release.

Since this appears to be your stable version now (1.3.x is unsupported as made clear in #96 ), will you be dropping the pre-release version numbering? Otherwise the only non-pre-release version (in Python 2 or 3) still contains the bug from #96 . I would have mentioned this as a comment on that issue, but unfortunately you locked the issue before I could.

Code stopped by SensorNotReady Error

First of all, great library, it's saved me a lot of time setting up my temperature monitoring system. I'm running this code to read from 12 different DS18B20 sensors every 30 secs and write to a CSV. The first time I ran it, it read about 210 times before throwing this error. Last time, only 2 reads before stopping. What is the problem here?

from w1thermsensor import W1ThermSensor
import csv
import time

#Sensors are labeled according to Shelf-Location, e.g. TL=Top-left.
#Left/Right based on facing into fridge from door

sensorTF=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000b20a912")
sensorTB=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000b208271")
sensorTR=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000a9ae2c7")
sensorTL=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000b1fde3a")
sensorMF=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000b201718")
sensorMB=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000a99ff32")
sensorMR=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000b2065d1")
sensorML=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000b1ffd03")
sensorBFR=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000a9a1729")
sensorBFL=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000a9a972b")
sensorBBR=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000a99b35a")
sensorBBL=W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000b1fcb31")

with open('IceboxTemps.csv', 'w') as f:
	thewriter = csv.writer(f)

	thewriter.writerow(['Time (s)', 'TopFront', 'TopBack', 'TopRight', 'TopLeft', 'MidFront', 'MidBack', 'MidRight', 'MidLeft', 'BotFrontRight', 'BotFrontLeft', 'BotBackRight', 'BotBackLeft'])
	for i in range(1,721):
		t=(i-1)*30
		thewriter.writerow([t, sensorTF.get_temperature(), sensorTB.get_temperature(), sensorTR.get_temperature(), sensorTL.get_temperature(), sensorMF.get_temperature(), sensorMB.get_temperature(), sensorMR.get_temperature(), sensorML.get_temperature(), sensorBFR.get_temperature(), sensorBFL.get_temperature(), sensorBBR.get_temperature(), sensorBBL.get_temperature()])
		time.sleep(30)

Is a nonblocking interface possible?

I am testing the package on my RPi 3 for use in a home automation system, and so far it works fine.

The only problem I have is that every call to sensor.get_temperature() blocks my program for about 1 second. If only we had a non-blocking interface to utilize the 1-second for other useful tasks.

Something like the following:

    sensor.start_conversion()
    #do other stuff here
    if sensor.is_conversion_ready():
            temp=sensor.get_temperature()

Many thanks

Murat Isik
murat . isik . istanbul @ gmail

Need to have separate GPIO pins for Tx and Rx

Currently, the 1-wire devices can easily be connected to single GPIO line, like GPIO4.
That kind of usage is very demonstrative, because it is easy to connect one or more DS18B20's there and start measuring.
However, there is need connect sensors via optocoupler, which help in protecting RPi devices from electrical glitches, especially from long distance wiring.
But connecting optocouplers is fairly difficult, in such bi-directional input/output channel usage, which 1-wire uses.

Resolution: Imagine if it was possible to define separate GPIO pins for Tx and Rx, for example with
dtoverlay=w1-gpio,gpiotx=4,gpiorx=17
Then there would be two lines from RPi, and wiring would be greatly easier.

Can the w1thermsensor already be used that way, or is it possible to modify it like that?

IndexError: list index out of range

I have four DS18B20 sensors on the 1-wire network of a Raspberry Pi. After a long time (multiple hours, actual time may vary) of calling get_temperature() every 30 seconds in a while loop, I get an IndexError with the following trace:

Aug 18 03:19:00 hot-tub balboa-mqtt.py[9327]:   File "/usr/local/lib/python3.7/dist-packages/w1thermsensor/core.py", line 263, in get_temperature
Aug 18 03:19:00 hot-tub balboa-mqtt.py[9327]:     raw_temperature_line = self.get_raw_sensor_strings()[1]
Aug 18 03:19:00 hot-tub balboa-mqtt.py[9327]:   File "/usr/local/lib/python3.7/dist-packages/w1thermsensor/core.py", line 245, in get_raw_sensor_strings
Aug 18 03:19:00 hot-tub balboa-mqtt.py[9327]:     if data[0].strip()[-3:] != "YES" or "00 00 00 00 00 00 00 00 00" in data[0]:
Aug 18 03:19:00 hot-tub balboa-mqtt.py[9327]: IndexError: list index out of range

After I restart the script, everything is happy, but it eventually occurs again. I will be adding some logging and updating this issue as I discover more. Any guidance is appreciated.

Environment and Version

  • Hardware: Raspberry Pi 2 Model B Rev 1.1
  • OS: Raspbian OS Buster 10.4 (latest updates)
  • Python Version: 3.7.3
  • w1thermsensor Version: 2.0.0a1 (issue also exists with distro release)

Intermittent Connection Crashes W1

I updated my Pi hardware and BCRobotics Weather HAT. It turns out that I had an intermittent connection problem with my temperature sensor. WeeWX (Python V3) would run for hours and then crash (see error below).

It would be nice to have to W1 code just log the error but carry on and not terminate.

---------- Error -----------------
Oct 14 05:00:17 IOTTAWA98 weewx[12418] INFO weewx.manager: Added record 2020-10-14 05:00:00 EDT (1602666000) to database 'weewx'
Oct 14 05:00:17 IOTTAWA98 weewx[12418] INFO weewx.manager: Added record 2020-10-14 05:00:00 EDT (1602666000) to daily summary in 'weewx'
Oct 14 05:00:17 IOTTAWA98 weewx[12418] INFO weewx.restx: Wunderground-PWS: Published record 2020-10-14 05:00:00 EDT (1602666000)
Oct 14 05:00:19 IOTTAWA98 weewx[12418] INFO weewx.engine: Main loop exiting. Shutting engine down.
Oct 14 05:00:19 IOTTAWA98 weewx[12418] INFO weewx.engine: Shutting down StdReport thread
Oct 14 05:00:22 IOTTAWA98 weewx[12418] INFO weewx.cheetahgenerator: Generated 8 files for report SeasonsReport in 5.26 seconds
Oct 14 05:00:27 IOTTAWA98 systemd[1]: apt-daily.service: Succeeded.
Oct 14 05:00:27 IOTTAWA98 systemd[1]: Started Daily apt download activities.
Oct 14 05:00:37 IOTTAWA98 weewx[12418] INFO weewx.imagegenerator: Generated 30 images for report SeasonsReport in 14.59 seconds
Oct 14 05:00:37 IOTTAWA98 weewx[12418] INFO weewx.reportengine: Copied 0 files to /var/www/html/weewx
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: Caught unrecoverable exception:
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** list index out of range
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** Traceback (most recent call last):
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** File "/usr/share/weewx/weewxd", line 154, in main
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** engine.run()
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** File "/usr/share/weewx/weewx/engine.py", line 188, in run
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** for packet in self.console.genLoopPackets():
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** File "/usr/share/weewx/user/BCRobotics.py", line 229, in genLoopPackets
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** readings = StationData.get_readings()
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** File "/usr/share/weewx/user/BCRobotics.py", line 301, in get_readings
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** if TempSensor : out_Temp = ds18b20.get_temperature()
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** File "/usr/lib/python3/dist-packages/w1thermsensor/core.py", line 230, in get_temperature
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** return factor(self.raw_sensor_value)
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** File "/usr/lib/python3/dist-packages/w1thermsensor/core.py", line 193, in raw_sensor_value
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** if data[0].strip()[-3:] != "YES":
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** IndexError: list index out of range
Oct 14 05:00:37 IOTTAWA98 weewx[12418] CRITICAL main: **** Exiting.
Oct 14 05:04:39 IOTTAWA98 rngd[370]: stats: bits received from HRNG source: 2120064
Oct 14 05:04:39 IOTTAWA98 rngd[370]: stats: bits sent to kernel pool: 2073312
Oct 14 05:04:39 IOTTAWA98 rngd[370]: stats: entropy added to kernel pool: 2073312
Oct 14 05:04:39 IOTTAWA98 rngd[370]: stats: FIPS 140-2 successes: 106

Error on CLI

Using Python 2.7.9 on latest Raspbian Jessie on a Pi 3. Installed via pip install w1thermsensor.
Attempting to use the CLI results in a "no such file or directory" error regarding 'test/mockedsensors'.

Kernel modules w1-gpio and w1-therm are loaded. A single MAX31850 is connected to GPIO 4. (IC GND - Pi GND; IC VIN - Pi 3.3V; IC 3.3V - 4.7K Resistor - IC DATA and Pi GPIO 4).

Running w1thermsensor in the command line with no arguments functions normally.

Running w1thermsensor ls or w1thermsensor all results in this error message (same for both):

Traceback (most recent call last):
  File "/usr/local/bin/w1thermsensor", line 9, in <module>
    load_entry_point('w1thermsensor==0.3.0', 'console_scripts', 'w1thermsensor')()
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 716, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 696, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 1060, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 889, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 534, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/cli.py", line 87, in all
    sensors = W1ThermSensor.get_available_sensors(types)
  File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/core.py", line 94, in get_available_sensors
    return [cls(cls.RESOLVE_TYPE_STR[s[:2]], s[3:]) for s in listdir(cls.BASE_DIRECTORY) if is_sensor(s)]
OSError: [Errno 2] No such file or directory: 'test/mockedsensors'

Running w1thermsensor get (any valid argument) results in this error message instead:

Traceback (most recent call last):
  File "/usr/local/bin/w1thermsensor", line 9, in <module>
    load_entry_point('w1thermsensor==0.3.0', 'console_scripts', 'w1thermsensor')()
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 716, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 696, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 1060, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 889, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 534, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/cli.py", line 135, in get
    sensor = W1ThermSensor(type_, hwid)
  File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/core.py", line 112, in __init__
    self._load_kernel_modules()
  File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/core.py", line 155, in _load_kernel_modules
    raise KernelModuleLoadError()
w1thermsensor.core.KernelModuleLoadError: Cannot load w1 therm kernel modules

Thanks for any help you can provide!

Threading of sensor reads

As far as I can tell, from use, you access each sensor sequencially.
Would it be possible to implement threading to access them concurrently, this would speed up reading taking for more than one sensor.

I assume people would want to be able to disable the use of threads for whatever reason.

I've had a search and found this that may or may not give an idea.
https://gist.github.com/RobThree/c6b9a5dc16357eeb0e011d3ed9a281b0

SLAVE_PREFIX = "10-"

I probably have a different version of the DS1820, but it still works with your module once I changed the SLAVE_PREFIX to "10-".

Perhaps you could allow either 28 or 10 as a SLAVE_PREFIX, or mention it in the README.

Document frequenctly asked questions in the wiki

There should be an FAQ in the wiki.
The closed issue contain a lot of knowledge and ways to debug issues.
I'd like to have them available in a wiki and also issue templates
which states what information is needed for debugging.

water temp sensor - sleep() does not work as intended!!

I have a water temp sensor DS18B20 (https://www.adafruit.com/product/381)
It's connected to pin GPIO4 and it has a 10k resistor like recommended
I want to have readings every second
So I've done this

from time import sleep
from datetime import datetime
from w1thermsensor import W1ThermSensor
## Constants
MEASURE_INTERVAL = 1   #seconds
while True:
    d = datetime.now()
    time_ = '{:%H:%M:%S}'.format(d)
    # (DS18B) Water temperature sensor
    try:
        w = W1ThermSensor()
        water_temp = str(w.get_temperature())  # default pin GPIO4 for data and temp in Celsius degrees
    except:
        water_temp = '0'
    print(time_,water_temp)
    sleep(MEASURE_INTERVAL)

However instead 1 sec interval I'm having 2 sec consistently (most of times)
this is the result

17:20:55 19.437
17:20:57 19.437
17:20:59 19.437
17:21:01 19.437
17:21:03 19.437
17:21:05 19.437
17:21:06 19.437
17:21:08 19.437
17:21:10 19.437
17:21:12 19.437
17:21:14 19.437
17:21:16 19.437
17:21:17 19.437
17:21:19 19.437
17:21:21 19.437

Why? I don't understand
should i change something in W1ThermSensor class?

Received IndexError instead of SensorNotReadyError from get_raw_sensor_strings() when reading DS18B20

I am having a few DS18B20 sensors connected to raspberry pi zero. From time to time the contents of the file /sys/bus/w1/devices/28.../w1_slave appears to be empty (not sure why). Hence the contents of the list data in the method get_raw_sensor_strings() in file async_core.py is empty as well. Accessing it raises an IndexError.

Changing line 65 in file async_core.py from:

     if (
            data[0].strip()[-3:] != "YES" or "00 00 00 00 00 00 00 00 00" in data[0]
        ):  # pragma: no cover
            raise SensorNotReadyError(self) 

to

     if (
           not data or data[0].strip()[-3:] != "YES" or "00 00 00 00 00 00 00 00 00" in data[0]
        ):  # pragma: no cover
            raise SensorNotReadyError(self) 

resolves the problem.

Thanks.

PS: I am using version w1thermsensor 2.0.0a1

Update to using f-strings instead of sting.format()

Update to using f-strings instead of sting.format()

Is your Feature Request related to a problem? Please describe.
This is just a nice to have.
f-strings are the new Python3.6+ method and are apparently much faster* especially in later python3's and for me easier to read too.
try a search on are f-strings faster than .format

Describe the solution you'd like
Change all strings from .format to f-string

Describe alternatives you've considered
No alternative other than no rush as not vital, 1-wire is slow anyway, but every little helps.

Additional context
Something for a rainy day.
It's the way forward for Python3
It does mean a drop of Python3.5 support (support for 3.5 has been dropped by Python)

Error handle 85 centigrades for DS18B20

Background

This code does not take the "reset" code 85 centigrades into account.
Thus - the code claims that the sensor says 85 degrees, even though it is an error code for DS18B20

That information is stated in the rasperry pi forums and also in the data sheet.

Needed solution

Add another guard in the raw_data section so it raises the SensorNotReadyError if the readout is exactly 85000 millicentigrades, and not only handle CRC failures as is now.

if data[0].strip()[-3:] != "YES":
raise SensorNotReadyError()
return float(data[1].split("=")[1])

This check should possibly only be done for the model DS18B20. I have limited knowledge about the other supported variants.

ImportError: cannot import name 'Sensor' from 'w1thermsensor'

Describe the bug
Hello, when I try to run a simple code (see code below) I receive this error:

Traceback (most recent call last):
  File "temperature.py", line 1, in <module>
    from w1thermsensor import W1ThermSensor, Sensor
ImportError: cannot import name 'Sensor' from 'w1thermsensor' (/usr/lib/python3/dist-packages/w1thermsensor/__init__.py)

Environment and Version

  • OS (incl. distribution and version): Raspbian (10 Buster)
  • Python Version: 3.7.3
  • w1thermsensor Version (w1thermsensor --version): 2.0.0
  • If applicable: DS18B20 wired to a Raspberry Pi 3 B+

To Reproduce
w1thermsensor installed via sudo apt-get install python3-w1thermsensor

simple test code:

from w1thermsensor import W1ThermSensor, Sensor
sensor = W1ThermSensor(Sensor.DS18B20, "3c01b55615b0")
sensor.set_resolution(9)
temperature_in_celsius = sensor.get_temperature()

print(temperature_in_celsius)

What am I missing?
Thank you!

ds18b20 vs w1thermsensor

Hi,
sorry I'm only a Dummy.
But it seems to me, that the given examples do not work, because it is only possible to import the W1ThermSensor Class.
Sorry, if I wrong.
Gruss, wowonk

Proper error handling

I'm using the w1thermsensor module in a program to debug the hardware of my 9 sensor temperature logger which has recently started to behave erratically. I'm currently using the following code as a starting point in debugging the hardware:

class TemperatureSensor:

   def __init__(self, id = "", name = "", calibration = 0, connected = 1):
        self.id = id
        self.name = name
        self.calibration = calibration
        self.connected = connected

sensors = [] # create an empty sensor list

# populate the sensor list with known sensors
sensors.append(TemperatureSensor("000005e4d76b", "radiator aanvoer", 0.0, 0))
sensors.append(TemperatureSensor("000005e4f2fd", "radiator retour", 0.0, 0))
sensors.append(TemperatureSensor("000005e5f606", "CV retour", 0.0, 1))
sensors.append(TemperatureSensor("000005e77695", "tapwater", 0.0, 1))
sensors.append(TemperatureSensor("000005fab05d", "CV ruimte", 0.0, 1))
sensors.append(TemperatureSensor("000005fab2e0", "vloer aanvoer", 0.0, 1))
sensors.append(TemperatureSensor("000005fab89c", "vloer retour", 0.0, 1))
sensors.append(TemperatureSensor("000005fb03d6", "CV aanvoer", 0.0, 1))
sensors.append(TemperatureSensor("0000061be3e2", "buitentemperatuur", 0.0, 1))

degree = u'\N{DEGREE SIGN}'
degreeCelsius = u'{0}'.format(degree).encode('ISO-8859-1') + "C"

for i in range (1, len(sensors)):
    if sensors[i].connected:
        sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensors[i].id)
        temperature = sensor.get_temperature()
        print '{:17s} {:5.1f} {:2s}'.format(sensors[i].name, temperature + sensors[i].calibration, degreeCelsius)

Occasionally, when one of the sensors is acting up, the program terminates with:

CV retour          21.7C
tapwater           24.4C
Traceback (most recent call last):
  File "t5.py", line 29, in <module>
    sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensors[i].id)
  File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/__init__.py", line 86, in __init__
    self._sensorpath = self.sensorpath
  File "/usr/local/lib/python2.7/dist-packages/w1thermsensor/__init__.py", line 123, in sensorpath
    raise NoSensorFoundError(self._type, self._id)
w1thermsensor.NoSensorFoundError: No DS18B20 temperature sensor with id '000005fab05d' found

I would like to embed this code in a larger program that will repeatedly read the sensors. The problem is that I haven't been able to figure out how to properly catch the errors, which I would like to write to an error log. This is probably trivial if you are an experienced Python developer but I haven't been able to figure it out.

Can you give me an example I can build on? Any help is welcome.

w1thermsensor get -p 12 needs to be root

/bin/sh: 1: cannot create /sys/bus/w1/devices/28-0316b56fb3ff/w1_slave: Permission denied
Traceback (most recent call last):
File "/usr/bin/w1thermsensor", line 9, in
load_entry_point('w1thermsensor==1.0.3', 'console_scripts', 'w1thermsensor')()
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 722, in call
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3/dist-packages/w1thermsensor/cli.py", line 145, in get
sensor.set_precision(precision, persist=False)
File "/usr/lib/python3/dist-packages/w1thermsensor/core.py", line 280, in set_precision
raise W1ThermSensorError("Failed to change resolution to {0} bit".format(precision))
w1thermsensor.errors.W1ThermSensorError: Failed to change resolution to 12 bit

Loading library on boot

Hi,

I wanted to see if you have come across a problem when you start a python program that uses DS18B20 on boot.

I have a crontab that is set to on reboot to start my python program.

The problem is when it init the library it fails. But if I run it manually with sudo at the command line it works fine.

it fails on sensor=DS18B20()

I can't see the error when it runs from cron so I have no idea what is happening.

Any ideas?

Thanks.

Edit:
Sometimes I get this
File "/home/pi/piminer/ds18b20/init.py", line 87, in _get_sensor
return path.join(DS18B20.BASE_DIRECTORY, DS18B20.SLAVE_PREFIX + self._id, DS18B20.SLAVE_FILE)
TypeError: cannot concatenate 'str' and 'NoneType' objects

Unable to locate package python3-w1thermsensor

Hey,

I've used this package before and really loved how easy it was to use.
I am having issues downloading the package this time. When I try to install it on Rasbian using
sudo apt-get install python3-w1thermsensor
I get the error: "unable to locate package python3-w1thermsensor"
I am using a raspberry pi with rasbian.
Any chance you can help me out?

Changing resolution DS18B20 doesn't change speed

Hi,

For a master's project I need to read two DS18B20 sensors for 30 seconds as much as possible. The 12 bit resolution takes ~750ms, so with two sensors it takes 1.5 sec for a measurement. To be quicker I changed the resolution to 11 bit ($ sudo w1thermsensor resolution --hwid 0114556f64aa --type DS18B20 11).

The accuracy of the sensor went down, but the speed of the readings doesn't improve. I can see on the specifications of the DS18B20 that the speed of a 11 bit reading should be ~375 ms instead of ~750 ms.

Why doesn't the sensor speed go down? Do you have a tip to get the sensor readings quicker?
I am using w1thermsensor 0.3.2 and to get a reading I just try 'sudo w1thermsensor all' in the terminal.

Thanks in advance

Citation

I used your library in my dissertation, can you confirm my citation?

T. Furrer, “w1thermsensor” , 2019. [Online]. Available: https://github.com/timofurrer/w1thermsensor. [Accessed: 24-Jul-2019].

Since there are several contributors without name or contact info, if you'd like me to reference them all, could you provide some information on them, please?

How to return name of sensor?

Is there a better way to get the sensor name?

I'm not very well versed in Python, I'm able to put together examples to build scripts to do what I want but that's about it...

I'm using the w1thermsensor library to publish all DS sensors on the 1wire bus to Home Assistant and would also like to include the sensor type in the discovery config, I currently do this by taking some of you code, namely the sensor definitions to convert the sensor type to a name, surely theres a better way but I don't know how I would do it with your library, could you point me in the right direction?

THERM_SENSOR_DS18S20 = 0x10
THERM_SENSOR_DS1822 = 0x22
THERM_SENSOR_DS18B20 = 0x28
THERM_SENSOR_DS1825 = 0x3B
THERM_SENSOR_DS28EA00 = 0x42
THERM_SENSOR_MAX31850K = 0x3B
TYPE_NAMES = {
    THERM_SENSOR_DS18S20: "DS18S20",
    THERM_SENSOR_DS1822: "DS1822",
    THERM_SENSOR_DS18B20: "DS18B20",
    THERM_SENSOR_DS1825: "DS1825",
    THERM_SENSOR_DS28EA00: "DS28EA00",
    THERM_SENSOR_MAX31850K: "MAX31850K",
}

while True:
    for sensor in W1ThermSensor.get_available_sensors():
        sensor_type_name = TYPE_NAMES.get(sensor.type, hex(sensor.type))
        temperature = sensor.get_temperature()
        sensor_id = sensor.id
        print("%s %s %.2f" % (sensor_type_name, sensor_id, temperature))

Interference with RPi.GPIO/RPi.PWM

Timo,

Thanks for the excellent library!

I'm trying to use this with the RPi.PWM library, but it appears that I run into problems if I run RPi.GPIO and w1thermsensor in separate processes. However, if I roll these into a common module, there appears to be no issue. Have you observed this behavior, and if so, thoughts on its cause?

Thanks!
Jim

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.