Using Java to write to LCD 20x4 Bricklet

For this project we are assuming, that you have a Java development environment set up and that you have a rudimentary understanding of the Java language.

If you are totally new to Java itself you should start here. If you are new to the Tinkerforge API, you should start here.

Goals

We are setting the following goals for this project:

  • Temperature, ambient light, humidity and air pressure should be shown on the LCD 20x4 Bricklet,
  • the measured values should be updated automatically when they change and
  • the measured values should be formated to be easily readable.

Since this project will likely run 24/7, we will also make sure that the application is as robust towards external influences as possible. The application should still work when

  • Bricklets are exchanged (i.e. we don't rely on UIDs),
  • Brick Daemon isn't running or is restarted,
  • WIFI Extension is out of range or
  • Weather Station is restarted (power loss or accidental USB removal).

In the following we will show step-by-step how this can be achieved.

Step 1: Discover Bricks and Bricklets

To start off, we need to define where our program should connect to:

private static final String host = "localhost";
private static final int port = 4223;

If the WIFI Extension is used or if the Brick Daemon is running on a different PC, you have to exchange "localhost" with the IP address or hostname of the WIFI Extension or PC.

When the program is started, we need to register the EnumerateListener listener and the ConnectedListener listener and trigger a first enumerate:

public static void main(String args[]) {
    ipcon = new IPConnection();
    ipcon.connect(host, port);

    weatherListener = new WeatherListener(ipcon);
    ipcon.addEnumerateListener(weatherListener);
    ipcon.addConnectedListener(weatherListener);

    ipcon.enumerate();
}

The enumerate callback is triggered if a Brick gets connected over USB or if the enumerate() function is called. This allows to discover the Bricks and Bricklets in a stack without knowing their types or UIDs beforehand.

The connected callback is triggered if the connection to the WIFI Extension or to the Brick Daemon got established. In this callback we need to trigger the enumerate again, if the reason is an auto reconnect:

class WeatherListener implements IPConnection.EnumerateListener,
                                 IPConnection.ConnectedListener {
    public void connected(short connectedReason) {
        if(connectedReason == IPConnection.CONNECT_REASON_AUTO_RECONNECT) {
            ipcon.enumerate();
        }
    }
}

An auto reconnect means, that the connection to the WIFI Extension or to the Brick Daemon was lost and could subsequently be established again. In this case the Bricklets may have lost their configurations and we have to reconfigure them. Since the configuration is done during the enumeration process (see below), we have to trigger another enumeration.

Step 1 put together:

class WeatherListener implements IPConnection.EnumerateListener,
                                 IPConnection.ConnectedListener {
    private IPConnection ipcon = null;

    public WeatherListener(IPConnection ipcon) {
        this.ipcon = ipcon;
    }

    public void connected(short connectedReason) {
        if(connectedReason == IPConnection.CONNECT_REASON_AUTO_RECONNECT) {
            ipcon.enumerate();
        }
    }
}

public class WeatherStation {
    private static final String host = "localhost";
    private static final int port = 4223;
    private static IPConnection ipcon = null;
    private static WeatherListener weatherListener = null;

    public static void main(String args[]) {
        ipcon = new IPConnection();
        ipcon.connect(host, port);

        weatherListener = new WeatherListener(ipcon);
        ipcon.addEnumerateListener(weatherListener);
        ipcon.addConnectedListener(weatherListener);

        ipcon.enumerate();
    }
}

Step 2: Initialize Bricklets on Enumeration

During the enumeration we want to configure all of the weather measuring Bricklets. Doing this during the enumeration ensures that Bricklets get reconfigured if the stack was disconnected or there was a power loss.

The configurations should be performed on first startup (ENUMERATION_TYPE_CONNECTED) as well as whenever the enumeration is triggered externally by us (ENUMERATION_TYPE_AVAILABLE):

public void enumerate(String uid, String connectedUid, char position,
                      short[] hardwareVersion, short[] firmwareVersion,
                      int deviceIdentifier, short enumerationType) {
    if(enumerationType == IPConnection.ENUMERATION_TYPE_CONNECTED ||
       enumerationType == IPConnection.ENUMERATION_TYPE_AVAILABLE) {

The LCD 20x4 configuration is simple, we want the current text cleared and we want the backlight on:

if(deviceIdentifier == BrickletLCD20x4.DEVICE_IDENTIFIER) {
    brickletLCD = new BrickletLCD20x4(uid, ipcon);
    brickletLCD.clearDisplay();
    brickletLCD.backlightOn();
}

We configure the Ambient Light, Humidity and Barometer Bricklet to return their respective measurements continuously with a period of 1000ms (1s):

  else if(deviceIdentifier == BrickletAmbientLight.DEVICE_IDENTIFIER) {
    brickletAmbientLight = new BrickletAmbientLight(uid, ipcon);
    brickletAmbientLight.setIlluminanceCallbackPeriod(1000);
    brickletAmbientLight.addIlluminanceListener(this);
} else if(deviceIdentifier == BrickletHumidity.DEVICE_IDENTIFIER) {
    brickletHumidity = new BrickletHumidity(uid, ipcon);
    brickletHumidity.setHumidityCallbackPeriod(1000);
    brickletHumidity.addHumidityListener(this);
} else if(deviceIdentifier == BrickletBarometer.DEVICE_IDENTIFIER) {
    brickletBarometer = new BrickletBarometer(uid, ipcon);
    brickletBarometer.setAirPressureCallbackPeriod(1000);
    brickletBarometer.addAirPressureListener(this);
}

This means that the Bricklets will call the illuminance, humidity and airPressure callback functions whenever the value has changed, but with a maximum period of 1000ms.

Step 2 put together:

public void enumerate(String uid, String connectedUid, char position,
                      short[] hardwareVersion, short[] firmwareVersion,
                      int deviceIdentifier, short enumerationType) {
    if(enumerationType == IPConnection.ENUMERATION_TYPE_CONNECTED ||
       enumerationType == IPConnection.ENUMERATION_TYPE_AVAILABLE) {
        if(deviceIdentifier == BrickletLCD20x4.DEVICE_IDENTIFIER) {
            brickletLCD = new BrickletLCD20x4(uid, ipcon);
            brickletLCD.clearDisplay();
            brickletLCD.backlightOn();
        } else if(deviceIdentifier == BrickletAmbientLight.DEVICE_IDENTIFIER) {
            brickletAmbientLight = new BrickletAmbientLight(uid, ipcon);
            brickletAmbientLight.setIlluminanceCallbackPeriod(1000);
            brickletAmbientLight.addIlluminanceListener(this);
        } else if(deviceIdentifier == BrickletHumidity.DEVICE_IDENTIFIER) {
            brickletHumidity = new BrickletHumidity(uid, ipcon);
            brickletHumidity.setHumidityCallbackPeriod(1000);
            brickletHumidity.addHumidityListener(this);
        } else if(deviceIdentifier == BrickletBarometer.DEVICE_IDENTIFIER) {
            brickletBarometer = new BrickletBarometer(uid, ipcon);
            brickletBarometer.setAirPressureCallbackPeriod(1000);
            brickletBarometer.addAirPressureListener(this);
        }
    }
}

Step 3: Show measurements on display

We want a neat arrangement of the measurements on the display, such as:

Illuminanc 137.39 lx
Humidity    34.10 %
Air Press  987.70 mb
Temperature 22.64 °C

The decimal marks and the units should be below each other. To achieve this we use two characters for the unit, two decimal places and crop the name to use the maximum characters that are left. That's why "Illuminanc" is missing its final "e".

String text = String.format("%6.2f", value);

The code above converts a floating point value to a string according to the given format specification. The result will be at least 6 characters long with 2 decimal places, filled up with spaces from the left if it would be shorter than 6 characters otherwise.

public void illuminance(int illuminance) {
    String text = String.format("Illuminanc %6.2f lx", illuminance/10.0);
    brickletLCD.writeLine((short)0, (short)0, text);
}

public void humidity(int humidity) {
    String text = String.format("Humidity   %6.2f %%", humidity/10.0);
    brickletLCD.writeLine((short)1, (short)0, text);
}

public void airPressure(int airPressure) {
    String text = String.format("Air Press %7.2f mb", airPressure/1000.0);
    brickletLCD.writeLine((short)2, (short)0, text);
}

We are still missing the temperature. The Barometer Bricklet can measure temperature, but it doesn't have a callback for it. As a simple workaround we can retrieve the temperature in the airPressure callback function:

public void airPressure(int airPressure) {
    String text = String.format("Air Press %7.2f mb", airPressure/1000.0);
    brickletLCD.writeLine((short)2, (short)0, text);

    int temperature = brickletBarometer.getChipTemperature();
    text = String.format("Temperature %5.2f %cC", temperature/100.0, 0xDF);
    brickletLCD.writeLine((short)3, (short)0, text);
}

Step 3 put together:

public void illuminance(int illuminance) {
    String text = String.format("Illuminanc %6.2f lx", illuminance/10.0);
    brickletLCD.writeLine((short)0, (short)0, text);
}

public void humidity(int humidity) {
    String text = String.format("Humidity   %6.2f %%", humidity/10.0);
    brickletLCD.writeLine((short)1, (short)0, text);
}

public void airPressure(int airPressure) {
    String text = String.format("Air Press %7.2f mb", airPressure/1000.0);
    brickletLCD.writeLine((short)2, (short)0, text);

    int temperature = brickletBarometer.getChipTemperature();
    // 0xDF == ° on LCD 20x4 charset
    text = String.format("Temperature %5.2f %cC", temperature/100.0, 0xDF);
    brickletLCD.writeLine((short)3, (short)0, text);
}

That's it. If we would copy these three steps together in one file and execute it, we would have a working Weather Station!

There are some obvious ways to make the output better. The name could be cropped according to the exact space that is available (depending on the number of digits of the measured value). Also, reading the temperature in the airPressure callback function is suboptimal. If the air pressure doesn't change, we won't update the temperature. It would be better to read the temperature in a different thread in an endless loop with a one second sleep after each read. But we want to keep this code as simple as possible.

However, we do not meet all of our goals yet. The program is not yet robust enough. What happens if it can't connect on startup? What happens if the enumerate after an auto reconnect doesn't work?

What we need is error handling!

Step 4: Error handling and Logging

On startup, we need to try to connect until the connection works:

while(true) {
    try {
        ipcon.connect(host, port);
        break;
    } catch(java.net.UnknownHostException e) {
    } catch(java.io.IOException e) {
    } catch(com.tinkerforge.AlreadyConnectedException e) {
    }

    try {
        Thread.sleep(1000);
    } catch(InterruptedException ei) {
    }
}

and we need to try enumerating until the message goes through:

while(true) {
    try {
        ipcon.enumerate();
        break;
    } catch(com.tinkerforge.NotConnectedException e) {
    }

    try {
        Thread.sleep(1000);
    } catch(InterruptedException ei) {
    }
}

With these changes it is now possible to first start the program and connect the Weather Station afterwards.

We also need to make sure, that we only write to the LCD if it is already initialized:

public void illuminance(int illuminance) {
    if(brickletLCD != null) {
        String text = String.format("Illuminanc %6.2f lx", illuminance/10.0);
        try {
            brickletLCD.writeLine((short)0, (short)0, text);
        } catch(com.tinkerforge.TinkerforgeException e) {
        }

        System.out.println("Write to line 0: " + text);
    }
}

and that we have to deal with errors during the initialization:

if(deviceIdentifier == BrickletAmbientLight.DEVICE_IDENTIFIER) {
    try {
        brickletAmbientLight = new BrickletAmbientLight(uid, ipcon);
        brickletAmbientLight.setIlluminanceCallbackPeriod(1000);
        brickletAmbientLight.addIlluminanceListener(this);
        System.out.println("Ambient Light initialized");
    } catch(com.tinkerforge.TinkerforgeException e) {
        brickletAmbientLight = null;
        System.out.println("Ambient Light init failed: " + e);
    }
}

Additionally we added some logging. With the logging we can later find out what exactly caused a problem, if the Weather Station failed for some time period.

For example, if we connect to the Weather Station via Wi-Fi and we have regular auto reconnects, it likely means that the Wi-Fi connection is not very stable.

Step 5: Everything put together

That's it! We are already done with our Weather Station and all of the goals should be met.

Now all of the above put together (download):

import com.tinkerforge.IPConnection;
import com.tinkerforge.BrickletLCD20x4;
import com.tinkerforge.BrickletAmbientLight;
import com.tinkerforge.BrickletAmbientLightV2;
import com.tinkerforge.BrickletAmbientLightV3;
import com.tinkerforge.BrickletHumidity;
import com.tinkerforge.BrickletHumidityV2;
import com.tinkerforge.BrickletBarometer;
import com.tinkerforge.BrickletBarometerV2;

class WeatherListener implements IPConnection.EnumerateListener,
                                 IPConnection.ConnectedListener,
                                 BrickletAmbientLight.IlluminanceListener,
                                 BrickletAmbientLightV2.IlluminanceListener,
                                 BrickletAmbientLightV3.IlluminanceListener,
                                 BrickletHumidity.HumidityListener,
                                 BrickletHumidityV2.HumidityListener,
                                 BrickletBarometer.AirPressureListener,
                                 BrickletBarometerV2.AirPressureListener {
    private IPConnection ipcon = null;
    private BrickletLCD20x4 brickletLCD = null;
    private BrickletAmbientLight brickletAmbientLight = null;
    private BrickletAmbientLightV2 brickletAmbientLightV2 = null;
    private BrickletAmbientLightV3 brickletAmbientLightV3 = null;
    private BrickletHumidity brickletHumidity = null;
    private BrickletHumidityV2 brickletHumidityV2 = null;
    private BrickletBarometer brickletBarometer = null;
    private BrickletBarometerV2 brickletBarometerV2 = null;

    public WeatherListener(IPConnection ipcon) {
        this.ipcon = ipcon;
    }

    public void illuminance(int illuminance) {
        if(brickletLCD != null) {
            String text = String.format("Illuminanc %6.2f lx", illuminance/10.0);

            try {
                brickletLCD.writeLine((short)0, (short)0, text);
            } catch(com.tinkerforge.TinkerforgeException e) {
            }

            System.out.println("Write to line 0: " + text);
        }
    }

    public void illuminance(long illuminance) {
        if(brickletLCD != null) {
            String text = String.format("Illumina %8.2f lx", illuminance/100.0);

            try {
                brickletLCD.writeLine((short)0, (short)0, text);
            } catch(com.tinkerforge.TinkerforgeException e) {
            }

            System.out.println("Write to line 0: " + text);
        }
    }

    public void humidity(int humidity) {
        if(brickletLCD != null) {
            float factor = 10.0f;

            if (brickletHumidityV2 != null) {
                factor = 100.0f; // FIXME: assuming that only one Humiditiy Bricklet (2.0) is connected
            }

            String text = String.format("Humidity   %6.2f %%", humidity/factor);

            try {
                brickletLCD.writeLine((short)1, (short)0, text);
            } catch(com.tinkerforge.TinkerforgeException e) {
            }

            System.out.println("Write to line 1: " + text);
        }
    }

    public void airPressure(int airPressure) {
        if(brickletLCD != null) {
            String text = String.format("Air Press %7.2f mb", airPressure/1000.0);
            try {
                brickletLCD.writeLine((short)2, (short)0, text);
            } catch(com.tinkerforge.TinkerforgeException e) {
            }

            System.out.println("Write to line 2: " + text);

            int temperature;
            try {
                if (brickletBarometerV2 != null) {
                    temperature = brickletBarometerV2.getTemperature();
                }
                else {
                    temperature = brickletBarometer.getChipTemperature();
                }
            } catch(com.tinkerforge.TinkerforgeException e) {
                System.out.println("Could not get temperature: " + e);
                return;
            }

            // 0xDF == ° on LCD 20x4 charset
            text = String.format("Temperature %5.2f %cC", temperature/100.0, 0xDF);
            try {
                brickletLCD.writeLine((short)3, (short)0, text);
            } catch(com.tinkerforge.TinkerforgeException e) {
            }

            System.out.println("Write to line 3: " + text.replace((char)0xDF, '°'));
        }
    }

    public void enumerate(String uid, String connectedUid, char position,
                          short[] hardwareVersion, short[] firmwareVersion,
                          int deviceIdentifier, short enumerationType) {
        if(enumerationType == IPConnection.ENUMERATION_TYPE_CONNECTED ||
           enumerationType == IPConnection.ENUMERATION_TYPE_AVAILABLE) {
            if(deviceIdentifier == BrickletLCD20x4.DEVICE_IDENTIFIER) {
                try {
                    brickletLCD = new BrickletLCD20x4(uid, ipcon);
                    brickletLCD.clearDisplay();
                    brickletLCD.backlightOn();
                    System.out.println("LCD 20x4 initialized");
                } catch(com.tinkerforge.TinkerforgeException e) {
                    brickletLCD = null;
                    System.out.println("LCD 20x4 init failed: " + e);
                }
            } else if(deviceIdentifier == BrickletAmbientLight.DEVICE_IDENTIFIER) {
                try {
                    brickletAmbientLight = new BrickletAmbientLight(uid, ipcon);
                    brickletAmbientLight.setIlluminanceCallbackPeriod(1000);
                    brickletAmbientLight.addIlluminanceListener(this);
                    System.out.println("Ambient Light initialized");
                } catch(com.tinkerforge.TinkerforgeException e) {
                    brickletAmbientLight = null;
                    System.out.println("Ambient Light init failed: " + e);
                }
            } else if(deviceIdentifier == BrickletAmbientLightV2.DEVICE_IDENTIFIER) {
                try {
                    brickletAmbientLightV2 = new BrickletAmbientLightV2(uid, ipcon);
                    brickletAmbientLightV2.setConfiguration(BrickletAmbientLightV2.ILLUMINANCE_RANGE_64000LUX,
                                                            BrickletAmbientLightV2.INTEGRATION_TIME_200MS);
                    brickletAmbientLightV2.setIlluminanceCallbackPeriod(1000);
                    brickletAmbientLightV2.addIlluminanceListener(this);
                    System.out.println("Ambient Light 2.0 initialized");
                } catch(com.tinkerforge.TinkerforgeException e) {
                    brickletAmbientLightV2 = null;
                    System.out.println("Ambient Light 2.0 init failed: " + e);
                }
            } else if(deviceIdentifier == BrickletAmbientLightV3.DEVICE_IDENTIFIER) {
                try {
                    brickletAmbientLightV3 = new BrickletAmbientLightV3(uid, ipcon);
                    brickletAmbientLightV3.setConfiguration(BrickletAmbientLightV3.ILLUMINANCE_RANGE_64000LUX,
                                                            BrickletAmbientLightV3.INTEGRATION_TIME_200MS);
                    brickletAmbientLightV3.setIlluminanceCallbackConfiguration(1000, false, 'x', 0, 0);
                    brickletAmbientLightV3.addIlluminanceListener(this);
                    System.out.println("Ambient Light 3.0 initialized");
                } catch(com.tinkerforge.TinkerforgeException e) {
                    brickletAmbientLightV3 = null;
                    System.out.println("Ambient Light 3.0 init failed: " + e);
                }
            } else if(deviceIdentifier == BrickletHumidity.DEVICE_IDENTIFIER) {
                try {
                    brickletHumidity = new BrickletHumidity(uid, ipcon);
                    brickletHumidity.setHumidityCallbackPeriod(1000);
                    brickletHumidity.addHumidityListener(this);
                    System.out.println("Humidity initialized");
                } catch(com.tinkerforge.TinkerforgeException e) {
                    brickletHumidity = null;
                    System.out.println("Humidity init failed: " + e);
                }
            } else if(deviceIdentifier == BrickletHumidityV2.DEVICE_IDENTIFIER) {
                try {
                    brickletHumidityV2 = new BrickletHumidityV2(uid, ipcon);
                    brickletHumidityV2.setHumidityCallbackConfiguration(1000, true, 'x', 0, 0);
                    brickletHumidityV2.addHumidityListener(this);
                    System.out.println("Humidity 2.0 initialized");
                } catch(com.tinkerforge.TinkerforgeException e) {
                    brickletHumidityV2 = null;
                    System.out.println("Humidity 2.0 init failed: " + e);
                }
            } else if(deviceIdentifier == BrickletBarometer.DEVICE_IDENTIFIER) {
                try {
                    brickletBarometer = new BrickletBarometer(uid, ipcon);
                    brickletBarometer.setAirPressureCallbackPeriod(1000);
                    brickletBarometer.addAirPressureListener(this);
                    System.out.println("Barometer initialized");
                } catch(com.tinkerforge.TinkerforgeException e) {
                    brickletBarometer = null;
                    System.out.println("Barometer init failed: " + e);
                }
            } else if(deviceIdentifier == BrickletBarometerV2.DEVICE_IDENTIFIER) {
                try {
                    brickletBarometerV2 = new BrickletBarometerV2(uid, ipcon);
                    brickletBarometerV2.setAirPressureCallbackConfiguration(1000, false, 'x', 0, 0);
                    brickletBarometerV2.addAirPressureListener(this);
                    System.out.println("Barometer 2.0 initialized");
                } catch(com.tinkerforge.TinkerforgeException e) {
                    brickletBarometerV2 = null;
                    System.out.println("Barometer 2.0 init failed: " + e);
                }
            }
        }
    }

    public void connected(short connectedReason) {
        if(connectedReason == IPConnection.CONNECT_REASON_AUTO_RECONNECT) {
            System.out.println("Auto Reconnect");

            while(true) {
                try {
                    ipcon.enumerate();
                    break;
                } catch(com.tinkerforge.NotConnectedException e) {
                }

                try {
                    Thread.sleep(1000);
                } catch(InterruptedException ei) {
                }
            }
        }
    }
}

public class WeatherStation {
    private static final String HOST = "localhost";
    private static final int PORT = 4223;
    private static IPConnection ipcon = null;
    private static WeatherListener weatherListener = null;

    public static void main(String args[]) {
        ipcon = new IPConnection();

        while(true) {
            try {
                ipcon.connect(HOST, PORT);
                break;
            } catch(com.tinkerforge.TinkerforgeException e) {
            }

            try {
                Thread.sleep(1000);
            } catch(InterruptedException ei) {
            }
        }

        weatherListener = new WeatherListener(ipcon);
        ipcon.addEnumerateListener(weatherListener);
        ipcon.addConnectedListener(weatherListener);

        while(true) {
            try {
                ipcon.enumerate();
                break;
            } catch(com.tinkerforge.NotConnectedException e) {
            }

            try {
                Thread.sleep(1000);
            } catch(InterruptedException ei) {
            }
        }

        try {
            System.out.println("Press key to exit"); System.in.read();
        } catch(java.io.IOException e) {
        }

        try {
            ipcon.disconnect();
        } catch(com.tinkerforge.NotConnectedException e) {
        }
    }
}