Tag Archives: Java

OCI Dashboard with Smashing/Dashing and Kafka

What’s up?
2021/03/05

This is another blog about Raspberry PI, and today I want to show how I did a simple Kafka cluster demo. It’s kind of a continuation from my two previous blogs, Kafka at the edge with Raspberry PI and Real-Time Locating System with Kafka.

If you’re not familiar with Kafka, I suggest you have a look at my previous post What is Kafka? before, and you can have a look at how I created the Kafka cluster here.

Idea

I found the idea of an OCI dashboard with smashing dashing in a colleague’s blog some time ago and I decided to pivot a little bit in a simple Raspberry Pi Kafka example where I can get OCI data and combine it with the smashing dashing dashboard idea.

For the producer part, you can use my Micronaut Sense hat example as a start point and just change to get the OCI data. You can get the full Micronaut Kafka Producer code on my GitHub.

https://docs.oracle.com/en-us/iaas/Content/API/SDKDocs/javasdk.htm
https://github.com/oracle/oci-java-sdk

For the consumer part, you can use my Quarkus example. You can get the full Quarkusl Kafka Consumer code on my GitHub.

clone the code and change the update.py file to read the value from the REST interface that Quarkus generates.

Results

Because this is a kind of Oracle Cloud solution you can use Oracle Streaming Service instead of hosting your Kafka.

Oracle Streaming Service (OSS) is a real-time, serverless, Apache Kafka-compatible event streaming platform for developers and data scientists, it provides a fully managed, scalable, and durable solution for ingesting and consuming high-volume data streams in real-time. To learn more about Oracle Streaming Service, see the documentation overview.

You can check my GitHub with some OSS examples and check the Micronaut one.

You just need to change the “application.yml” file from my Micronaut sense hat idea.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
kafka:
  bootstrap:
    servers: streaming.{your-region}.oci.oraclecloud.com:9092
  security:
    protocol: SASL_SSL
  sasl:
    mechanism: PLAIN
  key:
    serializer: org.apache.kafka.common.serialization.StringSerializer
    deserializer: org.apache.kafka.common.serialization.StringDeserializer
  value:
    serializer: org.apache.kafka.common.serialization.StringSerializer
    deserializer: org.apache.kafka.common.serialization.StringDeserializer
  retries: 5
  max:
    request:
      size: 1048576
    partition:
      fetch:
        bytes: 1048576
  group:
    id: group-0

And you can use all solutions in the cloud.

The Kafka consumer and the dashboard can be hosted in a cloud VM as well.

OCI Logging service is a highly scalable and fully managed single pane of glass for all the logs in your tenancy. Logging provides access to logs from Oracle Cloud Infrastructure resources. These logs include critical diagnostic information that describes how resources are performing and being accessed. To learn more about the Logging service, see the documentation overview.

OCI Service Connector Hub moves data, such as logs from Logging, to services, such as Object Storage, Streaming, and Monitoring. It triggers functions for custom data processing and sends notifications about changes to cloud resources. To learn more about the Service Connector Hub, see the documentation overview.

Here using Service Connector Hub I can get the logs from my tenancy and send them to OSS in a simple way.

Links

https://www.oc-blog.com/2019/05/13/oci-dashboard-with-smashing-dashing/

https://github.com/AnykeyNL/oci-smashing

Real-Time Locating System with Kafka

How’s the craic?
2021/03/03

This is another blog about Raspberry PI, and today I want to show how I did a simple Kafka cluster demo using the Inky pHAT. It’s kind of a continuation from my previous blog, Kafka at the edge with Raspberry PI.

If you’re not familiar with Kafka, I suggest you have a look at my previous post What is Kafka? before, and you can have a look at how I created the Kafka cluster here.

The Inky pHAT is an add-on board for Raspberry Pi, that has a low-energy, high-falutin, electronic paper (ePaper / eInk / EPD) display for your Pi, in three different color schemes: red/black/white, yellow/black/white, and black/white.
You can learn more about Inky pHAT here and check the API here.

Real-Time Locating System (RTLS) enables identifying and tracking the location of objects or people in real-time. It is used everywhere in transportation and logistics across industries.

Use Cases

  • Real-time alerting on a single event: Monitor assets and people and send an alert to a controller, mobile app, or any other interface if an issue happens.
  • Continuous real-time aggregation of multiple events: Correlation data while it is in motion. Calculate average, enforce business rules, apply an analytic model for predictions on new events, or any other business logic.
  • Batch analytics on all historical events: Take all historical data to find insights, e.g., for analyzing issues of the past, planning future location requirements, or training analytic models.

This is not an exhaustive list.

A postmodern RTLS requires an open architecture and high scalability and of course, the implementations can rely on Kafka.

Idea

A simple Raspberry Pi Kafka example where I can use one node to get the open Dublin Bus data and display it in real-time on the other node using Inky phat.

For the producer part, you can use my Micronaut Sense hat example as a start point and just change to use Dublin Bus data instead. You can get the full Micronaut Kafka Producer code on my GitHub.

https://data.smartdublin.ie/dataset/gtfs-r-real-time-passenger-information
https://developer.nationaltransport.ie/api-details#api=gtfsr&operation=gtfsr

For the consumer part, you can use my Quarkus example. You can get the full Quarkusl Kafka Consumer code on my GitHub.

Results

Kafka can be deployed as a single broker in a vehicle and a global Kafka infrastructure can spread to multiple cloud providers, regions, countries, or even continents and integrate with tens or hundreds of factories or other edge locations.

Curiosity

1- Dublin bus is already using an e-ink display to show bus stop data.

2- I did a demo for real-time data from connected vehicles some time ago.

3- I won a prize at Europe’s First government-funded Blockchain Hackathon with the idea of an app to track medical devices combining Kafka and BlockChain.

Links

https://towardsdatascience.com/tracking-nyc-citi-bike-real-time-utilization-using-kafka-streams-1c0ea9e24e79

https://eng.lyft.com/a-new-real-time-map-matching-algorithm-at-lyft-da593ab7b006

https://github.com/ds4es/real-time-units-gps-tracking

kafka at the edge with Raspberry PI

How’s the man?
2021/03/01

This is another blog about Raspberry PI, and today I want to show how I did a simple Kafka cluster demo using Sense Hat & GFX Hat.

If you’re not familiar with Kafka, I suggest you have a look at my previous post What is Kafka? before, and you can have a look at how I created the Kafka cluster here.

The Sense HAT is an add-on board for Raspberry Pi, tha has an 8×8 RGB LED matrix, a five-button joystick and includes the following sensors: Gyroscope, Accelerometer, Magnetometer, Barometer, Temperature sensor and Relative Humidity sensor.
You can learn more about Sense hat in my previous blog.

The GFX HAT is an add-on board for Raspberry Pi, tha has a 128×64 pixel, 2.15″ LCD display with snazzy six-zone RGB backlight and six capacitive touch buttons. GFX HAT makes an ideal display and interface for your headless Pi projects.
You can learn more about GFX hat here and check the API here.

The idea here is to focus on scenarios where the Kafka clients and the Kafka brokers are running on the edge. This enables edge processing, integration, decoupling, low latency, and cost-efficient data processing.

Edge Kafka is not simply yet another IoT project using Kafka in a remote location. Edge Kafka is an essential component of a streaming nervous system that spans IoT (or OT in Industrial IoT) and non-IoT (traditional data-center / cloud infrastructures).

Multi-cluster and cross-data center deployments of Apache Kafka have become the norm rather than an exception. A Kafka deployment at the edge can be an independent project. However, in most cases, Kafka at the edge is part of an overall Kafka architecture.
Apache Kafka is the New Black at the Edge in Industrial IoT, Logistics, and Retailing

https://www.kai-waehner.de/blog/2020/01/01/apache-kafka-edge-computing-industrial-iot-retailing-logistics/

Idea

A Raspberry Pi 2 nodes Kafka cluster, with a Micronaut Kafka producer that gets sense hat data and a Quarkus Kafka consumer that puts the result in a REST that GFX Hat reads using python API.

The Micronaut producer gets the Sense Hat humidity, pressure, and temperature values and sends it to a Kafka topic.

The Quarkus consumer reads a Kafka topic and generates a REST interface with the last topic value. I used the GFX Hat to display the result.

You can get the full Micronaut Kafka Producer code on my GitHub.
You can get the full Quarkusl Kafka Consumer code on my GitHub.

Results

Kafka is a great solution for the edge. It enables deploying the same open, scalable, and reliable technology at the edge, data center, and the cloud. This is relevant across industries. Kafka is used in more and more places where nobody has seen it before. Edge sites include retail stores, restaurants, cell towers, trains, and many others.

Rainbow HAT and Java

How’s it going there?
2021/02/26

The Rainbow HAT is an add-on board for Raspberry Pi, is a collection of sensors, inputs and outputs from popular components in one board, which we can attach the 40 pin pin-out of the Pi.
After Google announced Android Things Pimoroni designed the all-singing, all-dancing Rainbow HAT. Jam-packed with LEDs, buttons and sensors, it enables you to experiment with Android Things and use it with the wide range of protocols available on the Raspberry Pi.

Rainbow HAT is designed to stimulate ideas – a development platform that can be used to build new and exciting IoT hardware and software. It’s also meant to be fun to use, and that should be apparent just by looking at it – the playful rainbow formed from the seven APA102 LEDs and the barometer type markings below it.

Technical Specification:

  • Seven APA102 multicolor LEDs
  • Four 14-segment alphanumeric displays (green LEDs)
  • HT16K33 display driver chip
  • Three capacitive touch buttons
  • Atmel QT1070 capacitive touch driver chip
  • Blue, green, and red LEDs
  • BMP280 temperature and pressure sensor
  • Piezo buzzer
  • Breakout pins for servo, 12C, SPI, and UART (all 3v3)

The board is designed specifically to show off the wide range of protocols available on the Raspberry Pi, including SPI (the APA102 LEDs), 12C (the BPM280 sensor and 14-segment displays), GPIO (the capacitive touch buttons and LEDs), and PWM (the piezo buzzer).

GPIO

Android Things

Originally known as Project Brillo, Google’s relaunched Android Things operating system is designed to be used with IoT devices. The smart home project got its start in 2015 under the name Brillo, which was meant to provide the “underlying operating system for the internet of things.” In 2016, Google revamped Brillo and relaunched the initiative as Android Things, which was likewise meant to run on products like connected speakers, security cameras, and routers. By relying on Android, the OS was supposed to be familiar to developers and easy to get started with. Google envisioned it as an operating system that would let developers code for a whole world of smart devices using the tools they already knew from coding for Android phones. At the time, that included speakers and displays, but also more experimental gadgets, like small robots, art installations, a projector, a 3D printer, and more.

In 2018, some initial smart speakers and smart displays came out using the underlying OS, and then nothing happened. Nearly two years later, and Android Things is now on track to be shut down. Google recently announced phasing out its Android Things IoT platform. New projects will not be accepted after January 5, 2021, and the Android Things console will be turned down for all projects in 2022.

https://developer.android.com/things/

Getting started with the Rainbow HAT

For information on how to get started with Android Things and RainbowHAT visit the official developer site for Android Things. To put the latest Android Things image on your SD card, see the instructions here.

You can find the driver and samples published in the official GitHub organization.

With Raspbian you can check the Python library here.

The Rainbow HAT uses the same 14 segments display that I showed in the Helidon demo.

HT16K33 driver

The HT16K33 is a memory mapping and multi-function LED controller driver. The max. Display segment numbers in the device is 128 patterns (16 segments and 8 commons) with a 13*3 (MAX.) matrix key scan circuit. The software configuration features of the HT16K33 make it suitable for multiple LED applications including LED modules and display subsystems.

I created a Java API to control the Rainbow Hat 14 segments display, using the HT16K33 driver.

This is just a simple test and I create the driver just for the 14 segment display, but one idea is to complete the driver to control all other Rainbow HAT components.
I follow the idea of the Android thing and translate it to PI4j.

This time I decided to do an example with Javalin.

Javalin is a very lightweight web framework for Java 8 (and later) and Kotlin. It supports modern features such as HTTP/2, WebSocket, and asynchronous requests. Javalin is servlet-based, and its main goals are simplicity, a great developer experience, and first-class interoperability between Java and Kotlin. Javalin is built on top of Jetty, and its performance is equivalent to raw Jetty code.

Idea

A simple Javalin example that shows a 14 segments display and control in real-time using my Java API Rainbow Hat 14 segments display. A 14 segments display – 5421AG with HT16K33 Driver

Code

1
2
3
4
5
6
7
8
9
10
    public static void main(String[] args) {
        try {
            AlphanumericDisplay segment = new AlphanumericDisplay("I2C1");
            segment.setBrightness(Ht16k33.HT16K33_BRIGHTNESS_MAX);
            segment.display("Igor");
            segment.setEnabled(true);
        } catch (IOException | UnsupportedBusNumberException e) {
            e.printStackTrace();
        }
    }

Disclaimer – I got the CSS and JS here.

You can get the full code on my GitHub.

Another cool thing about this idea is that some other Hats use the HT16K33 driver as well, and this means that we can reuse this code just by changing the GPIO numbers. For example the Four Letter pHat.

Links

https://javalin.io/

https://pdf1.alldatasheet.com/datasheet-pdf/view/683745/FORYARD/FYD-5421AX-32.html

https://pinout.xyz/pinout/rainbow_hat

https://shop.pimoroni.com/products/rainbow-hat-for-android-things

https://developer.android.com/things

https://shop.pimoroni.com/products/four-letter-phat

https://cdn-shop.adafruit.com/datasheets/ht16K33v110.pdf
https://www.adafruit.com/product/1427

Raspberry Pi Helidon 14 segment display

How goes the battle?
2021/02/22

This post is to show how I created a Helidon demo with a Raspberry PI. A simple web application to control a 14 segments display. This is another blog about Java on Raspberry PI.

Originally named J4C (Java for Cloud), Helidon was designed to be simple and fast, and the framework supports two programming models for writing microservices: Helidon SE and Helidon MP. Helidon SE is designed to be a microframework that supports the reactive programming model, it features three core APIs to create a microservice; a web server, configuration, and security. Helidon MP, on the other hand, is an Eclipse MicroProfile runtime that allows the Jakarta EE community to run microservices in a portable way; supports the MicroProfile 1.1 specification for building microservices-based applications.
But in both cases, a Helidon microservice is a Java SE application that starts a tinny HTTP server from the main method.


Helidon architecture


Microservices frameworks categories


Helidon 2.0 adds significant improvements for both Helidon SE and Helidon MP programming styles

Fun Facts
Helidon is a Greek word for swallow, a type of bird that according to Wikipedia has “a slender, streamlined body and long pointed wings, which allow great maneuverability and very efficient flight”. Perfect for darting through the clouds.

Idea

A simple Helidon example that shows a 14 segments display and control in real-time a real one with a Raspberry Pi 3 B.

I have the “5421AG” model. 14 segments display – 5421AG

The PI4J uses a different GPIO number.

Note: Pi4J (by default) uses an abstract pin numbering scheme to help insulate software from hardware changes. Pi4J implements the same pin number scheme as the Wiring Pi

http://wiringpi.com/pins/

PIN 11 -> GPIO 11
PIN16 -> GPIO 25

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
    static Routing createRouting() {
        List<Class<? extends Encoder>> encoders = Collections.singletonList(UppercaseEncoder.class);

        return Routing.builder()
                .register("/rest", component)
                .register("/websocket",
                        TyrusSupport.builder().register(
                                ServerEndpointConfig.Builder.create(MessageBoardEndpoint.class, "/board")
                                        .encoders(encoders).build())
                                .build())
                .register("/web", StaticContentSupport.builder("/WEB").build())
                .build();
    }

Disclaimer – I use the same CSS that I used in my Quarkus Qute example and I started this demo using this WebSocket sample

You can get the full code on my GitHub.

Links

https://helidon.io

https://github.com/oracle/helidon

https://www.youtube.com/channel/UChg00-uTTrCMmPsuzUNaZsA

https://medium.com/helidon

https://twitter.com/helidon_project

https://www.jetbrains.com/help/idea/helidon.html

https://microprofile.io/

Raspberry Pi Vert.X web potentiometer

How’s the form?
2021/01/15

After I wrote my motivation resolutions post I came with the idea that it is possible to do a lot of Raspberry Pi projects without a wait or by any new component.
“Invest your time before you invest your money and build something before you buy the component.”
Just create a virtual one.

For example, If you don’t have a 7 segment display you can follow this;
If you don’t have an 8×8 Led Matrix you can follow this and so on.

You can go ahead and use this idea to start your project without waiting more time and without buying anything.

Today I want to show a way to play with a potentiometer.

From Wikipedia
A potentiometer is a three-terminal resistor with a sliding or rotating contact that forms an adjustable voltage divider. If only two terminals are used, one end and the wiper, it acts as a variable resistor or rheostat.

From Google
An instrument for measuring an electromotive force by balancing it against the potential difference produced by passing a known current through a known variable resistance.

From Youtube

And More
potentiometers basic principles

Idea

A simple web application that I can use as a potentiometer.

This time I decided to do it with Vert.X.

Vert.x is an open-source, reactive and polyglot software development toolkit from the developers of Eclipse. Vert.x is a tool-kit for building reactive applications on the JVM
It is called polyglot due to its support for multiple JVM and non-JVM languages like Java, Groovy, Ruby, Python, and JavaScript.

Being reactive, verticles remain dormant until they receive a message or event. Verticles communicate with each other through the event bus. The message can be anything from a string to a complex object. Message handling is ideally asynchronous, messages are queued to the event bus, and control is returned to the sender. Later it’s dequeued to the listening verticle. The response is sent using Future and callback methods and with that, I can create something that calls the REST several times in a sequence without care about the answer and with no blocks.

If I use setPwm(), my LED can be any value between 0 and 100, and using an input range will only call one time to change the value. This will jump the value from current to select and not will create a potentiometer style.

But I can add some CSS style and create a knob and simulate a real potentiometer. Now I can call my REST interface for each value and simulate a real use of a potentiometer.

I can combine this with my Duke robot and control the Duke’s arm.
I can combine it with my Christmas hats and create a nice fade effect.

I can do a simple Led example.

Code

I just used the Vert.X web start hello world example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    private void changePwmValue(RoutingContext routingContext) {
        String range = routingContext.pathParam("id");
       
        System.out.println(range); //just to see calls
       
        final GpioController gpio = GpioFactory.getInstance();
        Gpio.pwmSetMode(Gpio.PWM_MODE_MS);
        Gpio.pwmSetRange(100);
        Gpio.pwmSetClock(500);
       
        GpioPinPwmOutput led01 = gpio.provisionSoftPwmOutputPin(RaspiPin.GPIO_15, "LeftGreen");
        led01.setPwm(Integer.parseInt(range));

        routingContext.response()
                .putHeader("content-type", "application/json")
                .setStatusCode(200)
                .end(Json.encodePrettily(range));
    }

Disclaimer – I got the CSS from here

You can get the full code on my GitHub.

Links

https://vertx.io/

https://github.com/eclipse-vertx/vert.x

https://passive-components.eu/resistors-potentiometers-basic-principles/

https://pi4j.com/

Raspberry Christmas Hat

What’s the story Rory?
2020/12/24

Today I want to show some Christmas project ideas using Hats. Yes, another blog about Raspberry PI.

Thanks to their GPIO headers, most Pi computers can connect to devices called HATs, which stands for Hardware Attached on Top.

Theses are the Hats that I have and they came from ThePiHut

Christmas Tree Programmable KitLink

I think this hat comes in 3 different sets, one just with white LEDs, one with just red LEDs and one with mixed white and red LEDs and you can find the Pre-soldered version as well.
From the Python API you can get the GPIO numbers to use with PI4j

SnowPiLink

The SnowPi is a discontinued item, but you can find it in ThePiHut.
From the Python API you can get the GPIO numbers to use with PI4j

During 2020 there was another successful Kickstarter project for the SnowPi RGB. This is a new version of the Snowman. There is no soldering required and it now has color NeoPixels instead of single color LEDs.

3D Xmas Tree for Raspberry PiLink

After a while, they release an RGB version as well. Like all the others you can find the Pre-soldered version as well.
From the code sample, you can get the GPIO numbers to use with PI4j

Raspberry Pi Christmas Tree StarLink

From the Python API you can get the GPIO numbers to use with PI4j

The idea here is that all hats are just boards with some LEDs, and this makes the project like an electronics project for blinking LEDs.
We can use the PWM idea, “Pulse Width Modulation” that I already explained here, but let me explain from the LEDs perspective.

From Wikipedia

The term duty cycle describes the proportion of ‘on’ time to the regular interval or ‘period’ of time; a low duty cycle corresponds to low power because the power is off for most of the time. Duty cycle is expressed in percent, 100% being fully on. When a digital signal is on half of the time and off the other half of the time, the digital signal has a duty cycle of 50% and resembles a “square” wave. When a digital signal spends more time in the on state than the off state, it has a duty cycle of >50%. When a digital signal spends more time in the off state than the on state, it has a duty cycle of <50%. Here is a pictorial that illustrates these three scenarios.

You can find examples and samples for all Hats in Python, but because I support the #JavaOnRaspberryPi idea, let’s see how to use them with Java.
Remember to use the hashtag #JavaOnRaspberryPi on Twitter to show the world Raspberry Pi with Java.

PI4J
You can check my post to start with PI4J but for these hats what you need to understand is the Pwm Example

1
2
3
com.pi4j.wiringpi.Gpio.pwmSetMode(com.pi4j.wiringpi.Gpio.PWM_MODE_MS);
com.pi4j.wiringpi.Gpio.pwmSetRange(100);
com.pi4j.wiringpi.Gpio.pwmSetClock(500);

The idea is that “setPwm()” can be 0, to turn off, 100, to turn on and any value between 0 and 100 to create a fade.

1
2
3
setPwm(0)
setPwm(100)
setPwm(value);

Now you can not just turn on and off, but you can also pulse, blink and add a fade effect.

Here is my forest project from 2018.

Of course, you can do some Christmas ideas with any other hat.

Sensehat http://www.igfasouza.com/blog/sense-hat/

You can create your Christmas tree using my Micronaut example. GitHub Or just using this.

E-ink display

I know that 4tronix has some Christmas Micro Bit hats and people did some hack around to use with a Raspberry PI, But If you know any other Christmas Hat, please let me know in the comments.

As a good developer, I always get confused about Christmas and Halloween as 25 Dec is equal to 31 Oct

PumpkinPi https://thepihut.com/products/halloween-pumpkinpi-for-raspberry-pi

Some other Christmas ideas
https://www.raspberrypi.org/blog/tag/christmas/

Raspberry Pi Servo Java Duke Robot

What’s up?
2020/10/12

This post is to show how I created a Java Duke Servo demo with a Raspberry Pi. This is another blog about Java on Raspberry Pi.

Interfacing a Servo Motor with Raspberry Pi is an interesting topic as Servo Motors are the main components of a Robot and with the help of Raspberry Pi, you can have endless opportunities in Robotics.

Because today we celebrate children’s day in Brazil, I came with the idea to show this simple robot example using a servo motor and a Raspberry Pi. And nothing better than a Java Duke servo demo to show Java on Raspberry Pi.

Components

  • SG90 Micro-servo motor
  • Jumper wires (generic)
  • Raspberry Pi 3b or Arduino

Idea

Using a cardboard and Duke image to create a servo demo where Duke moves his arm.


I used this image to create my demo.

Control a Servo Motor

To control a Servo Motor, you need to use a technique called Pulse Width Modulation or PWM. In PWM technique, you will be sending a pulse of variable width and the position of the Servo Motor’s shaft will be set by the width or length of the Pulse.

Nice “Pulse Width Modulation” explanation here

The frequency of the PWM signal is a fixed value and is dependent on the type of Servo Motor.
At 50Hz i.e. a period of 20ms, the minimum pulse width is 1ms and the maximum pulse width is 2ms. Most servo motors can have a swept area of 180 degrees i.e. 90 degrees on either side of the neutral position.

When the pulse width of the PWM Signal is 1ms, the position of the servo is the left. The Duty Cycle of this position is (1ms/20ms) x 100 = 5%.

Similarly, for pulse widths of 1.5ms and 2ms, the position of the servo is middle (with a duty cycle of 7.5%) and far right (with a duty cycle of 10%).

  • so for 50hz, one frequency is 20ms
  • duty cycle for 0 degree = (1/20)*100 = 5%
  • duty cycle for 90 degree = (1.5/20)*100 = 7.5%
  • duty cycle for 180 degree = (2/20)*100 = 10%

Note: Be aware here that you need to test and check your servo. You might need to calibrate this number for you.

Schematics

I’m using the SG90 servo motor and you can check the Datasheet here.

The Tower Pro SG90 Servo Motor Consists of three Pins: PWM (Orange or Yellow), VCC (Red), and GND (Brown). The VCC and GND pins must be connected to +5V and GND of the power supply.

PWM or Signal Pin of the Servo Motor must be connected to the PWM Output of the Controller (Raspberry Pi). Based on the width of the Pulses from the PWM signal, the angle of the Servo Motor’s shaft will vary.

1ms pulse for 0 degree (LEFT)
1.5ms pulse for 90 degree (MIDDLE)
2ms pulse for 180 degree (RIGHT)

PI4J

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinPwmOutput;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.util.CommandArgumentParser;


public class TestPwmServoMotor {

    public static void main(String[] args) throws InterruptedException {
        pwm(args);
    }

    /**
     * @param args
     * @throws InterruptedException
     */

    public static void pwm(String[] args) throws InterruptedException{

        final GpioController gpio = GpioFactory.getInstance();

        Pin pin = CommandArgumentParser.getPin(
        RaspiPin.class,    
        RaspiPin.GPIO_00,  
        args);            
        GpioPinPwmOutput pwm = gpio.provisionSoftPwmOutputPin(pin);
        pwm.setPwmRange(100);

        int sleep = 1000;
        for(int i = 0 ;i<10;i++){
             pwm.setPwm(25);
            System.out.println("PWM rate is: " + pwm.getPwm());
            Thread.sleep(sleep);

            pwm.setPwm(15);
            System.out.println("PWM rate is: " + pwm.getPwm());
            Thread.sleep(sleep);

            pwm.setPwm(6);
            System.out.println("PWM rate is: " + pwm.getPwm());
            Thread.sleep(sleep);
        }
        gpio.shutdown();        
        System.out.println("pwm end");

    }
}

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import RPi.GPIO as GPIO
import time


control = [5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10]
servo = 22
GPIO.setmode(GPIO.BOARD)
GPIO.setup(servo,GPIO.OUT)
p=GPIO.PWM(servo,50)
p.start(2.5)

try:
       while True:
           for x in range(11):
             p.ChangeDutyCycle(control[x])
             time.sleep(0.03)
             print x
           
           for x in range(9,0,-1):
             p.ChangeDutyCycle(control[x])
             time.sleep(0.03)
             print x
           
except KeyboardInterrupt:
    GPIO.cleanup()

Arduino

And of course, you can do this demo with an Arduino as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <Servo.h>


Servo servo

void setup() {
  servo.attach(9);
 
}
void loop() {
  servo.write(0);
  delay(500);
  delay(10000);
  servo.write(90);
  delay(500);
  delay(10000);
  servo.write(180);
  delay(500);
  delay(10000);
  servo.write(90);
  delay(500);
  delay(10000);
  servo.write(0);
  delay(500);
  delay(10000);
}

Results

The next steps are to create a code that transforms text into the flag language

Links

https://pi4j.com/1.2/index.html

https://github.com/Pi4J/pi4j

http://www.ee.ic.ac.uk/pcheung/teaching/DE1_EE/stores/sg90_datasheet.pdf

https://en.wikipedia.org/wiki/Pulse-width_modulation

https://www.electronics-tutorials.ws/blog/pulse-width-modulation.html

https://en.wikipedia.org/wiki/Flag_semaphore

Micronaut Velocity with Raspberry PI

How’s the lad?
2020/09/29

This post is to show how I created a Micronaut Velocity demo with a Raspberry PI. This is another blog about Java on Raspberry PI.

Micronaut is a JVM-based framework for building lightweight, modular applications. Developed by OCI, the same company that created Grails, Micronaut is the latest framework designed to make creating microservices quick and easy.

One of the most exciting features of Micronaut is its compile time dependency injection mechanism. Most frameworks use reflection and proxies to perform dependency injection at runtime. Micronaut, however, builds its dependency injection data at compile time. The result is a faster application startup and smaller memory footprints.

Although Micronaut is primarily designed around message encoding/decoding there are occasions where it is convenient to render a view on the server-side. The views module provides support for view rendering on the server-side and does so by rendering views on the I/O thread pool in order to avoid blocking the Netty event loop.

https://micronaut-projects.github.io/micronaut-views/latest/guide/

Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.

http://velocity.apache.org/

You can check my blog post about sense hat here

Idea

I started with the idea to do something similar with my Quarkus Qute 7 segment display demo, using Micronaut, but I pivoted a little bit. I end up with a Micronaut Vecolcity interface that provides a way to control the 8×8 Led Matrix from SenseHat.

I used this Java wrapper for Sense Hat

Code

LedController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package example.micronaut;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Consumes;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.views.View;
import rpi.sensehat.api.SenseHat;
import rpi.sensehat.api.dto.Color;

@Controller("/display")
public class LedController {
   
    SenseHat senseHat = new SenseHat();

    @View("led")
    @Get("/create")
    public Map<String, Object> create() {
        senseHat.ledMatrix.clear();
        return createModelWithBlankValues();
    }

    @View("led")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Post("/save")
    public Map<String, Object> save(@Valid @Body CommandLedSave cmd) {
        if(cmd != null) {
            if(cmd.getLeds() != null && !cmd.getLeds().equals("")) {
                String possitions[] = cmd.getLeds().split(",");
                Color[] pixels = createLedMatrix();
                int i = 0;
                int x = 0;
                int y = 0;
                while (i < possitions.length){
                    x = Integer.parseInt(possitions[i++]);
                    y = Integer.parseInt(possitions[i++]);
                    if(x != 0) {
                        x = x*8;
                    }
                    pixels[x+y] = Color.RED;
                   
                }
                senseHat.ledMatrix.setPixels(pixels);
            }else {
                senseHat.ledMatrix.clear();
            }
        }

        final Map<String, Object> model = new HashMap<>();
        model.put("leds", cmd.getLeds());
        return model;
    }

    private Map<String, Object> createModelWithBlankValues() {
        final Map<String, Object> model = new HashMap<>();
        model.put("title", "");
        return model;
    }
   
    private Color[] createLedMatrix() {
        Color off = Color.of(0, 0, 0);
        Color[] pixels = new Color[64];
        for (int i = 0; i < pixels.length; i++) {
            pixels[i] = off;
        }
        return pixels;
    }

}

led.vm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Micronaut Velocity Sensehat</title>

 <style>
    body {
  background-color: #888889;
  color: white;
  font-family: sans-serif;
}

h1 {
  text-align: center;
  font-size: 3em;
}

.base {
  display: inline-block;
  border: 10px groove gray;
  border-right: 10px ridge gray;
  border-bottom: 10px ridge gray;
  padding: 10px;
  background-color: #BBBBBB;
  position: absolute;
  text-align: center;
}

.matrix {
  width: 250px;
  height: 240px;
  background-color: black;
  border: 5px ridge gray;
  border-bottom: 5px groove gray;
  border-left: 5px groove gray;
}

.led {
  cursor:pointer;
  display: inline-block;
  margin: 5px;
  margin-bottom: 0px;
  width: 20px;
  height: 20px;
  border-radius: 10px;
  background-color: red;
  -webkit-box-shadow: 0px 0px 15px 5px rgba(255, 0, 0, .75);
  -moz-box-shadow: 0px 0px 15px 5px rgba(255, 0, 0, .75);
  box-shadow: 0px 0px 15px 5px rgba(255, 0, 0, .75);
}

.off{
  background-color: #222222;
   -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 190, .75);
  -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 190, .75);
  box-shadow: 0px 0px 0px 0px rgba(255, 255, 190, .75);
}
  </style>

<script>
function newLine(mat){
  var matrix = document.getElementById("matrix");
  var line = new Array();
  for (var i = 0; i < 8; i++){
   var led = document.createElement("div");
   led.onclick = function(){onOff(this, mat)};
   led.className = "led off";
   matrix.appendChild(led);
   line[i] = led;
 }
 return line;
}

function start(mat) {
 for (var i = 0; i < 8; i++)
   mat[i] = newLine(mat);
 return mat;
}

function onOff (led, mat) {
 if (led.className == "led off")
   led.className = "led";
 else
   led.className = "led off";
   
 getCoords(mat);
 document.getElementById("form_display").submit();
}

function getCoords (mat) {
 var coords = new Array();
 for ( var i = 0; i < mat.length; i++)
   for ( var j = 0; j < mat[i].length; j++)
     if (mat[i][j].className == "led") {
       coords.push(i);
       coords.push(j);
     }
 document.getElementById("leds").value = coords;
}

function write (mat,arr) {
 var i = 0;
 while (i < arr.length){
   mat[arr[i++]][arr[i++]].className = "led";
 }
}

window.onload = function() {
    var mat = new Array();
    var mat_final = start(mat);
   
    var leds = document.getElementById("leds").value;
    if (typeof leds !== 'undefined' && leds) {
        write(mat_final,leds.split(","));
    }
}

</script>

</head>
<body>
<h1>Led Display</h1>
<form action="/display/save" method="post" id="form_display">

    <input type="hidden" id="leds" name="leds" value="$leds" />
    <div id="base" class="base">
        <div id="matrix" class="matrix"></div>
    </div>
   
</form>

</body>
</html>

Disclaimer – I got the CSS from here

You can get the full code on my GitHub.

Links

https://micronaut.io/

https://micronaut-projects.github.io/micronaut-views/latest/guide/

http://velocity.apache.org/

https://github.com/cinci/rpi-sense-hat-java

Quarkus Qute with Raspberry PI

Hey you!
2020/09/22

This post is to show how I created a Quarkus Qute demo with a Raspberry PI. This is another blog about Java on Raspberry PI.

Quarkus is a full-stack, Kubernetes-native Java framework made for Java virtual machines (JVMs) and native compilation, optimizing Java specifically for containers and enabling it to become an effective platform for serverless, cloud, and Kubernetes environments.

Qute is a templating engine designed specifically to meet the Quarkus needs. The usage of reflection is minimized to reduce the size of native images. The API combines both the imperative and the non-blocking reactive style of coding. The engine is based on RESTEasy/JAX-RS. As such, Qute web applications are implemented by defining resource types with methods answering to specific HTTP verbs and accept headers. The only difference being, that HTML pages are returned instead of JSON as in your typical REST-ful data API. The individual pages are created by processing template files.

If you’ve worked with other templating engines before, like me, this will look very familiar to you.

Note: Qute is an experimental feature.

Idea

A simple Quarkus Qute example that shows a 7 segments display and control in real-time a real one with a Raspberry Pi 3 B.
When I was googling about a 7 segment display this site appeared in my result and I came up with the idea.

I suggest you check out my 7 segment display blog before looking at the code.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package com.igor;

import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;

@Path("hello")
public class HelloResource {

    @Inject
    Template hello;
   
    final GpioController gpio = GpioFactory.getInstance();
    GpioPinDigitalOutput pin01 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_26, "1", PinState.HIGH);
    GpioPinDigitalOutput pin02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_22, "2", PinState.HIGH);
    GpioPinDigitalOutput pin04 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_07, "3", PinState.HIGH);
    GpioPinDigitalOutput pin05 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_09, "4", PinState.HIGH);
    GpioPinDigitalOutput pin06 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_08, "5", PinState.HIGH);
    GpioPinDigitalOutput pin07 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_15, "6", PinState.HIGH);
    GpioPinDigitalOutput pin09 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_16, "7", PinState.HIGH);
    GpioPinDigitalOutput pin10 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_21, "8", PinState.HIGH);

    @GET
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance get() {

        return hello.data("field1", "Test").data("field2", "Igor");
    }

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Transactional
    @Path("/segment")
    public TemplateInstance segmentDisplay(@MultipartForm MessageForm messageForm) {
       
        if(messageForm.segment1 == null && messageForm.segment2 == null &&
                messageForm.segment3 == null && messageForm.segment4 == null &&
                messageForm.segment5 == null && messageForm.segment6 == null &&
                messageForm.segment7 == null && messageForm.segment8 == null) {
            pin01.setShutdownOptions(true, PinState.HIGH);
            pin02.setShutdownOptions(true, PinState.HIGH);
            pin04.setShutdownOptions(true, PinState.HIGH);
            pin05.setShutdownOptions(true, PinState.HIGH);
            pin06.setShutdownOptions(true, PinState.HIGH);
            pin07.setShutdownOptions(true, PinState.HIGH);
            pin09.setShutdownOptions(true, PinState.HIGH);
            pin10.setShutdownOptions(true, PinState.HIGH);
            pin01.high();
            pin02.high();
            pin04.high();
            pin05.high();
            pin06.high();
            pin07.high();
            pin09.high();
            pin10.high();
        }

        display(messageForm);

        return hello.data("field1", "Test").data("field2", "Igor")
                .data("segment1", messageForm.segment1)
                .data("segment2", messageForm.segment2)
                .data("segment3", messageForm.segment3)
                .data("segment4", messageForm.segment4)
                .data("segment5", messageForm.segment5)
                .data("segment6", messageForm.segment6)
                .data("segment7", messageForm.segment7)
                .data("segment8", messageForm.segment8);
    }

    public void display(MessageForm messageForm) {

        if(messageForm.segment1 != null && messageForm.segment1.equals("on")) {
            pin01.low();
        }else {
            pin01.high();
        }
        if(messageForm.segment2 != null && messageForm.segment2.equals("on")) {
            pin02.low();
        }else {
            pin02.high();
        }
        if(messageForm.segment3 != null && messageForm.segment3.equals("on")) {
            pin04.low();
        }else {
            pin04.high();
        }
        if(messageForm.segment4 != null && messageForm.segment4.equals("on")) {
            pin05.low();
        }else {
            pin05.high();
        }
        if(messageForm.segment5 != null && messageForm.segment5.equals("on")) {
            pin06.low();
        }else {
            pin06.high();
        }
        if(messageForm.segment6 != null && messageForm.segment6.equals("on")) {
            pin07.low();
        }else {
            pin07.high();
        }
        if(messageForm.segment7 != null && messageForm.segment7.equals("on")) {
            pin09.low();
        }else {
            pin09.high();
        }
        if(messageForm.segment8 != null && messageForm.segment8.equals("on")) {
            pin10.low();
        }else {
            pin10.high();
        }
    }
}

Disclaimer – I got the CSS from here

You can get the full code on my GitHub.

Links

https://quarkus.io/

https://quarkus.io/guides/qute

https://quarkus.io/guides/qute-reference

https://propjockey.github.io/bcd7sdd/

https://pi4j.com/1.2/index.html