Skip to content

JVM related (Java, Groovy, Scala, Kotlin, etc) samples for the Raspberry PI, relying on PI4J. IoT and friends.

Notifications You must be signed in to change notification settings

Scrappers-glitch/raspberry-coffee

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Raspberry Coffee Raspberry Coffee

Java code and wiring for the Raspberry Pi, featuring reusable libraries and snippets

It uses the PI4J library, itself relying on WiringPi.

$ curl -s get.pi4j.com | sudo bash

Get started, from scratch, now!

bash -c "$(curl -L https://raw.githubusercontent.com/OlivierLD/raspberry-coffee/master/install.sh)"

This project contains Java code, mostly translated from Python, dedicated to usually one board (like BMP180, LSM303, etc). More consistent samples can be found in the RasPISamples module (being moved to the Project.Trunk module), where several components have been assembled together. Do take a look, it also comes with a readme file.


Raspberry Pi's Mechanical drawings



Summary

Setup a brand-new Raspberry Pi

To get started as quickly as possible, and not only for this project, from scratch.

Foundation Software

The goal here is to get ready with the minimal configuration you will be able to use to clone a git repository and start working on it.

Typically, you will need to have the minimal git tools and the right compilers. The code contained in the repo(s) will be responsible for downloading the right dependencies at build time (gradle is definitely good at that).

Minimal setup
  • Install Raspbian (not NOOBS) as explained at https://www.raspberrypi.org/learning/software-guide/quickstart/, and burn your SD card

    • Depending on the OS you burn the SD card from, the procedure varies. Well documented in the link above.
  • Boot on the Raspberry with the new SD card, USB keyboard and HDMI screen attached to it (if this is an old RPi, use a USB WiFi dongle too)

    • It should boot to the Graphical Desktop.
  • Connect to your local network

  • Use RPi-Config (from the Desktop GUI, Menu > Preferences > Raspberry Pi Configuration) to:

    • enable needed interfaces (ssh, serial, spi, i2c, VNC, etc)
      • ssh and VNC will allow remote access to your Raspberry Pi, the others depend on the projects you want to work on.
      • This can be modified or reverted at any time.
    • setup config (keyboard, locale, etc)
    • change pswd, hostname
      • for the hostname, you might need to go a Terminal, reach sudo raspi-config, and use Network > Hostname.
  • Reboot (and now, you can use ssh if it has been enabled above) and reconnect

  • From a terminal, run the following commands:

$ sudo apt-get update
$ sudo apt-get install vim
  • setup your .bashrc as needed, adding for example lines like
alias ll="ls -lisah"
  • recent Raspbian releases come with a development environment that includes
    • JRE & JDK
    • git
    • python
    • C Compiler (gcc, g++)
#  Optional: sudo apt-get install -y curl git build-essential default-jdk
#  Optional too, to install nodejs and npm:
$ sudo su -
root# curl -sL https://deb.nodesource.com/setup_9.x | bash -
root# exit
$ sudo apt-get install -y nodejs
  • make sure what you might need is installed, by typing:
$ java -version
$ javac -version
$ git --version
$ python --version
$ python3 --version
$ gcc -v
$ node -v
$ npm -v
  • some utilities, to make sure they are present, type:
$ which scp
$ which curl
$ which wget
  • You can use VNC (if enabled in the config above)

    • Run vncserver from a terminal, and use VNC Viewer from another machine to connect.
  • You may also remove unwanted software, just in case you don't need them:

    • $ sudo apt-get purge wolfram-engine
    • $ sudo apt-get purge minecraft-pi
    • $ sudo apt-get purge sonic-pi
    • $ sudo apt-get purge libreoffice*
    • $ sudo apt-get clean
    • $ sudo apt-get autoremove
  • If you need AI and Deep Learning (Anaconda, Jupyter notebooks, TensorFlow, Keras), follow this link.

    • or type:
    $ wget https://repo.anaconda.com/archive/Anaconda3-5.3.0-Linux-x86_64.sh
    
    • Anaconda on Raspberry Pi
    • Jupyter Notebooks on Raspberry Pi
      • Start Jupyter Notebooks by typing jupyter notebook [--allow-root] --ip 0.0.0.0 --no-browser
      • Then the command to use to reach Jupyter would show up in the console.
    • Note: Training a Neural Network is a very demanding operation, that requires computing resources not granted on a Raspberry Pi. Installing Keras on a Raspberry Pi might not be relevant. OpenCV, though, would be an option to consider. Google it ;).

Extra softs

  • Docker
 $  curl -sSL https://get.docker.com | sh
  • Go
 $ wget https://dl.google.com/go/go1.9.2.linux-armv6l.tar.gz
 $ sudo tar -C /usr/local -xzf go1.9.2.linux-armv6l.tar.gz
 $ export PATH=$PATH:/usr/local/go/bin
 $ go version
 go version go1.9.2 linux/arm
  • dep - Package manager for Go
 $ go get -u github.com/golang/dep/cmd/dep
 $ sudo cp ~/go/bin/dep /usr/local/bin/
 $ dep version
 dep:
  version : devel
  build date :
  git hash :
   go version : go1.9.2
  go compiler : gc
  platform : linux/arm
  • Fing CLI, nice to have.
    • Make sure you use the Fing CLI for your system, dpkg --print-architecture will tell you what to choose.
Connect to the Raspberry Pi from your laptop, using a USB cable

It's easy, and convenient. See here, or here.

To connect to a Raspberry Pi Zero, all you need is a USB cable A-to-microB.

Some other devices can be nice to have:

Once your RPi is connected through a USB connection, after configuring it as explained, you can use ssh as follow:

$ ssh pi@raspberrypi.local

where raspberrypi is the hostname of the Raspberry. No wireless connection or IP address is required.

Raspberry Pi as an Access Point and Internet access.

Your Raspberry Pi can be turned into an Access Point, this means that it generates its own network, so you can connect to it from other devices (other Raspberry Pis, laptops, tablets, smart-phones, ESP8266, etc). It can be appropriate when there is no network in the area you are in, for example when sailing in the middle of the ocean, kayaking in a remote place, hiking in the boonies, etc.

Setting up the Raspberry Pi to be an access point is well documented on the Adafruit website. This one is also useful.

And this too.

As we said above, to enable hostapd to have your Raspberry Pi acting as a WiFi hotspot, you can follow those good instructions from the Adafruit website.

Warning: Since Raspbian's Stretch release, a lot of things have changed for the network config. See here.

>>> Skip to the next section if you run Stretch or later (as I am). Consider the Ethernet option ;)

The thing is that when the Raspberry Pi becomes a WiFi hotspot, you cannot use it to access the Internet, cannot use apt-get install, cannot use git pull origin master, etc, that can rapidly become quite frustrating.

Now, for development purpose, you may very well need to have an Access Point and an Internet access (i.e. access to your local or wide area network).

For that, you need 2 WiFi adapters (yes, you could also use an Ethernet connection, which is a no brainer, we talk about WiFi here). Recent Raspberry Pis are WiFi-enabled, you just need a WiFi dongle, that would fit on a USB port. On older Raspberry Pis (not WiFi-enabled), you need 2 USB dongles.

The Raspberry Pi 3 and the Zero W already have one embedded WiFi port, I just added another one, the small USB WiFi dongle I used to use on the other Raspberry Pis. This one becomes named wlan1. All I had to do was to modify /etc/network/interfaces:

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet static
  address 192.168.42.1
  netmask 255.255.255.0

#iface wlan0 inet manual
#    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet dhcp
wpa-ssid "ATT856"
wpa-psk "<your network passphrase>"

See the 4 lines at the bottom of the file, that's it!

Note: above, 192.168.42.1 will be the address of your hotspot, aka gateway. Feel free to change it to anything else, like 192.168.127.1... If that was the case, you also need to make sure that the entry you've added in /etc/dhcp/dhcpd.conf matches this address range:

subnet 192.168.127.0 netmask 255.255.255.0 {
  range 192.168.127.10 192.168.127.50;
  option broadcast-address 192.168.127.255;
  option routers 192.168.127.1;
  default-lease-time: 600;
  max-lease-time: 7200;
  option domain-name "local-pi";
  option domain-name-servers 8.8.8.8 8.8.4.4;
}

The lines to pay attention to are the ones with a 127 in it...

Note: you might also want to modify the file /etc/dhcpcd.conf, add the following lines:


interface wlan0
static ip_address=192.168.127.1/24
# static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.127.1
static domain_name_servers=192.168.127.1

Now, when the wlan1 is plugged in, this Raspberry Pi is a WiFi hotspot, and has Internet access.

This means that when you are on a Raspberry Pi with two WiFi adapters (the Raspberry Pi 3 with an extra dongle, where you do you developments from for example), you have two WiFi interfaces, wlan0 and wlan1.

When the same SD card runs on a Raspberry Pi with only one WiFi adapter (the Raspberry Pi Zero W you use to do some logging, when kayaking in the boonies for example), you have only one WiFi interface wlan0, and the Raspberry Pi is a hotspot generating its own network, as defined by you in /etc/hostapd/hostapd.conf.

Note: In some cases, I was not able to have hostapd to start at boot time... It was working fine from the command line though. I've cheated by putting an hostapd /etc/hostapd/hostapd.conf & in /etc/rc.local. It's not elegant, but it works.

Now you're ready to rock!

Bonus: Mount a USB drive on the Raspberry Pi

Java Virtual Machine (JVM)

Note: Java code is compiled into class files, that run on a Java Virtual Machine (JVM). Java is not the only language that runs a JVM, this project also contains some small samples of other JVM-aware languages, invoking and using the features of this project.

Those samples include Scala, Groovy, Kotlin..., and the list is not closed!

See in the OthetJVM.languages directory, there is more about that.


How to build and run

Note: This project uses gradle and git. Gradle will be installed automatically if it is not present on your system, it uses the gradle wrapper (gradlew).

To have a first idea of the structure of the project, use

 $ ./gradlew projects [--info]

Sub-projects may have dependencies.

 $ cd Project-Trunk/REST-clients/REST-assembler
 $ ../../../gradlew dependencies [--info]

Git is usually installed on Linux and Mac, but not on all versions of Windows. On Windows, you need to install the git bash shell, and run in it the commands mentioned in this document. Recent versions of Windows (like Windows 10) seem to come with a git command available in a Terminal. But this forward-slash/back-slash story remains in your way, I have not tested it.


To build it, clone this project (this repo), make sure the script named gradlew is executable, and execute gradlew.

Note: If you wish to access serial ports, a good library (beside PI4J) is librxtx:

sudo apt-get install librxtx-java
 Prompt> git clone https://github.com/OlivierLD/raspberry-coffee.git
 Prompt> cd raspberry-coffee
 Prompt> chmod +x gradlew
 Prompt> ./gradlew [--daemon | --no-daemon] build [--info]

Note: On small-memory boards, use --no-daemon, like in:

./gradlew --no-daemon clean build --info

If you see a message like VM is only supported on ARMv7+ VFP, you probably need to downgrade your JDK (and JRE) from 11 to 8.

You are expecting an end like that one:


BUILD SUCCESSFUL in 55s
97 actionable tasks: 17 executed, 80 up-to-date
Prompt>

See the gradle web-site for info about Gradle.

We will also be using the shadowJar gradle plugin is several projects. This plugin is aggregating the required classes and all their dependencies into a single archive, called a fat Jar. This simplifies the syntax of the classpath.

Typically, this operation will be run like this:

 Prompt> cd RESTNavServer
 Prompt> ../gradlew build --info
 Prompt> ../gradlew clean shadowJar [--info]

The expected archive will be produced in the local build/libs directory.

Important : If JAVA_HOME is not set at the system level, you can set it in set.gradle.env and execute it before running gradlew:

 Prompt> ../set.gradle.env

Note: If you are behind a firewall, you need a proxy. Mention it in all the files named gradle.propetries, and in all the build.gradle scripts, uncomment the following two lines:

// ant.setproxy(proxyhost: "$proxyHost", proxyport: "$proxyPort") //, proxyuser="user", proxypassword="password")
// compileJava.dependsOn(tellMeProxy)

Or you can also set it at runtime:

 Prompt> ../gradlew clean shadowJar -Dhttp.proxyHost=www-proxy.domain.com -Dhttp.proxyPost=80 -Dhttps.proxyHost=www-proxy.domain.com -Dhttps.proxyPost=80

Developing on the Raspberry Pi, or Developing for the Raspberry Pi ?

To write code, the simplest editor is enough. I have used vi for ages, mostly because this was the only one available, but also because it is indeed good enough. vi (and vim) is (are) available on the Raspberry Pi, nano too, graphical editors like gedit, geany are even easier to use, on a grahical desktop.

All the code provided here can be built from Gradle (all gradle scripts are provided), on the Raspberry Pi itself. The Raspberry Pi is self-sufficient, if this is all you have, nothing is preventing you from accessing all the features presented here.

But let us be honest, Integrated Development Environments (IDE) are quite cool. In my opinion, IntelliJ leads the pack, and Eclipse, JDeveloper, NetBeans follow. Cloud9 provides amazing features, on line. Smaller ones like GreenFoot, BlueJ are also options to consider.

Those two last ones might be able to run on a Raspberry Pi, but forget about the others..., they use way too much RAM. The features they provide definitely increase productivity, and when you use them, you learn as you code. Code-insight, auto-completion and similar features are here to help. And I'm not even talking about the remote debugging features they provide as well.

So, as the Raspberry Pi is not the only machine on my desk, I develop on a laptop using IntelliJ (with several GigaBytes of RAM, like 8, 16, ...), and I use scp to transfer the code to (and possibly from) the Raspberry Pi. Worst case scenario, I do a git push from the development machine, and a git pull from the Raspberry Pi. I found it actually faster and more efficient than developing directly on the Raspberry Pi.

Something to keep in mind

The Java Virtual Machine (JVM) implements the Java Platform Debugging Architecture (JPDA). This allows remote debugging. In other words, you run the code on the Raspberry Pi, but you debug it (set breakpoints, introspect variable values, etc) on another machine (the one where the IDE runs). This is specially useful when the code interacts with sensors and other devices that are not supported from the laptop. This will make your life considerably easier than if you used another language missing it (like Python, C, and many others). It uses TCP between the debugger and the debuggee.


Raspberry Pi, a possible thing of the Internet of Things...

  • The Raspberry Pi is a fully featured Linux computer, which can - as such - connect to the Internet.
  • The Raspberry Pi has a General Purpose Input Output (GPIO) interface that allows it to drive all kind of electronic components, from a simple LED to a complex robot, and including all kind of sensors (GPS, light resistors, pressure sensors, temperature sensors, all kinds!). None of the above is new. Connecting to the Internet does not impress anyone anymore. Driving a robot, modern kitchens are full of robots, cars are loaded with electronic components... But what if we put those two together, with the Raspberry Pi sitting in between. Then, we can drive a robot over the Internet. And this is not that usual (yet).

The snippets provided in this project are here to help in this kind of context. Some will use the network aspect of the story, some others will interact with electronic components. The two aspects should be easy to bridge, that is the goal. If that was not the case, please let me know (email address of the left side).


Project list, growing...

Several projects are featured here:

  • Basic GPIO interaction
  • Two Leds
  • Use the Raspberry Pi to turn LEDs on and off, through email (with doc)
  • Read Serial Port (with doc)
  • Read and parse NMEA Data from a GPS (with doc)
  • Read analog data with an Analog Digital Converter (ADC). (with doc, with node.js and WebSocket)
  • Drive servos using the PCA9685. (with doc).
  • Drive servos using the PCA9685, over the Internet, with an Android client option. (with doc).
  • Use the LSM303. (I2C compass & accelerometer, with doc).
  • Use the BMP180. (I2C temperature and pressure sensor, with doc).
  • Use the BMP183. (SPI temperature and pressure sensor, with doc).
  • Use a relay, through email. (with doc).
  • Use a relay, through HTTP. (with doc).
  • Use a seven-segment display. (with doc).
  • Use the VCNL4000 (I2C proximity sensor).
  • Use the TCS34725 (I2C color sensor, demo).
  • Use the TSL2561 (I2C light sensor).
  • Use the L3GD20 (I2C gyroscope, demo).
  • Use the MCP4725 (I2C Digital to Analog Converter, demo).
  • ... and more.

All the doc - with more details than here - can be reached from this page.

A Maven repo in GitHub

Yes, this is possible!

See this.

Why Java, why not something else?

Tricky question... Thanks for scrolling down that far.

The languages you use depend a lot on what you expect from your computer.

If you live on the hardware/sensors side of the world, you might prefer Python, as it is a simple language, close to scripting. The programs you will write will not be bigger than a couple of thousand lines.

If you are a mathematician, developing AI models, again Python might be your friend, it is well structured (I know, it's not 100% true... Ping me for details), and close enough to your mind set. You don't need to learn what will give extra value to - say - the JVM languages.

Now, if you need to scale, if you need to run on small single board computers as well as on clouds of big machines, then this is where JVM-based languages come on stage. They also provide some remote-debugging features, you only have to see them once to love them. Their consistency is also an asset, and you do not have to wait for the runtime to detect problems and errors (IDEs have made tremendous progresses in this area, leveraging the potential of the JVM). Their structure allows you to write multi-million line programs (C does it too, by the way).

This being said...

This being said, choosing your favorite language does not necessary isolate you from the rest of the world.

All languages - or almost - understand HTTP and related technologies like REST (if yours does not, drop it).

Docker and similar technologies provide this container abstraction.

Nothing is preventing you from using as many languages, frameworks and techniques you want, all you need is to package your applications as HTTP/REST servers that can communicate with each others. Bundling those servers into Docker images gives you even more flexibility.

It is very easy to invoke Python from Java, but the overhead of invoking it as a script is not negligible, and there is no in-memory status or transient state, in this case.

HTTP/REST sounds much nicer. We will provide examples, Java pinging a Python server, and vice-versa.

For now: there is a skeleton/template for a Python HTTP REST Server in http-tiny-server/src/main/python/http_server_skeleton.py

Same works also for Scala (JVM based language), NodeJS, ... whatever understands HTTP.

It does indeed open a lot of possibilities.

The common protocol is REST over HTTP (JSON - or XML - is also nice to have, to format the conveyed data).

Then it becomes what latin was in Europe in the middle-age: a common communication media.

The same must have happened in Arabic, Asian, and more communities, please don't get me wrong.

I like Java and related technologies.

You're welcome here, even if you don't!


About

JVM related (Java, Groovy, Scala, Kotlin, etc) samples for the Raspberry PI, relying on PI4J. IoT and friends.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java 28.4%
  • JavaScript 25.1%
  • HTML 12.3%
  • C++ 6.4%
  • Python 6.3%
  • Scala 6.1%
  • Other 15.4%