Skip to content

šŸ“ Blog

PiG 4 - Lcd and Java

The plan was to deliver you the Golo version of the previous post code to allow you to write on the LCD.

But it looks like I’ve done too much Java those months and not enough Golo. I’m currently stucked on a technical issue.
I’ll find a way but in the meantime and to keep the new goal to publish more often, I’ll share with you the Java version.

First, you have of course to follow the instruction on the second PiG article

Then, I used two command lines.
First, I compiled the source:

javac -source 7 -target 7 -classpath .:classes:/opt/pi4j/lib/'*' -d . LcdExample.java

Then I ran it:

sudo java -classpath .:classes:/opt/pi4j/lib/'*' LcdExample

You need root permissions to access the GPIO pins.

And finally, the Java code you need:

Download Here!

/*
* adapted from https://github.com/Pi4J/pi4j/blob/master/pi4j-example/src/main/java/LcdExample.java
* which is 
* Copyright (C) 2012 - 2013 Pi4J
* Licensed under the Apache License, Version 2.0 (the "License")
*
* Modified version by Thierry Chantier
* Copyright (C) 2013 PiG
* Licensed under the Apache License, Version 2.0 (the "License")
*
* compile with: javac -source 7 -target 7 -classpath .:classes:/opt/pi4j/lib/'*' -d . LcdExample.java 
* run with: sudo java -classpath .:classes:/opt/pi4j/lib/'*' LcdExample
*/
import java.text.SimpleDateFormat;
import java.util.Date;

import com.pi4j.component.lcd.LCDTextAlignment;
import com.pi4j.component.lcd.impl.GpioLcdDisplay;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;

public class LcdExample {

    public final static int LCD_ROWS = 2;
    public final static int LCD_ROW_1 = 0;
    public final static int LCD_ROW_2 = 1;
    public final static int LCD_COLUMNS = 16;
    public final static int LCD_BITS = 4;

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

        System.out.println("<--Pi4J--> GPIO 4 bit LCD example program");

        // create gpio controller
        final GpioController gpio = GpioFactory.getInstance();

        // initialize LCD
        final GpioLcdDisplay lcd = new GpioLcdDisplay(LCD_ROWS,          // number of row supported by LCD
                                                LCD_COLUMNS,       // number of columns supported by LCD
                                                RaspiPin.GPIO_11,  // LCD RS pin 
                                                RaspiPin.GPIO_10,  // LCD strobe pin
                                                RaspiPin.GPIO_06,  // LCD data bit 1
                                                RaspiPin.GPIO_05,  // LCD data bit 2
                                                RaspiPin.GPIO_04,  // LCD data bit 3
                                                RaspiPin.GPIO_01); // LCD data bit 4

        // clear LCD
        lcd.clear();
        Thread.sleep(1000);

        // write line 1 to LCD
        lcd.write(LCD_ROW_1, "Pi4J is great!");



        // stop all GPIO activity/threads by shutting down the GPIO controller
        // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
        // gpio.shutdown();   <--- implement this method call if you wish to terminate the Pi4J GPIO controller                
    }
}

I’m going to practice basics of Golo again, my brain is not on full steam those days ;)

See you soon!

PiG 3 - LCD Use

Last time, I explained how to use you Pi to interact with a LED using Golo. Let’s see something a bit stronger.

As I told you in my first Raspberry post, I bought a bunch of HD44780U LCD.

Those little LCD can be controled in 2 modes: 4 or 8 bits.
To minimize the number of GPIO pins used, I choosed the 4 bits mode.
It uses only 6 pins to write to the LCD instead of 11 with 8 bits mode.
The only drawbacks is that you have to write the 4 most significant bits first, use a validation impulse on LCD pin 6 (enable pin), then write the 4 least significant bits.

So first, use one of the existing schema on internet to wire your LCD to the GPIO. I used one from Zem.fr

This schema is working, clear… and show a pot to define contrast!

If you read french, take some time to read the full article there, first part has a good introduction to Raspberry GPIO and this LCD.

Here is my wiring:

Lots of wiresMy good old fellow: my breadboard

The next step was to test this wiring and I used the python script provided once more in this article. Just be careful that you use tabs in your python code after copy/paste.

#!/usr/bin/python

import RPi.GPIO as GPIO
from time import sleep
class HD44780:

  def __init__(self, pin_rs=7, pin_e=8, pins_db=[25, 24, 23, 18]):

      self.pin_rs=pin_rs
      self.pin_e=pin_e
      self.pins_db=pins_db

      GPIO.setmode(GPIO.BCM)
      GPIO.setup(self.pin_e, GPIO.OUT)
      GPIO.setup(self.pin_rs, GPIO.OUT)
      for pin in self.pins_db:
          GPIO.setup(pin, GPIO.OUT)

      self.clear()

  def clear(self):
      """ Blank / Reset LCD """

      self.cmd(0x33) # $33 8-bit mode
      self.cmd(0x32) # $32 8-bit mode
      self.cmd(0x28) # $28 8-bit mode
      self.cmd(0x0C) # $0C 8-bit mode
      self.cmd(0x06) # $06 8-bit mode
      self.cmd(0x01) # $01 8-bit mode

  def cmd(self, bits, char_mode=False):
      """ Send command to LCD """

      sleep(0.001)
      bits=bin(bits)[2:].zfill(8)

      GPIO.output(self.pin_rs, char_mode)

      for pin in self.pins_db:
          GPIO.output(pin, False)

      for i in range(4):
          if bits[i] == "1":
              GPIO.output(self.pins_db[::-1][i], True)

      GPIO.output(self.pin_e, True)
      GPIO.output(self.pin_e, False)

      for pin in self.pins_db:
          GPIO.output(pin, False)

      for i in range(4,8):
          if bits[i] == "1":
              GPIO.output(self.pins_db[::-1][i-4], True)


      GPIO.output(self.pin_e, True)
      GPIO.output(self.pin_e, False)

  def message(self, text):
      """ Send string to LCD. Newline wraps to second line"""

      for char in text:
          if char == '\n':
              self.cmd(0xC0) # next line
          else:
              self.cmd(ord(char),True)

if __name__ == '__main__':

  lcd = HD44780()
  lcd.message(" Sure it works! ")

Just for your eyes, a picture from what Zem.fr script is providing.

It works!

Now we are all set!

Wait? What? Where’s PiG?

I know, I know, this is my goal here.
But let’s meditate a moment: is it better to blog once every 6 months when a project is complete or post each little experiment steps?

See you soon ;)

Gary - Little 1

In those months, apart from kids and work, I started to play with a lot more electronics and robotics things.

The first thing I’d like to show you is my mobile platform.

base montƩe et cablƩe

Nice, isn’t it ? ;)

As I wanted to dig a little deeper in robotics world, I needed 2 things:

  • a long term goal, some dream project that I don’t know if it’s doable, no planning and such
  • sub goals of short projects that will help me in the larger picture.

In a far far away future, I’d like to have a mobile robot wandering in the house (ooops, stairs :) ) avoiding obstacles and able to launch an alert in case of unwanted presence (picture snapshot? video stream?).

And I lied… I have a second long term project, something already done by others: a Pixar Luxo lamp with minimal facial recognition and IA behaviours.

To achieve those goals, I decided to run little experiments in the meantime.
(yes, that’s the blog title and purpose ;) ) (note: at that time, the blog was called Little Experiments)

What I already started:

  • a simple 4WD robot
  • learn or remember electronics ;)
  • a webcam on a pan/tilt that I can control from computer
  • learn to use OpenCv
  • control a 2 lines LCD from my Raspberry

What is planned:

  • add IR and/or ultrasonic sensor to implement obstacle avoidance
  • control a 2.8ā€ touch screen from Pi and/or the Arduino
  • add JY-MCU to Arduino and have communication with a computer
  • control the Arduino from the Raspberry
  • stream video from the Pi to a computer

What is just in my mind:

  • experiment with plastic polymorph
  • build some quadri or hexa pod
  • play with 2.4Ghz R/C transmitter/receiver

That’s a lot and I’ll go deeper in each of those in later, but closer, blog posts.

As the subject of this post was Gary, I’ll finish with little details on it.

It is based on a DFRobot kit called 4WD Mobile Platform
The brain is a compatible Arduino board with motor bridge already on it called Romeo

I took some pictures during the assembly of the kit.

If french is not a problem, I had some details already in a forum where I got help.

This remind me that I need to push everything in a nice project page on Let’s make robots

As I already started to play with it, expect a IR sensor on Gary very soon. Next I’ll add the ultrasonic I just received.

See ya!

Why Golo ?

As I only receive emails and no comments, I have to post some explanations here ;)

When I first heard of Golo, I didn’t needed a new language. At least, I was satisfied with my daily use of Java or Groovy.

Then a little twitt from Julien Ponge mentionned something coming, something that will be linked to the JVM, something called… Golo

Because I already knew a little bit this crazy man who love explaining black magic voodoo with JVM bytecode, I decided to look at it.
It could have stopped there. The official release was planned in a few month ahead and I will wait.

Wait? Philippe CharriĆØre couldn’t ! He started to ask for an early release.
It looks funny, so I followed him, saying all the wonderful things to try with this language I didn’t knew :)

That’s how I became a beta tester of Golo, coding a http server and chatting with people writing framework with Golo for fun!

Maybe I didn’t accomplish huge things as Fast framework or Graddle plugin, but I already had great moments.

For sure, I learn every day new things.
Using Golo pushed me to question myself.
For example, as I discovered Java and object languages on the field, I never took time to look at the concepts behind. Trying to understand something with Golo bring me to a moment of thinking on inheritance versus composition.

Believe me: give a try to new languages! You will learn new ways of coding, thinking and having fun!

This article is in fact a lame excuse to thanks Julien and Philippe at least: thanks mates to give me such enthusiastic moments!

Golo - Little 5

Ok! That’s time to sync everyone on the state of GoloHttpServer.
First of all, I created a GitHub for this and you’re more than welcome to contribute, ask questions or even just talk about it.

This will allow you to take a look at the implementation of the run function which handle the Http request and response.

function run = |connectedClient, serverState| {

  let inFromClient = BufferedReader( InputStreamReader (connectedClient:getInputStream()))
  let outToClient = DataOutputStream(connectedClient:getOutputStream())

  let requestString = inFromClient:readLine()
  let headerLine = requestString

  let tokenizer = StringTokenizer(headerLine)
  let httpMethod = tokenizer:nextToken()
  let httpQueryString = tokenizer:nextToken()
  let responseBuffer = StringBuffer()
  responseBuffer:append("<b> This is the HTTP Server Home Page.... </b><BR>")
    responseBuffer:append("The HTTP Client request is ....<BR>")

    while (inFromClient:ready()) {
        # Read the HTTP complete HTTP Query
        responseBuffer:append(requestString + "<BR>")
      requestString = inFromClient:readLine()
  }

  httpMethodHandle(httpMethod, httpQueryString, responseBuffer, outToClient)
}

As you can see, I lied a bit: the run function is just here to prepare all the needed element to delegate to httpMethodHandle.
The input and output buffers are initialized, the query is tokenized and everything is set to httpMethodHandle function.

function httpMethodHandle = |methodName, queryString, responseBuffer, outToClient| {
  case {
      when methodName == "GET" {
          var fileName = queryString:replaceFirst("/", "")
          if (queryString=="/") {
              # The default home page
              fileName = Parameters(): HOME()   
          }
          fileName = URLDecoder.decode(fileName)
          if ( File(fileName):isFile()){                              
              sendResponse(200, fileName, true, outToClient)
          } else {
              sendResponse(404, "<b>The Requested resource not found ...." + "Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/<fileName></b>", false, outToClient)
          }    
      }
      otherwise {
          sendResponse(404, "<b>The Requested resource not found ...." + "Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/<fileName></b>", false, outToClient)
          }
      }
}

This method has a simple goal: analyze the resource name asked and return the appropriate content.
Note the use of case..when..otherwise Golo statements.
This is quite useful isn’t it ?

From here, I’ll try to use GoloHttpServer for side projects.
For example, during MixIT 2013, I attended a conference on the Dart language.
Serve HTML pages and javascripts ? That may be doable with GoloHttpServer ;)

As usual, I’m waiting your emails and comments.
Don’t be shy and drop me an email as the other little hackers that prefers that to public comment! As of today, everyone had my answers ;)