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?

  • Why don't you just poll the /sys/bus/device/... node? Do you need to check the temperature 100000 times a second?
    – goldilocks
    Dec 29, 2015 at 19:26
  • Would you care to elaborate @goldilocks what connection does a 100KHz sample rate got to do with Pi4J which seems to be a java I/O library the for Raspberry Pi and a device presented in the sysfs file-system area by the kernel?
    – SlySven
    Dec 29, 2015 at 20:39
  • 1
    here is an excellent java example github.com/marcandreuf/sunfounder-sensors-raspi-4j/blob/master/… Apr 21, 2016 at 20:00

2 Answers 2


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) {

Maven Dependencies:


    <!-- used for the TemperatureSensor interface -->

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]

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


  • I know how to read file. I just thought that there is some function which gets sensor id and returns temperature. That's all. Dec 30, 2015 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.