RPi and Java Embedded GPIO: Java code to blink more LEDs
- by hinkmond
Now, it's time to blink the other GPIO ports with the other LEDs connected to them. This is easy using Java Embedded, since the Java programming language is powerful and flexible. Embedded developers are not used to this, since the C programming language is more popular but less easy to develop in.
We just need to use a dynamic Java String array to map to the pinouts of the GPIO port names from the previous diagram posted. This way we can address each "channel" with an index into that String array.
static String[] GpioChannels =
{ "0", "1", "4", "17", "21", "22", "10", "9" };
With this new dynamic array, we can streamline the main() of this Java program to activate all the ports.
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
FileWriter[] commandChannels;
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");
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 port input/output control
FileWriter directionFile =
new FileWriter("/sys/class/gpio/gpio" + gpioChannel +
"/direction");
// Set port for output
directionFile.write(GPIO_OUT);
directionFile.flush();
}
And, then simply add array code to where we blink the LED to make it blink all the LEDS on and off at once.
/*** Send commands to GPIO port ***/
commandChannels = new FileWriter[GpioChannels.length];
for (int channum=0; channum
It's easier than falling off a log... or at least easier than C programming.
Hinkmond