Tag Archives: Raspberry PI

Raspberry Pi Servo Java Duke Robot

What’s up?

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

Raspberry Pi Kafka cluster

How heya?

This is another blog about Raspberry PI, and today I want to show how I did a simple Kafka cluster.

If you’re not familiar with Kafka, I suggest you have a look at my previous post “What is Kafka?” before.

This is a really simple tutorial and you can find similar instructions over the internet.

Pre-Requisites

  • Raspbian installed

Components

  • 3x Raspberry Pi3 B with power supply and micro SD card with Raspbian.

Despite every time that you look at a cluster tutorial they add a switch, router, and some internet cables I did use just simple wifi.

For the software part, we will download Zookeeper and Kafka, and there’s no installation. Is just about untar and changing some settings files.
Download latest Apache Zookeeper & Apache Kafka.

Steps

You should do this in all Raspberry PIs.

1) Zookeeper

1
wget https://downloads.apache.org/zookeeper/zookeeper-3.6.1/apache-zookeeper-3.6.1-bin.tar.gz

Modify the “conf/zoo.cfg” with;

1
2
3
4
5
6
7
8
9
dataDir=/opt/zookeeper_data
tickTime=2000
initLimit=10
syncLimit=5
dataDir=/var/zookeeper
clientPort=2181
server.1=192.168.0.18:2888:3888
server.2=192.168.0.15:2888:3888
server.3=192.168.0.16:2888:3888

create a file “myid” and the file should have only the id of the zookeeper node.
I use 1, 2 and 3

Run this under the zookeeper’s root folder to start the Zookeeper service.

1
./bin/zkServer.sh start > /dev/null 2>&1 &

2) Kafka

I downloaded the most recent stable version
Modify the “config/server.properties” with:

1
2
3
broker.id=1
port=9092
host.name=192.168.0.10 zookeeper.connect=192.168.0.18:2181,192.168.0.15:2181,192.168.0.16:2181

Boker.id should be 1,2 and 3 for each PI
Host.name is the machine IP address
zookeeper.connect should be equals in all

(Depends on each Raspberry PI version you are using)

Update the “bin/kafka-server-start.sh” with:

1
2
export JMX_PORT=${JMX_PORT:-9999}
export KAFKA_HEAP_OPTS="-Xmx256M -Xms128M"

Otherwise, JVM would complain not able to allocate the specified memory.

Update “bin/kafka-run-class.sh” with:

1
KAFKA_JVM_PERFORMANCE_OPTS="-client -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+CMSScavengeBeforeRemark -XX:+DisableExplicitGC -Djava.awt.headless=true" # change -server to -client

You can run this to start Kafka

1
/opt/kafka/bin/kafka-server-start.sh -daemon /opt/kafka/config/server.properties > /dev/null 2>&1 &

And that’s it! Now you can do some basic tests.

Create a topic

1
/opt/kafka/bin/kafka-topics.sh --create --zookeeper 192.168.0.15:9092,192.168.0.16:9092,192.168.0.18:9092  --replication-factor 1 --partitions 1 --topic test

Describe this topic

1
/opt/kafka/bin/kafka-topics.sh --zookeeper localhost:2181 --describe --topic test

Star a terminal producer

1
/opt/kafka/bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test

Start a terminal consumer

1
/opt/kafka/bin/kafka-console-consumer.sh  --bootstrap-server localhost:9092 --topic test --from-beginning

I put my Zookeeper and Kafka in the “/opt” folder, but you can put it in any path.

Final Thoughts

I did use a Raspberry PI 3 B, but Raspberry PI already released The Raspberry Pi4 with 8g.
I don’t think we are too far from seeing a new Raspberry version, make Pi4 16gb or PI5, who knows.
I did use the Raspbian that is 32bits OS, and Raspberry PI already released Raspberry Pi OS, (yes they changed the name), that is the new official operating system and there’s a 64bits version.

With a more powerful computer, memory, and a 64bits OS it’s open to a lot of more ideas and scenarios. Kubernetes, Strimzi, and keda are just some initial things.

Another thing is that Kafka is about to remove the Apache Zookeeper dependency, and this will make a lot of changes.

I found a lot of tutorials about Kubernetes and 64bits OS for Raspberry, but could not find any Kubernetes Kafka example or Strimzi. I think with this new OS and more powerful hardware is just a question of time.

MicroK8s – is a powerful, lightweight, reliable production-ready Kubernetes distribution. It is an enterprise-grade Kubernetes distribution that has a small disk and memory footprint while offering carefully selected add-ons out-the-box, such as Istio, Knative, Grafana, Cilium, and more.

Canonical has released Ubuntu 19.10 with a focus on accelerating developer productivity in AI/ML, new edge capabilities for MicroK8s, and delivering the fastest GNOME desktop performance.
The Raspberry Pi 4 Model B is supported by Ubuntu 19.10. The latest board from the Raspberry Pi Foundation offers a faster system-on-a-chip with a processor that uses the Cortex-A72 architecture (quad-core 64-bit ARMv8 at 1.5GHz) and offers up to 8GB of RAM. With the Raspberry Pi 4 Model B, developers get access to a low-cost board, powerful enough to orchestrate workloads at the edge with MicroK8s.

Canonical and Raspberry

Raspberry with Ubuntu 20.04

K3s – a flavor of Kubernetes that is highly optimized for the edge. Though K3s is a simplified, miniature version of Kubernetes, it doesn’t compromise the API conformance and functionality.

Links

Kafka
confluent
Raspberry PI
8gb Raspberry PI4
Raspberry Pi OS
Strimzi
kubernetes
Keda
K3s
Microk8s

Some similar tutorial;

https://towardsdatascience.com/kafka-and-zookeeper-over-ubuntu-in-a-3-node-cluster-a-data-science-big-data-laboratory-part-4-of-4-47631730d240

http://czcodezone.blogspot.com/2014/11/setup-kafka-in-cluster.html

https://pandariel.com/posts/kafka-cluster/

https://rdiot.tistory.com/329

Micronaut Velocity with Raspberry PI

How’s the lad?

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!

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

7 Segment Display

What’s the crack jack?

Table of contents

1. 7-Segment Display
2. Cathode vs Anode
3. Components
4. Schematics
5. Code
6. PI4J
7. Links

1. 7-Segment Display

The 7-segment display, also written as “seven segment display”, consists of seven LEDs (hence its name) arranged in a rectangular fashion as shown. Each of the seven LEDs is called a segment because when illuminated the segment forms part of a numerical digit (both Decimal and Hex) to be displayed. An additional 8th LED is sometimes used within the same package thus allowing the indication of a decimal point (DP).


A 7-segment is a packaged set of 8 LEDs (7 number-segments & 1 decimal point).

I have the “hdsp-c1g1” model and it is a Common-Anode.

2. Cathode vs Anode

Common anode means that the anode (positive) side of all of the LEDs is electrically connected at one pin, and each LED cathode has its own pin. So turning on any particular segment will involve running a current from this common anode (positive) pin to the particular cathode (negative) pin for the desired segment.

Common cathode means that the cathodes of all of the LEDs are common and connected to a single pin. The anode for each LED has its own pin. So driving one of these means running a current from the particular anode (positive) pin for the desired segment to the common cathode pin.

The way that you are diving the 7-segment involves using a separate pin to drive each segment, so you use 8 pins of the Arduino to drive the display.

3. Components

  • 1x Arduino
  • 1x Raspberry Pi
  • 1x Common-Anode 7-segment display
  • 8x Resistor 221 ohm
  • 10x Jumper wires (generic)

4. Schematics

Common-Anode 7-segment display

My 7-segment display has its common pins (COM) connected to the +5V pin.
If a pin turns off, the corresponding segment will turn on. It’s because when the pin is on, the voltage difference between the pin and the +5V is 0. It is the same if the +5V was replaced by 0V. We can’t connect the COM to the GND because the LEDs are like diodes so they wouldn’t light up at all.

For Raspberry PI you need to check the GPIO numbers. Note that the pin number is not the same thing as the GPIO number.

For my example here I create a table to map:

5. Code

Arduino

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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
void setup()
{
  init();
  /*your setup code here*/
}

void loop()
{
  /*
   * your loop code here
   *
   * use display(num, dp) to display num (0123456789ABCDEF)
   * and the dot (if dp).
   *
   * you can turn off all the leds by writing display().
   */

}

void init()
{
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
}

void display(int n=-1, boolean dp)
{
  digitalWrite(9, !dp);
  if(num == 0)
  {
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 1);
  } else if(num == 1) {
    digitalWrite(2, 1);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 1);
    digitalWrite(6, 1);
    digitalWrite(7, 1);
    digitalWrite(8, 1);
  } else if(num == 2) {
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 1);
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 1);
    digitalWrite(8, 0);
  } else if(num == 3) {
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 0);
    digitalWrite(6, 1);
    digitalWrite(7, 1);
    digitalWrite(8, 0);
  } else if(num == 4) {
    digitalWrite(2, 1);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 1);
    digitalWrite(6, 1);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else if(num == 5) {
    digitalWrite(2, 0);
    digitalWrite(3, 1);
    digitalWrite(4, 0);
    digitalWrite(5, 0);
    digitalWrite(6, 1);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else if(num == 6) {
    digitalWrite(2, 0);
    digitalWrite(3, 1);
    digitalWrite(4, 0);
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else if(num == 7) {
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 1);
    digitalWrite(6, 1);
    digitalWrite(7, 1);
    digitalWrite(8, 1);
  } else if(num == 8) {
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else if(num == 9) {
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 0);
    digitalWrite(6, 1);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else if(num == 10) {
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 1);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else if(num == 11) {
    digitalWrite(2, 1);
    digitalWrite(3, 1);
    digitalWrite(4, 0);
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else if(num == 12) {
    digitalWrite(2, 0);
    digitalWrite(3, 1);
    digitalWrite(4, 1);
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 1);
  } else if(num == 13) {
    digitalWrite(2, 1);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 1);
    digitalWrite(8, 0);
  } else if(num == 14) {
    digitalWrite(2, 0);
    digitalWrite(3, 1);
    digitalWrite(4, 1);
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else if(num == 15) {
    digitalWrite(2, 0);
    digitalWrite(3, 1);
    digitalWrite(4, 1);
    digitalWrite(5, 1);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
  } else {
    digitalWrite(2, 1);
    digitalWrite(3, 1);
    digitalWrite(4, 1);
    digitalWrite(5, 1);
    digitalWrite(6, 1);
    digitalWrite(7, 1);
    digitalWrite(8, 1);
  }
}

Raspberry PI – 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
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
from gpiozero import LED
from time import sleep

pin01 = LED(2)
pin02 = LED(3)
pin04 = LED(4)
pin05 = LED(5)
pin06 = LED(6)
pin07 = LED(12)
pin09 = LED(14)
pin10 = LED(15)


def clear():
    pin01.on()
    pin02.on()
    pin04.on()
    pin05.on()
    pin06.on()
    pin07.on()
    pin09.on()
    pin10.on()


def display(number):
    if number == 0:
        pin01.off()
        pin02.off()
        pin04.off()
        pin05.on()
        pin06.off()
        pin07.off()
        pin09.off()
        pin10.on()
    if number == 1:
        pin01.on()
        pin02.on()
        pin04.off()
        pin05.on()
        pin06.off()
        pin07.on()
        pin09.on()
        pin10.on()
    if number == 2:
        pin01.off()
        pin02.off()
        pin04.on()
        pin05.on()
        pin06.off()
        pin07.off()
        pin09.on()
        pin10.off()
    if number == 3:
        pin01.on()
        pin02.off()
        pin04.off()
        pin05.on()
        pin06.off()
        pin07.off()
        pin09.on()
        pin10.off()
    if number == 4:
        pin01.on()
        pin02.on()
        pin04.off()
        pin05.on()
        pin06.off()
        pin07.on()
        pin09.off()
        pin10.off()
    if number == 5:
        pin01.on()
        pin02.off()
        pin04.off()
        pin05.on()
        pin06.on()
        pin07.off()
        pin09.off()
        pin10.off()
    if number == 6:
        pin01.off()
        pin02.off()
        pin04.off()
        pin05.off()
        pin06.on()
        pin07.off()
        pin09.off()
        pin10.off()
    if number == 7:
        pin01.on()
        pin02.on()
        pin04.off()
        pin05.on()
        pin06.off()
        pin07.off()
        pin09.on()
        pin10.on()
    if number == 8:
        pin01.off()
        pin02.off()
        pin04.off()
        pin05.on()
        pin06.off()
        pin07.off()
        pin09.off()
        pin10.off()
    if number == 9:
        pin01.on()
        pin02.on()
        pin04.off()
        pin05.off()
        pin06.off()
        pin07.off()
        pin09.off()
        pin10.off()


clear()
sleep(1)
while True:
    for x in range(10):
        display(x)
        sleep(1)

6. PI4J

PI4J provides a friendly object-oriented I/O API and implementation libraries for Java programmers to access the full I/O capabilities of the Raspberry Pi platform. This project abstracts the low-level native integration and interrupts monitoring to enable Java programmers to focus on implementing their application business logic.

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/

This is the Number for the PI 3 B model.

Because the PI4J use a different GPIO number I add a new column in my table;

Raspberry PI – Java – 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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package led.example;

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;

public class SevenSegmentsDisplay {

    static GpioPinDigitalOutput pin01 = null;
    static GpioPinDigitalOutput pin02 = null;
    static GpioPinDigitalOutput pin04 = null;
    static GpioPinDigitalOutput pin05 = null;
    static GpioPinDigitalOutput pin06 = null;
    static GpioPinDigitalOutput pin07 = null;
    static GpioPinDigitalOutput pin09 = null;
    static GpioPinDigitalOutput pin10 = null;

    public static void display(int number) {

        if(number == 0) {
            pin01.low();
            pin02.low();
            pin04.low();
            pin05.high();
            pin06.low();
            pin07.low();
            pin09.low();
            pin10.high();
        }
        if(number == 1) {
            pin01.high();
            pin02.high();
            pin04.low();
            pin05.high();
            pin06.low();
            pin07.high();
            pin09.high();
            pin10.high();
        }
        if(number == 2) {
            pin01.low();
            pin02.low();
            pin04.high();
            pin05.high();
            pin06.low();
            pin07.low();
            pin09.high();
            pin10.low();
        }
        if(number == 3) {
            pin01.high();
            pin02.low();
            pin04.low();
            pin05.high();
            pin06.low();
            pin07.low();
            pin09.high();
            pin10.low();
        }
        if(number == 4) {
            pin01.high();
            pin02.high();
            pin04.low();
            pin05.high();
            pin06.low();
            pin07.high();
            pin09.low();
            pin10.low();
        }
        if(number == 5) {
            pin01.high();
            pin02.low();
            pin04.low();
            pin05.high();
            pin06.high();
            pin07.low();
            pin09.low();
            pin10.low();
        }
        if(number == 6) {
            pin01.low();
            pin02.low();
            pin04.low();
            pin05.low();
            pin06.high();
            pin07.low();
            pin09.low();
            pin10.low();
        }
        if(number == 7) {
            pin01.high();
            pin02.high();
            pin04.low();
            pin05.high();
            pin06.low();
            pin07.low();
            pin09.high();
            pin10.high();
        }
        if(number == 8) {
            pin01.low();
            pin02.low();
            pin04.low();
            pin05.high();
            pin06.low();
            pin07.low();
            pin09.low();
            pin10.low();
        }
        if(number == 9) {
            pin01.high();
            pin02.low();
            pin04.low();
            pin05.low();
            pin06.low();
            pin07.low();
            pin09.low();
            pin10.low();
        }

    }

    public static void main(String[] args) {

        final GpioController gpio = GpioFactory.getInstance();

        pin01 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_08);
        pin02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_09);
        pin04 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_07);
        pin05 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_21);
        pin06 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_22);
        pin07 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_26);
        pin09 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_15);
        pin10 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_16);

        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);

        try {
            while(true) {
                for (int i = 0; i < 10; i++) {
                    display(i);
                    System.out.println("Number " + i);
                    Thread.sleep(2000);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            gpio.shutdown();
        }
    }

}

Results

7. Links

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

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

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

https://github.com/Pi4J/pi4j

Led Race – Another DublinMaker

Hey you!

Last week 20th July was the Dublin Maker 2019.

So, let’s start with an explanation about what is Dublin Maker.

Dublin Maker is a free to attend, community run event, which was held on Saturday, July 20th, 2019 in Merrion Square. Dublin Maker takes the form of a “show and tells” experience where inventors/makers sourced through an open call, to have an opportunity to showcase their creations in a carnival atmosphere. It is a family friendly showcase of invention, creativity and resourcefulness, and a celebration of the maker movement. It’s a place where people show what they are making and share what they are learning.

If you have science interested kids, or you’re a kid yourself, this is a great event with lots of interesting open people and things that at least some of them you’ll probably not get the chance to see again.

I have been attending the event for a long time now, and today I want to explain the project that I presented this year. The Open Led Race. Back in March I was on holidays and I saw one tweet from Arduino about the project and I said to myself, it’s exactly what I’m going to show on Dublin Maker.

My first concern was about using an arcade button, because the idea is to let a lot of kids to play, I was afraid that they would break the button fast and I need to replace fast as well because a lot of people came to see the project.
After few days looking at the instructions and the components I had the idea to change the arcade button to MakeyMakey and because of that I decided to create the idea using a Raspberry PI to simplify the idea.

Apparent I’m the first one to do it.

The project is really simple. I’m using the WS2813 led strip and using the API that I found on the internet.

Python library wrapping for the rpi-ws281x library

You can check my GitHub to see the full code.

It’s basically a Python code that runs on the Raspberry Pi that controls the Led Strip and the MakeyMakey that I used to simulate one keyboard. Every click I move the led 3 positions forward.
The makeymakey part is just one aluminium foil and play-doh.

I used the GPIO 10 (pin 19) and 18 (pin 12) for LED_PIN and LED_DMA and GPIO 9 (pin 6) for Ground.

I created a simple version of the Led Race, but there are lots of space for improvement.

I came with some ideas that one day I’ll implement;

  • Add a monitor where I can show a timer and the best lap timer;
  • I can show a speedometer or something like the number of push per second;
  • I can display the best lap overall;
  • four players put for cars at the same time;

Other ideas are some things that I saw on the Open Led Races Arduino web site and the comments, like;

  • Add velocity;
  • Add some physics when the car goes up, more push is needed, or increase the speed when going down;
  • Add a second Led Strip and then the car can go left and right and they can leave some kind of weapons on the track, and the car gets stuck there if hits for fill push;

I want to add here a big thanks to Elaine Akemi who helped me with the project. She is also my official partner of Hackathons and events, and she was with me in the last two Dublin Maker editions.

Raspberry Pi with InfluxDB and Grafana

Alright, boss?

Grafana is an open source metric analytics & visualization suite. It is most commonly used for visualizing time series data for infrastructure and application analytics but many use it in other domains including industrial sensors, home automation, weather, and process control.

https://grafana.com/
http://docs.grafana.org/guides/getting_started/

InfluxDB is an open-source time series database developed by InfluxData.
it is written in Go and optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet of Things sensor data, and real-time analytics.

https://www.influxdata.com/

Install InfluxDB on Raspberry Pi
https://gist.github.com/boseji/bb71910d43283a1b84ab200bcce43c26

You can follow the link for more details but basically, I just run this:

1
2
3
4
5
6
7
sudo apt-get update && sudo apt install apt-transport-https curl

curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add -

echo "deb https://repos.influxdata.com/debian jessie stable" | sudo tee /etc/apt/sources.list.d/influxdb.list

sudo apt-get update && sudo apt-get install influxdb

For this example we don’t care about the web-based Admin user interface.

To start the server

1
sudo service influxdb start

Install Grafana on Raspberry Pi
https://github.com/fg2it/grafana-on-raspberry/wiki

You can follow the link for more details but basically, I just run this:

1
2
3
4
5
6
7
8
9
sudo apt-get install apt-transport-https curl

curl https://bintray.com/user/downloadSubjectPublicKey?username=bintray | sudo apt-key add -

echo "deb https://dl.bintray.com/fg2it/deb jessie main" | sudo tee -a /etc/apt/sources.list.d/grafana.list

sudo apt-get update

sudo apt-get install grafana

To start the server

1
sudo service grafana-server start

With everything installed you are ready to start doing some awesome things.

I going to show two examples here:
One using sense-hat to get the temperature, pressure and humidity value
and other using HS110 to get the energy consumption

Here is a good InfluxDB getting started
https://docs.influxdata.com/influxdb/v0.8/introduction/getting_started/

1
influx -precision rfc3339
1
CREATE DATABASE logger

You can test with

1
SHOW DATABASES

To run the code you need Install the python package first

1
sudo pip install influxdb

Both examples are quite similar. Just change what I write on the table.
This code is a hack from some Google examples.

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
import argparse
import time
import datetime
import sys
from influxdb import InfluxDBClient
from sense_hat import SenseHat

sense=SenseHat()
 
# Set required InfluxDB parameters.
host = "localhost" #Could also set local ip address
port = 8086
user = "root"
password = "root"
 
# How frequently we will write sensor data from SenseHat to the database.
sampling_period = 5

def get_args():
    '''This function parses and returns arguments passed in'''
    # Assign description to the help doc
    parser = argparse.ArgumentParser(description='Program writes measurements data from SenseHat to specified influx db.')
    # Add arguments
    parser.add_argument(
        '-db','--database', type=str, help='Database name', required=True)
    parser.add_argument(
        '-sn','--session', type=str, help='Session', required=True)
    now = datetime.datetime.now()
    parser.add_argument(
        '-rn','--run', type=str, help='Run number', required=False,default=now.strftime("%Y%m%d%H%M"))
   
    # Array of all arguments passed to script
    args=parser.parse_args()
    # Assign args to variables
    dbname=args.database
    runNo=args.run
    session=args.session
    return dbname, session,runNo
   
def get_data_points():
    # Get the three measurement values from the SenseHat sensors
    temperature = sense.get_temperature()
    pressure = sense.get_pressure()
    humidity = sense.get_humidity()
    # Get a local timestamp
    timestamp=datetime.datetime.utcnow().isoformat()
    print ("{0} {1} Temperature: {2}{3}C Pressure: {4}mb Humidity: {5}%" .format(session,runNo,
    round(temperature,1),u'u00b0'.encode('utf8'),
    round(pressure,3),round(humidity,1)))
   
    # Create Influxdb datapoints (using lineprotocol as of Influxdb >1.1)
    datapoints = [
            {
                "measurement": session,
                "tags": {"runNum": runNo,
                },
                "time": timestamp,
                "fields": {
                    "temperaturevalue":temperature,"pressurevalue":pressure,"humidityvalue":humidity
                    }
                }
            ]
    return datapoints

# Match return values from get_arguments()
# and assign to their respective variables
dbname, session, runNo =get_args()  
print "Session: ", session
print "Run No: ", runNo
print "DB name: ", dbname

# Initialize the Influxdb client
client = InfluxDBClient(host, port, user, password, dbname)
       
try:
     while True:
        # Write datapoints to InfluxDB
        datapoints=get_data_points()
        bResult=client.write_points(datapoints)
        print("Write points {0} Bresult:{1}".format(datapoints,bResult))
       
        sense.show_message("OK")
           
        # Wait for next sample
        time.sleep(sampling_period)
       
        # Run until keyboard ctrl-c
except KeyboardInterrupt:
    print ("Program stopped by keyboard interrupt [CTRL_C] by user. ")

The HS110 example I just change some lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
consumption = plug.get_emeter_realtime()[“power”]
    # Create Influxdb datapoints (using lineprotocol as of Influxdb >1.1)
    datapoints = [
            {
                "measurement": session,
                "tags": {"runNum": runNo,
                },
                "time": timestamp,
                "fields": {
                    "consumption":consumption
                    }
                }
            ]
    return datapoints

To run:

1
python igor.py -db=logger -sn=test1

To setup Grafana:
http://localhost:3000

Go to Datasource->Add New and fill in with your database details
User and psw should be: “root” and “root” by default

Create a new dashboard, choose your database and on the tab matrics configure your query.

Edit the dashboard and go to metrics.

Choose the database and then configure the query.

If you succeed in create your dashboard let a comment below about what are you doing.

Sense HAT

What’s the story Rory?

The Sense HAT is an add-on board for Raspberry Pi, made especially for the Astro Pi mission – it launched to the International Space Station in December 2015 – and is now available to buy. The Sense HAT 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.

HAT stands for “Hardware attached on top”. It is a new hardware specification for add-one modules for the Raspberry Pi. HATs have several advantages compared to older add-on modules for the Raspberry Pi.

www.raspberrypi.org/products/sense-hat/
www.raspberrypi.org/blog/announcing-2017-18-astro-pi/
www.astro-pi.org/

Technical Specification:

Gyroscope – angular rate sensor: +/-245/500/2000dps
Accelerometer – Linear acceleration sensor: +/-2/4/8/16 g
Magnetometer – Magnetic Sensor: +/- 4/8/12/16 gauss
Barometer: 260 – 1260 hPa absolute range (accuracy depends on the temperature and pressure, +/- 0.1 hPa under normal conditions)
Temperature sensor (Temperature accurate to +/- 2 degC in the 0-65 degC range)
Relative Humidity sensor (accurate to +/- 4.5% in the 20-80%rH range, accurate to +/- 0.5 degC in 15-40 degC range)
8×8 LED matrix display
Small 5 button joystick

GPIO – https://pinout.xyz/pinout/sense_hat

Getting started with the Sense HAT

Getting the Sense HAT ready to use is quite simple. Turn off your Raspberry Pi and make sure your Raspbian SD card is inserted if it isn’t already. Place the Sense HAT on the GPIO pins, carefully aligning them before pressing down firmly so that it properly attaches to the Raspberry Pi. Once that’s done, turn the Raspberry Pi back on. If it’s attached properly, the LEDs on the SenseHAT will light up in a rainbow pattern during boot time. When it gets to the desktop, the pattern might turn off but that’s normal.

1
2
sudo apt-get install sense-hat
sudo pip-3.2 install pillow

you’ll need to reboot the Raspberry Pi.

Now you are ready to try some examples; Finding magnetic North with Sense HAT | How To make Compass

1
2
3
4
5
6
7
8
from sense_hat import SenseHat
import time

hat = SenseHat()

while true:
    bearing = sense.get_compass()
    print ('bearing: {:.0f} to north' .format(bearing))

https://projects.raspberrypi.org/en/projects/getting-started-with-the-sense-hat
https://www.raspberrypi.org/documentation/hardware/sense-hat/README.md

book

https://www.raspberrypi.org/blog/experiment-with-the-sense-hat-in-the-new-magpi-essentials-book/

API’s

Python
https://pythonhosted.org/sense-hat/

NodeJS
https://www.npmjs.com/package/node-sense-hat

Scratch
https://www.raspberrypi.org/documentation/usage/scratch/gpio/README.md

node-red
https://www.npmjs.com/package/node-red-node-pi-sense-hat

Source code
https://github.com/RPi-Distro/python-sense-hat

Emulator
https://www.trinket.io/sense-hat

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

Examples
https://github.com/RPi-Distro/python-sense-hat/blob/master/examples/README.md
https://codeclubprojects.org/en-GB/sense-hat/

I have some examples in my Github as well

Raspberry Pi Zero OTG mode

Story Horse?

The Raspberry Pi Zero support USB On The Go, given the processor, is connected directly to the USB port, unlike on the B, B+ or Pi 2 B, which goes via a USB hub.

Since there are so many who have experienced various problems with their Pi setup and connection I created the following steps that I used from Linux Ubuntu 16.04 with success.

With OTG mode, the process is like this:

  • Format the SD card on your computer
  • Tweak a few files on the SD card before ejecting it
  • Plug the SD card into the Pi
  • Plug the Raspberry Pi USB port into your computer
  • Share Internet with the Raspberry pi device
  • SSH to the Pi
  • Continue any setup on the device

This is a huge improvement as we no longer need to plug in the HDMI monitor or keyboard for initial setup!

When you plug the Pi into your computer in the above example, it is emulating a virtual Ethernet device. Essentially, your computer thinks you plugged a network card into it.

Let’s go:

1 – Downloaded Raspbian Jessie Lite image from here:

https://www.raspberrypi.org/downloads/

2 – Copied image to Micro SDHC card via these instructions:

https://www.raspberrypi.org/documentation/installation/

1
$ sudo dd bs=4M if=2017-04-10-raspbian-jessie.img of=/dev/sdb status=progress

OR

1
$ sudo unzip -p 2017-04-10-raspbian-jessie.zip | sudo dd of=/dev/sdX bs=4096

OR you can use Etcher https://etcher.io/

I recommend Etcher.io which will flash your SD card, in the same way, whichever of those Operating Systems you use on your PC/laptop.

3 – To help prevent Raspberry Pis around the globe from being hacked the RPi foundation have now disabled SSH on the default image. Just create a text file in /boot/ called ssh – it can be blank or you can type anything you want it.

To /boot add empty file: ssh

https://www.raspberrypi.org/documentation/remote-access/ssh/

To share internet from USB

To /boot/config.txt add line with: dtoverlay=dwc2

To /boot/cmdline.txt after rootwait add: modules-load=dwc2,g_ether

4 – Unmount sd card, put in Pi Zero, connect USB cable between Pi Zero power port and Linux computer.

5 – From Linux computer:

Open the nm-connection-editor (from the panel). Select Wired connection 2 (RasPi on USB) & click Edit. Under ‘IPv4 Setting’ set ‘Method’ = ‘Shared to other computers’.

6 – SSH

1
$ ssh pi@raspberrypi.local (password = raspberry)

DONE!

Extras:
Once its booted you should now be able to open up the terminal, and using ping Raspberry pi.local you can see the RPi’s IP address.
Using this address in terminal type

1
ssh pi@

https://raspberryblog.de/?p=1921