So, you've followed the previous steps to install Java Embedded on your Raspberry Pi ?, you went to Fry's and picked up some jumper wires, LEDs, and resistors ?, you hooked up the wires, LED, and resistor the the correct pins ?, and now you want to start programming in Java on your RPi? Yes? ???????!
OK, then... Here we go.
You can use the following source code to blink your first LED on your RPi using Java. In the code you can see that I'm not using any complicated gpio libraries like wiringpi or pi4j, and I'm not doing any low-level pin manipulation like you can in C. And, I'm not using python (hell no!). This is Java programming, so we keep it simple (and more readable) than those other programming languages.
See:
Write Java code to do this
In the Java code, I'm opening up the RPi Debian Wheezy well-defined file handles to control the GPIO ports. First I'm resetting everything using the unexport/export file handles. (On the RPi, if you open the well-defined file handles and write certain ASCII text to them, you can drive your GPIO to perform certain operations. See this GPIO reference). Next, I write a "1" then "0" to the value file handle of the GPIO0 port (see the previous pinout diagram). That makes the LED blink. Then, I loop to infinity. Easy, huh?
import java.io.*
/*
* Java Embedded Raspberry Pi GPIO app
*/
package jerpigpio;
import java.io.FileWriter;
/**
*
* @author hinkmond
*/
public class JerpiGPIO {
static final String GPIO_OUT = "out";
static final String GPIO_ON = "1";
static final String GPIO_OFF = "0";
static final String GPIO_CH00="0";
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
FileWriter commandFile;
try {
/*** Init GPIO port for output ***/
// 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");
// Reset the port
unexportFile.write(GPIO_CH00);
unexportFile.flush();
// Set the port for use
exportFile.write(GPIO_CH00);
exportFile.flush();
// Open file handle to port input/output control
FileWriter directionFile =
new FileWriter("/sys/class/gpio/gpio"+GPIO_CH00+"/direction");
// Set port for output
directionFile.write(GPIO_OUT);
directionFile.flush();
/*--- Send commands to GPIO port ---*/
// Opne file handle to issue commands to GPIO port
commandFile = new FileWriter("/sys/class/gpio/gpio"+GPIO_CH00+"/value");
// Loop forever
while (true) {
// Set GPIO port ON
commandFile.write(GPIO_ON);
commandFile.flush();
// Wait for a while
java.lang.Thread.sleep(200);
// Set GPIO port OFF
commandFile.write(GPIO_OFF);
commandFile.flush();
// Wait for a while
java.lang.Thread.sleep(200);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Hinkmond