Wednesday, December 11, 2013

Java Program to Read 1-Wire Temperature Data on a Beaglebone Black

This Java example shows how to read the current temperature from one or more DS18B20 temperature sensors.  If you need to install Java 7 on a Beaglebone Black, see this post.  

To configure the BB Black's pins for 1-wire support, see this post at Hipstercircuits.  This configuration is necessary before continuing.


Connections


Looking at the flat side of the DS18B20's plastic head, connect the left pin to ground on the Beaglebone Black (P9-1), the right pin to 3V3 (P9-3), and the center pin to P9-22.  A 4.7k Ohm pull-up resistor is required on the connection of the first sensor's center pin to P9-22.  If using multiple sensors, each needs to be connected to the voltage and ground; parasitic power mode does not seem to be supported.  The center (data) pins need to be connected together (with the pull-up on the connection to the BB Black)

Java Code


The following Java code finds the connected DS18B20s and prints each sensor's temperature data to the console.

import java.io.*;
import java.util.*;

public class w1 {
  // This directory created by 1-wire kernel modules
  static String w1DirPath = "/sys/bus/w1/devices";

  public static void main(String[] argv) throws Exception {
    File dir = new File(w1DirPath);
    File[] files = dir.listFiles(new DirectoryFileFilter());
    if (files != null) {
      for(File file: files) {
        System.out.print(file.getName() + ": ");
// Device data in w1_slave file
String filePath = w1DirPath + "/" + file.getName() + "/w1_slave";
File f = new File(filePath);
try(BufferedReader br = new BufferedReader(new FileReader(f))) {
          String output;
  while((output = br.readLine()) != null) {
    int idx = output.indexOf("t=");
    if(idx > -1) {
      // Temp data (x1000) in 5 chars after t=
      float tempC = Float.parseFloat(
          output.substring(output.indexOf("t=") + 2));
      // Divide by 1000 to get degrees Celsius
      tempC /= 1000;
      System.out.println(tempC);
    }
          }
}
catch(Exception ex) {
  System.out.println(ex.getMessage());
                   }
      }
    }
  } 
}

// This FileFilter selects subdirs with name beginning with 28-
// Kernel module gives each 1-wire temp sensor name starting 
// with 28-
class DirectoryFileFilter implements FileFilter
{
  public boolean accept(File file) {
    String dirName = file.getName();
    String startOfName = dirName.substring(0, 3);
    return (file.isDirectory() && startOfName.equals("28-"));
  }
}


No comments:

Post a Comment