This exercise show how to read Pi's system temperature in Java,
using ProcessBuilder with command of "
vcgencmd measure_temp".
|
Read Raspberry Pi system temperature in Java |
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;
/**
* @web helloraspberrypi.blogspot.com
*/
public class readTemp {
public static void main(String[] args) {
// Example to run "dir" in Windows
String[] command = {"vcgencmd", "measure_temp"};
StringBuilder cmdReturn = new StringBuilder();
try {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
try (InputStream inputStream = process.getInputStream()) {
int c;
while ((c = inputStream.read()) != -1) {
cmdReturn.append((char) c);
}
}
System.out.println(cmdReturn.toString());
String stringTemp = measure_temp_toString(cmdReturn.toString());
System.out.println("Get the numerical part as String: " + stringTemp);
System.out.println("converte to float: " + cnvStringToFloat(stringTemp));
} catch (IOException ex) {
System.out.println(ex.toString());
}
}
private static String measure_temp_toString(String src){
return src.replaceAll("[^0123456789.]", "");
}
private static float cnvStringToFloat(String src){
float result = (float)0.0;
Scanner scanner = new Scanner(src);
while(scanner.hasNext()){
if(scanner.hasNextFloat()){
result = scanner.nextFloat();
}else{
scanner.next(); //ignore
}
}
return result;
}
}
No comments:
Post a Comment