3

I want to read temperature from DS18B20 sensors. Sensors are connected and works fine. How can I read temperature using Pi4J? Is there API for this?

mariusz2108
  • 195
  • 2
  • 10

2 Answers2

3

Pi4J has released a 1-Wire API in version 1.1. It's no longer a SNAPSHOT version.

W1Master master = new W1Master();
List<W1Device> w1Devices = master.getDevices(TmpDS18B20DeviceType.FAMILY_CODE);
for (W1Device device : w1Devices) {
    //this line is enought if you want to read the temperature
    System.out.println("Temperature: " + ((TemperatureSensor) device).getTemperature());
    //returns the temperature as double rounded to one decimal place after the point

    try {
        System.out.println("1-Wire ID: " + device.getId() +  " value: " + device.getValue());
        //returns the ID of the Sensor and the  full text of the virtual file
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Maven Dependencies:

<dependencies>
    <dependency>
        <groupId>com.pi4j</groupId>
        <artifactId>pi4j-core</artifactId>
        <version>1.1</version>
        <exclusions>
            <exclusion>
                <groupId>com.pi4j</groupId>
                <artifactId>pi4j-native</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- used for the TemperatureSensor interface -->
    <dependency>
        <groupId>com.pi4j</groupId>
        <artifactId>pi4j-device</artifactId>
        <version>1.1</version>
    </dependency>
</dependencies>
Simulant
  • 651
  • 1
  • 9
  • 22
1

The API is open the file /sys/bus/w1/devices/28-00*/w1_slave, read the file, close the file, and then parse the results. Do that as often as needed but any faster than once every four seconds is pretty pointless.

Here is some Python code you can adapt.

#!/usr/bin/env python

import glob
import time

# Typical reading
# 73 01 4b 46 7f ff 0d 10 41 : crc=41 YES
# 73 01 4b 46 7f ff 0d 10 41 t=23187

while True:

   for sensor in glob.glob("/sys/bus/w1/devices/28-00*/w1_slave"):
      id = sensor.split("/")[5]

      try:
         f = open(sensor, "r")
         data = f.read()
         f.close()
         if "YES" in data:
            (discard, sep, reading) = data.partition(' t=')
            t = float(reading) / 1000.0
            print("{} {:.1f}".format(id, t))
         else:
            print("999.9")

      except:
         pass

   time.sleep(3.0)
joan
  • 71,852
  • 5
  • 76
  • 108