Code Examples


This is how I got Java working, I have designed my own board which you see here or on ebay.  All of the code is very rough and ready,  I have not written Java in years but I stil prefer it to c/C++.  Note these examples assume use of c mmap examples from Gertboard or wiringpi examples on the wiki.  There may be are other simpler ways

1) First step was to find c code to do the low level memory access.  I looked at Gertboard examples but struggled to hack the code reliably ( my fault I am sure) so I then used the wiringPi example  which I found easier to use.  Try here I think  – .

2) In order to use the c code through JNI you should use a process of first creating  methods in Java,  you then use a tool called javah to create a *.h ‘c’ header file ,  then you write ‘c’ code to implement.  As the c code already existed I had to slightly reverse this process,  so for example the wiring pi function called

int wiringPiSetup (void)

gets called

// native methods

public native int wiringPiSetup();

in Java.

3) You then use javah ( part of the full sdk) which produces output *.h file with function of the form :-

* Class: JNIWiringPi
* Method: wiringPiSetup
* Signature: ()I
JNIEXPORT jint JNICALL Java_JNIWiringPi_wiringPiSetup
(JNIEnv *, jobject);

4) and then have to implement these in c  e.g

JNIEXPORT jint JNICALL Java_JNIWiringPi_wiringPiSetup
(JNIEnv *env, jobject obj)

// int wiringPiSetup (void)
int fd ;
uint8_t *gpioMem, *pwmMem, *clkMem ;

blah blah…

5) You compile the c code using the Raspi c compiler and link it to create a library file,  these are examples of the command’s I used ( my modifies c file was called JNIWiringPi.c.

gcc -fPIC -g  -c -Wall  -I /usr/lib/jvm/java-1.6.0-openjdk/include -I /usr/lib/jvm/java-1.6.0-openjdk/include/linux JNIWiringPi.c

then to create lib

gcc  -shared -Wl,-soname, -o JNIWiringPi.o

then you have to copy it to lib directory

sudo cp /usr/lib

then I understand you have to run ldconfig ( need to find a linux expert to confirm this) ,  now check files/links are correct

pi@raspberrypi:/usr/lib$ ls -al | grep JNI
lrwxrwxrwx 1 root root 23 May 30 18:58 ->
-rwxr-xr-x 1 root root 39128 Jun 14 13:52

now you shoudl be ready to install your java class/jar file and run it using sudo off course.

If you want code sources i am at

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s