I\'m trying to read temperature data from a DHT11 temperature sensor, using pi4j. I followed the code written in c and python in this site: http://www.uugear.com/portfolio/dht11
I've the same issue and, unfortunately, I've read that Java cannot read data from DHT11/22 in this way for timing problems.
I've found in the Raspberry Forum a thread where you can find some solutions using SPI or pigpio. Another full Java possible solution is there.
I've received my sensor yesterday and I have not already tried this solutions. When I'll try, I'll let you know.
[EDIT]
Hi, I've solved the problem calling a python script (which uses the Adafruit Driver) and reading it's output. The python script is simply the example published in the Adafruit's library. I've only changed the output at line 48 in
print '{0:0.1f} {1:0.1f}'.format(temperature, humidity)
The Java method that updates the values with new values is:
public void update() {
String cmd = "sudo python DHTReader.py 11 4";
try {
String ret = "";
try {
String line;
Process p = Runtime.getRuntime().exec(cmd.split(" "));
p.waitFor();
BufferedReader input = new BufferedReader
(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
output += (line + '\n');
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
ret.trim();
if (ret.length() == 0) // Library is not present
throw new RuntimeException(LIB_NOT_PRESENT_MESSAGE);
else{
// Error reading the the sensor, maybe is not connected.
if(ret.contains(ERROR_READING)){
String msg = String.format(ERROR_READING_MSG,toString());
throw new Exception(msg);
}
else{
// Read completed. Parse and update the values
String[] vals = ret.split(" ");
float t = Float.parseFloat(vals[0].trim());
float h = Float.parseFloat(vals[1].trim());
if( (t != lastTemp) || (h != lastHum) ){
lastUpdate = new Date();
lastTemp = t;
lastHum = h;
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
if( e instanceof RuntimeException)
System.exit(-1);
}
}
To make it work you have to install the Adafruit library as described in the linked page and change DHTReader.py with the path of the scipt. I'm working to build a "library". If you need, when I've finished, I'll publish it on GitHub.