Java on the Raspberry Pi - Part 1: GPIOS Products Code Forgot Login Password?Thank you for registration for your assessment!Thanks for your review!

Java on the Raspberry Pi - Part 1: GPIOS Products Code Forgot Login Password?Thank you for registration for your assessment!Thanks for your review!

Kurze Einführung in JavaJava auf dem Raspbbuzzy Pi - Teil 1: GPIOs Produkte Code einbetten Login Passwort vergessen? Zur Registrierung Vielen Dank für Ihre Bewertung! Vielen Dank für Ihre Bewertung!

Java is one of the programming languages that have been around for a very long time.The first version was published in 1995, in the same year in which JavaScript, PHP and QT were born.Python is a little older, the first version was published in 1991.While the Java brand has passed from Sun Microsystems to Oracle, the development of the programming language is operated as an open source project that has moved to Github in 2020.Since 2018, two new Java releases have been provided annually, which means that buzzor corrections and newly developed functions regularly get to the computers.The new functions also include improvements that aim at embedded platforms such as the Raspbbuzzy Pi.There is the view that "Java is dead", but the numerous conferences - even if they have become virtually virtually in times of Corona - and many Java -related projects are proof that the language is still alive.A large number of well -known companies are responsible for the further development of Java, including Oracle, Microsoft, SAP and Google.It is also rumored that half of the Microsoft Azure Cloud runs on Java!Today there are Java distributions from various open source (JDK.Java.net, adoptopenjdk.net) and commercial providers (Azul, Bellsoft, Oracle and others).

Java on the Raspbbuzzy Pi?!

Wasn't the Raspbbuzzy Pi developed to be programmed with Python?That may be the case, but that doesn't mean that you can't use other languages.And, although this is a Java article, we do not want to say that this language is preferable to Python, C or another language!Each project has its own requirements for which a specific language could be perfect, or in which the development team has the best knowledge.When my first attempt to build a python-based pong game, ended unsuccessfully and turned the user interface to be disappointing, I wanted to explore as a Java developer whether I might not apply my specialist knowledge to the Raspbbuzzy Pi.Fortunately, user interfaces can be generated with JavaFX, an independent project [4, 5], which Java expanded to include a framework for creating GUIS (Graphical User Interface).It offers all typical basic components (buttons, labels, tables, diagrams) and there are a variety of free and open source libraries that are still expanding this list.Here I also found the perfect combination of Java with the Raspbbuzzy Pi, because I wanted to build a touchscreen surface for my son's drum booth (picture 1 and Fig. 2).

Combined with a relay board, an Arduino and some LED strips, this should be the basis for my experiments in the new world of embedded Java programming.

Preparation

For the experiments described in this article, you need a current Raspbbuzzy Pi with an ARMV7 or ARMV8 processor.The older boards with an ARMV6 have another internal layout that does not work for the standard Java.If you want to use Java on such an ARMV6 board, there is a solution that uses the Azul Zulu JDK.You do not have to type in code examples used in the article series, they are available in a Github repository.Start preparing the SD card for the Raspbbuzzy Pi.For some time now there has been a practical "Imager" tool in which you choose "Raspbbuzzy Pi Os Full (32-bit)" (Fig. 3).

Sobald die SD-Karte fertig ist und Sie Ihren Raspbbuzzy Pi gestartet haben, geben Sie am Terminal Java -version ein, um zu überprüfen, ob es die Version 11 ist.As you will see, OpenJDK is pre -installed in this full version of the operating system:

$ Java -version

OpenJDK version "11.0.9 "2020-10-20

OpenJDK Runtime Environment (Build 11.0.9+11-post raspbian-1deb10u1)

OpenJDK Server VM (Build 11.0.9+11-post raspbian-1deb10U1, mixed mode)

Visual studio code

You can develop, test and run your Java code on a PC before transfbuzzing it to the Raspbbuzzy Pi after completion.But there is another approach: Visual Studio Code.This free IDE (Integrated Development Environment) from Microsoft has a long list of extensions that make you the perfect companion for every programming project.There is a version for 32-bit arm systems (for example the Raspbbuzzy-Pi-OS) and 64-bit arm systems (the upcoming Raspbbuzzy-Pi-OS, which is still in development) or UbuntuDesktop.There is also a "Java Extension Pack", which the IDE adds several Java extensions to make it a full Ide for Java developers (Fig. 4)!

Experiment with Hello World!

Let us try out our first Java program on the Raspbbuzzy Pi.Write a new text file called “Helloworld in a text editor or in a text editor or in the terminal.Java“ mit folgendem Inhalt:

Public Class Helloworld {

public static void main (string args []) {

system.out.Println ("Hello World!");

}

}

Our entire code is part of the Helloworld class, which is equal to the file name by convention.A Java program begins with the Public Static Void Main (String Args []) method.The only thing we have to do here is "Hello World!" As an issue of the program.With Java 11 we can do this simple program without compiling the code. Geben Sie im Terminal im Verzeichniss der Java-Datei den Befehl Java HelloWorld.Java ein, um das folgende Ergebnis zu erhalten pi@raspbbuzzypi:~/elektor $ Java HelloWorld.JavaHello World! Sicherlich ist print() in Python kürzer im Vergleich zu system.out.Println () in Java, but we forgive Java this as a youth sin.

Read out the CPU temperature

Auf viele der systemwerte, Ein- und Ausgaben kann über das Verzeichnis /sys/ des Linux-Dateisystems zugegriffen werden.The values stored there can simply be read out as a text file.Let's try to determine the temperature of the Raspbbuzzy Pi processor from one of the files in this SYS directory. Die Namensgebung in der Verzeichnisstruktur ist nicht immer sehr eindeutig und auch die Interpretation der Werte ist nicht immer einfach, aber es ist ein guter Ausgangspunkt, um auch ein wenig das Linux-system kennenzulernen.Perform the following command:

$ ls -l /sys /

Total 0

DRWXR-XR-X 2 Root Root 0 Dec 2 15:44 Block

DRWXR-XR-X 29 Root Root 0 Feb 14 2019 Bus

DRWXR-XR-X 64 Root Root 0 Feb 14 2019 Class

DRWXR-XR-X 4 Root Root 0 Feb 14 2019 Dev

DRWXR-XR-X 10 Root Root 0 Feb 14 2019 Devices

DRWXR-XR-X 3 Root Root 0 Feb 14 2019 firmware

DRWXR-XR-X 8 Root Root 0 Jan 1 1970 FS

DRWXR-XR-X 12 Root Root 0 Jan 1 1970 Kernel

DRWXR-XR-X 122 Root Root 0 Feb 14 2019 modules

DRWXR-XR-X 2 Root Root 0 Dec 15 11:39 Power

It seems that we can find a lot of information here!Consider some of them a little more closely:

$ CAT/SYS/Firmware/DeviceTree/Base/CPUS/CPU@0/Compatible

Arm, Cortex-A72

$ cat/sys/class/net/wlan0/address

DC: A6: 32: C5: B7: 9D

$ cat/sys/class/bluetooth/hci0/uevent

Devtype = host

$ cat/sys/class/thermal/thermal_zone0/temp

30667

The last indication actually looks like a temperature in Grad Celsius if we would share the value by 1000!Let us write a simple program that reads this value every second and calculates the average temperature.

The code in Listing 1 uses some additional Java methods that are imported at the beginning.The IO methods read a SYS file as a text file.List and arraylist create a list of all measured values.In the Main () method we call up a separate method of checking speed () that captures the temperature and saves in the list.It is good practice to isolate any functionality in your own method to keep the code clean.

Listing 1: The CPutemp.Java code to read the Raspbbuzzy Pi processor temperature.import Java.io.BufferedReader;import Java.io.File;import Java.io.FileReader;import Java.util.List;import Java.util.Arraylist; public class cputemp {private static final string file = "/sys/class/thermal/thermal_zone0/temp";Private Static Final List

values = new ArrayList<>(); public static void main(String[] args) throws IntbuzzuptedException { while(true) { checkTemp(); Thread.Sleep (1000);}} private static void checkemp () {try (bufferedreader br = new buffered reader (new filereader (file))) {int value = integer.Valueof (BR.readline ());value.add (value);Int Total = Values.Stream ().MAPTOONT (Integer :: Valueof).sum(); system.out.Println ("Now:" + Value + " - Average:" + (Total / Values.Size ()) + " - Number of Measurements:" + Values.size()); } catch (Exception ex) { system.buzz.Println ("Error During Temperature Check:" + EX.Getmessage ());}}}

Thread.Sleep (1000) ensures that a second passes between each temperature determination.The average value is calculated within the method by calculating the total amount of the value list using a stream.Streams were introduced in Java 8 and are a very powerful way to work with lists of elements.Here, too, the file name is also the name of the class “CPutemp.Java“.As before, this is a simple Java class without additional dependencies, so that we can do it without compilation.The output can be stopped with "Ctrl+C":

pi@raspbbuzzypi:~/elektor $ Java CPUTemp.Java

Now: 36998 - Average: 36998 - Number of Measurements: 1

Now: 34563 - Average: 35780 - Number of Measurements: 2

Now: 35537 - Average: 35699 - Number of Measurements: 3

Now: 36024 - Average: 35780 - Number of Measurements: 4

Now: 35537 - Average: 35731 - Number of Measurements: 5

Control an LED and read out a button

Let us create another single-file Java application that switches two LEDs and can read out the condition of a button.The circuit to connect two LEDs and a button on separate GPIOS is quite simple. Der Taster benötigt 3,3 V, nicht 5,0 V, verwenden Sie also den richtigen Power-Pin des Raspbbuzzy Pi! In diesem Aufbau sind die LEDs an die Pins BCM 14 und BCM 15 angeschlossen, der Taster an BCM 18 (Bild 5).

Test at the terminal

Mit den im Raspbbuzzy-Pi-OS integrierten Befehlen können wir vom Terminal aus auf die GPIOs zugreifen.We use this to test our wiring.Perform the following commands to configure PIN 14 as the starting spin (surgery) and to switch it to high (ie) or low (dl).Try the same for the other LED of BCM 15:

$ raspi-gpio set 14 op

$ raspi-gpio set 14 dH

$ raspi-gpio set 14 dl

We can use a similar approach to test the button by configuring the PIN as an input spin and query the condition of the entrance:

$ raspi-gpio set 18 IP

$ raspi-gpio get 18

GPIO 18: Level = 0 FSEL = 0 func = input pull = down

$ raspi-gpio get 18

GPIO 18: Level = 1 FSEL = 0 func = input pull = down

When the button is pressed, the "level" value changes to 1.

Doing it in Java

Do it in Java!

We use the same basic approach as in “CPutemp.Java“ und nutzen die Terminalbefehle in einem Java-Programm, indem wir Runtime.Truntime ().Exec (cmd) specify.If we add the user input class scanner, we can also record the result of the command and use it to check the condition of the button.This is shown in Listing 2.

The code uses an action enum to simplify the processing of the command.In its simplest form, an enum is only a list of predefined names, but in this example we add a value to every name.This is a strong plus of enums, as they enable the code to make the code much more legible and usually simplify it at the same time.As can be seen in the Doaction Method, the action enum is used as a parameter and its value is used to generate the command to be carried out.The comments in the code should make everything clear, as this is only simple Java to illustrate the use of input and output GPIOs.The most complex part is the RunCommand method that uses some combined methods to carry out the command, read the result and treat possible errors.If this is not clear to you at the moment, don't worry - it will be as soon as the code is going! Since this example has no dependencies, we can do it without compilation.The output shows what is going on, so you should see how your LEDs switch on and off at different intervals.If the LEDs stop flashing, you can press the button that is checked ten times at a distance of one second.The expected edition is as follows:

$ Java RaspiGpio.Java

Executing: Raspi-Gpio Set 14 Op

Executing: Raspi-Gpio Set 15 Op

Executing: Raspi-Gpio Set 18 IP

Blink Loop: 0

Executing: Raspi-Gpio Set 14 DH

Executing: Raspi-Gpio Set 15 DH

Blink Loop: 1

Executing: Raspi-GPio set 14 dl

Executing: Raspi-Gpio Set 15 DL

...

Executing: Raspi-Gpio Get 18

Button check 0: GPIO 18: Level = 0 FSEL = 0 func = input pull = down

- Pushed: False

...

Button check 3: GPIO 18: Level = 1 FSEL = 0 func = input pull = down

- Pushed: True

...

Homework for next time!

Mit einigen Grundlagen haben wir eine kleine Einführung in Java auf dem Raspbbuzzy Pi gegeben.You are welcome to play around with the example code and read the background in the links given to deepen your understanding.Hopefully this will make the next steps easier in the next article if we develop a complete Java application and link our GPIOs to a website.(200617-02)

Haben Sie Fragen oder Kommentare?Haben Sie technische Fragen oder Kommentare zu diesem Artikel? Dann kontaktieren Sie den Autor direkt über Javaonraspbbuzzypi@webtechie.be or the editorial team via ditor@elector.com.