RPi and Java Embedded GPIO: Sensor Reading using Java Code
- by hinkmond
And, now to program the Java code for reading the fancy-schmancy static electricity sensor connected to your Raspberry Pi, here is the source code we'll use:
First, we need to initialize ourselves...
/*
* Java Embedded Raspberry Pi GPIO Input app
*/
package jerpigpioinput;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
*
* @author hinkmond
*/
public class JerpiGPIOInput {
static final String GPIO_IN = "in";
// Add which GPIO ports to read here
static String[] GpioChannels =
{ "7" };
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
/*** Init GPIO port(s) for input ***/
// Open file handles to GPIO port unexport and export controls
FileWriter unexportFile =
new FileWriter("/sys/class/gpio/unexport");
FileWriter exportFile =
new FileWriter("/sys/class/gpio/export");
for (String gpioChannel : GpioChannels) {
System.out.println(gpioChannel);
// Reset the port
unexportFile.write(gpioChannel);
unexportFile.flush();
// Set the port for use
exportFile.write(gpioChannel);
exportFile.flush();
// Open file handle to input/output direction control of port
FileWriter directionFile =
new FileWriter("/sys/class/gpio/gpio" + gpioChannel +
"/direction");
// Set port for input
directionFile.write(GPIO_IN);
directionFile.flush();
}
And, next we will open up a RandomAccessFile pointer to the GPIO port.
/*** Read data from each GPIO port ***/
RandomAccessFile[] raf = new RandomAccessFile[GpioChannels.length];
int sleepPeriod = 10;
final int MAXBUF = 256;
byte[] inBytes = new byte[MAXBUF];
String inLine;
int zeroCounter = 0;
// Get current timestamp with Calendar()
Calendar cal;
DateFormat dateFormat =
new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
String dateStr;
// Open RandomAccessFile handle to each GPIO port
for (int channum=0; channum
Then, loop forever to read in the values to the console.
// Loop forever
while (true) {
// Get current timestamp for latest event
cal = Calendar.getInstance();
dateStr = dateFormat.format(cal.getTime());
// Use RandomAccessFile handle to read in GPIO port value
for (int channum=0; channum
Rinse, lather, and repeat...
Compile this Java code on your host PC or Mac with javac from the JDK. Copy over the JAR or class file to your Raspberry Pi, "sudo -i" to become root, then start up this Java app in a shell on your RPi.
That's it! You should see a "1" value get logged each time you bring a statically charged item (like a balloon you rub on the cat) near the antenna of the sensor. There you go. You've just seen how Java Embedded technology on the Raspberry Pi is an easy way to access sensors.
Hinkmond