Using Python to write to LCD 20x4 Bricklet

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

If you are totally new to Python 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:

HOST = "localhost"
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 CALLBACK_ENUMERATE callback and the CALLBACK_CONNECTED callback and trigger a first enumerate:

def __init__(self):
    self.ipcon = IPConnection()
    self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT)

    self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                 self.cb_enumerate)
    self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                 self.cb_connected)

    self.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:

def cb_connected(self, connected_reason):
    if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
        self.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 WeatherStation:
    HOST = "localhost"
    PORT = 4223

    def __init__(self):
        self.ipcon = IPConnection()
        self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT)

        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.cb_connected)

        self.ipcon.enumerate()

    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
            self.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):

def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                 firmware_version, device_identifier, enumeration_type):
    if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
       enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:

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

if device_identifier == LCD20x4.DEVICE_IDENTIFIER:
    self.lcd = LCD20x4(uid, self.ipcon)
    self.lcd.clear_display()
    self.lcd.backlight_on()

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

elif device_identifier == AmbientLight.DEVICE_IDENTIFIER:
    self.al = AmbientLight(uid, self.ipcon)
    self.al.set_illuminance_callback_period(1000)
    self.al.register_callback(self.al.CALLBACK_ILLUMINANCE,
                              self.cb_illuminance)
elif device_identifier == Humidity.DEVICE_IDENTIFIER:
    self.hum = Humidity(uid, self.ipcon)
    self.hum.set_humidity_callback_period(1000)
    self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                               self.cb_humidity)
elif device_identifier == Barometer.DEVICE_IDENTIFIER:
    self.baro = Barometer(uid, self.ipcon)
    self.baro.set_air_pressure_callback_period(1000)
    self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE,
                                self.cb_air_pressure)

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

Step 2 put together:

def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                 firmware_version, device_identifier, enumeration_type):
    if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
       enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
        if device_identifier == LCD20x4.DEVICE_IDENTIFIER:
            self.lcd = LCD20x4(uid, self.ipcon)
            self.lcd.clear_display()
            self.lcd.backlight_on()
        elif device_identifier == AmbientLight.DEVICE_IDENTIFIER:
            self.al = AmbientLight(uid, self.ipcon)
            self.al.set_illuminance_callback_period(1000)
            self.al.register_callback(self.al.CALLBACK_ILLUMINANCE,
                                      self.cb_illuminance)
        elif device_identifier == Humidity.DEVICE_IDENTIFIER:
            self.hum = Humidity(uid, self.ipcon)
            self.hum.set_humidity_callback_period(1000)
            self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                       self.cb_humidity)
        elif device_identifier == Barometer.DEVICE_IDENTIFIER:
            self.baro = Barometer(uid, self.ipcon)
            self.baro.set_air_pressure_callback_period(1000)
            self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE,
                                        self.cb_air_pressure)

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".

text = '%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.

def cb_illuminance(self, illuminance):
    text = 'Illuminanc %6.2f lx' % (illuminance/10.0)
    self.lcd.write_line(0, 0, text)

def cb_humidity(self, humidity):
    text = 'Humidity   %6.2f %%' % (humidity/10.0)
    self.lcd.write_line(1, 0, text)

def cb_air_pressure(self, air_pressure):
    text = 'Air Press %7.2f mb' % (air_pressure/1000.0)
    self.lcd.write_line(2, 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 cb_air_pressure callback function:

def cb_air_pressure(self, air_pressure):
    text = 'Air Press %7.2f mb' % (air_pressure/1000.0)
    self.lcd.write_line(2, 0, text)

    # \xDF == ° on LCD 20x4 charset
    text = 'Temperature %5.2f \xDFC' % (self.baro.get_chip_temperature()/100.0)
    self.lcd.write_line(3, 0, text)

Step 3 put together:

def cb_illuminance(self, illuminance):
    text = 'Illuminanc %6.2f lx' % (illuminance/10.0)
    self.lcd.write_line(0, 0, text)

def cb_humidity(self, humidity):
    text = 'Humidity   %6.2f %%' % (humidity/10.0)
    self.lcd.write_line(1, 0, text)

def cb_air_pressure(self, air_pressure):
    text = 'Air Press %7.2f mb' % (air_pressure/1000.0)
    self.lcd.write_line(2, 0, text)

    # \xDF == ° on LCD 20x4 charset
    text = 'Temperature %5.2f \xDFC' % (self.baro.get_chip_temperature()/100.0)
    self.lcd.write_line(3, 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 cb_air_pressure 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:
        self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT)
        break
    except Error as e:
        log.error('Connection Error: ' + str(e.description))
        time.sleep(1)
    except socket.error as e:
        log.error('Socket error: ' + str(e))
        time.sleep(1)

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

while True:
    try:
        self.ipcon.enumerate()
        break
    except Error as e:
        log.error('Enumerate Error: ' + str(e.description))
        time.sleep(1)

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:

def cb_illuminance(self, illuminance):
    if self.lcd is not None:
        text = 'Illuminanc %6.2f lx' % (illuminance/10.0)
        self.lcd.write_line(0, 0, text)
        log.info('Write to line 0: ' + text)

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

if device_identifier == AmbientLight.DEVICE_IDENTIFIER:
    try:
        self.al = AmbientLight(uid, self.ipcon)
        self.al.set_illuminance_callback_period(1000)
        self.al.register_callback(self.al.CALLBACK_ILLUMINANCE,
                                  self.cb_illuminance)
        log.info('Ambient Light initialized')
    except Error as e:
        log.error('Ambient Light init failed: ' + str(e.description))
        self.al = None

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import sys
import time
import math
import logging as log
log.basicConfig(level=log.INFO)

from tinkerforge.ip_connection import IPConnection
from tinkerforge.ip_connection import Error
from tinkerforge.bricklet_lcd_20x4 import BrickletLCD20x4
from tinkerforge.bricklet_ambient_light import BrickletAmbientLight
from tinkerforge.bricklet_ambient_light_v2 import BrickletAmbientLightV2
from tinkerforge.bricklet_ambient_light_v3 import BrickletAmbientLightV3
from tinkerforge.bricklet_humidity import BrickletHumidity
from tinkerforge.bricklet_humidity_v2 import BrickletHumidityV2
from tinkerforge.bricklet_barometer import BrickletBarometer
from tinkerforge.bricklet_barometer_v2 import BrickletBarometerV2

class WeatherStation:
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    al = None
    al_v2 = None
    al_v3 = None
    hum = None
    hum_v2 = None
    baro = None
    baro_v2 = None

    def __init__(self):
        self.ipcon = IPConnection()
        while True:
            try:
                self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT)
                break
            except Error as e:
                log.error('Connection Error: ' + str(e.description))
                time.sleep(1)
            except socket.error as e:
                log.error('Socket error: ' + str(e))
                time.sleep(1)

        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.cb_connected)

        while True:
            try:
                self.ipcon.enumerate()
                break
            except Error as e:
                log.error('Enumerate Error: ' + str(e.description))
                time.sleep(1)

    def cb_illuminance(self, illuminance):
        if self.lcd is not None:
            text = 'Illuminanc %6.2f lx' % (illuminance/10.0)
            self.lcd.write_line(0, 0, text)
            log.info('Write to line 0: ' + text)

    def cb_illuminance_v2(self, illuminance):
        if self.lcd is not None:
            text = 'Illumina %8.2f lx' % (illuminance/100.0)
            self.lcd.write_line(0, 0, text)
            log.info('Write to line 0: ' + text)

    def cb_illuminance_v3(self, illuminance):
        if self.lcd is not None:
            text = 'Illumina %8.2f lx' % (illuminance/100.0)
            self.lcd.write_line(0, 0, text)
            log.info('Write to line 0: ' + text)

    def cb_humidity(self, humidity):
        if self.lcd is not None:
            text = 'Humidity   %6.2f %%' % (humidity/10.0)
            self.lcd.write_line(1, 0, text)
            log.info('Write to line 1: ' + text)

    def cb_humidity_v2(self, humidity):
        if self.lcd is not None:
            text = 'Humidity   %6.2f %%' % (humidity/100.0)
            self.lcd.write_line(1, 0, text)
            log.info('Write to line 1: ' + text)

    def cb_air_pressure(self, air_pressure):
        if self.lcd is not None:
            text = 'Air Press %7.2f mb' % (air_pressure/1000.0)
            self.lcd.write_line(2, 0, text)
            log.info('Write to line 2: ' + text)

            try:
                temperature = self.baro.get_chip_temperature()
            except Error as e:
                log.error('Could not get temperature: ' + str(e.description))
                return

            # \xDF == ° on LCD 20x4 charset
            text = 'Temperature %5.2f \xDFC' % (temperature/100.0)
            self.lcd.write_line(3, 0, text)
            log.info('Write to line 3: ' + text.replace('\xDF', '°'))

    def cb_air_pressure_v2(self, air_pressure):
        if self.lcd is not None:
            text = 'Air Press %7.2f mb' % (air_pressure/1000.0)
            self.lcd.write_line(2, 0, text)
            log.info('Write to line 2: ' + text)

            try:
                temperature = self.baro_v2.get_temperature()
            except Error as e:
                log.error('Could not get temperature: ' + str(e.description))
                return

            # \xDF == ° on LCD 20x4 charset
            text = 'Temperature %5.2f \xDFC' % (temperature/100.0)
            self.lcd.write_line(3, 0, text)
            log.info('Write to line 3: ' + text.replace('\xDF', '°'))

    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            if device_identifier == BrickletLCD20x4.DEVICE_IDENTIFIER:
                try:
                    self.lcd = BrickletLCD20x4(uid, self.ipcon)
                    self.lcd.clear_display()
                    self.lcd.backlight_on()
                    log.info('LCD 20x4 initialized')
                except Error as e:
                    log.error('LCD 20x4 init failed: ' + str(e.description))
                    self.lcd = None
            elif device_identifier == BrickletAmbientLight.DEVICE_IDENTIFIER:
                try:
                    self.al = BrickletAmbientLight(uid, self.ipcon)
                    self.al.set_illuminance_callback_period(1000)
                    self.al.register_callback(self.al.CALLBACK_ILLUMINANCE,
                                              self.cb_illuminance)
                    log.info('Ambient Light initialized')
                except Error as e:
                    log.error('Ambient Light init failed: ' + str(e.description))
                    self.al = None
            elif device_identifier == BrickletAmbientLightV2.DEVICE_IDENTIFIER:
                try:
                    self.al_v2 = BrickletAmbientLightV2(uid, self.ipcon)
                    self.al_v2.set_configuration(self.al_v2.ILLUMINANCE_RANGE_64000LUX,
                                                 self.al_v2.INTEGRATION_TIME_200MS)
                    self.al_v2.set_illuminance_callback_period(1000)
                    self.al_v2.register_callback(self.al_v2.CALLBACK_ILLUMINANCE,
                                                 self.cb_illuminance_v2)
                    log.info('Ambient Light 2.0 initialized')
                except Error as e:
                    log.error('Ambient Light 2.0 init failed: ' + str(e.description))
                    self.al_v2 = None
            elif device_identifier == BrickletAmbientLightV3.DEVICE_IDENTIFIER:
                try:
                    self.al_v3 = BrickletAmbientLightV3(uid, self.ipcon)
                    self.al_v3.set_configuration(self.al_v3.ILLUMINANCE_RANGE_64000LUX,
                                                 self.al_v3.INTEGRATION_TIME_200MS)
                    self.al_v3.set_illuminance_callback_configuration(1000, False, 'x', 0, 0)
                    self.al_v3.register_callback(self.al_v3.CALLBACK_ILLUMINANCE,
                                                 self.cb_illuminance_v3)
                    log.info('Ambient Light 3.0 initialized')
                except Error as e:
                    log.error('Ambient Light 3.0 init failed: ' + str(e.description))
                    self.al_v3 = None
            elif device_identifier == BrickletHumidity.DEVICE_IDENTIFIER:
                try:
                    self.hum = BrickletHumidity(uid, self.ipcon)
                    self.hum.set_humidity_callback_period(1000)
                    self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                               self.cb_humidity)
                    log.info('Humidity initialized')
                except Error as e:
                    log.error('Humidity init failed: ' + str(e.description))
                    self.hum = None
            elif device_identifier == BrickletHumidityV2.DEVICE_IDENTIFIER:
                try:
                    self.hum_v2 = BrickletHumidityV2(uid, self.ipcon)
                    self.hum_v2.set_humidity_callback_configuration(1000, True, 'x', 0, 0)
                    self.hum_v2.register_callback(self.hum_v2.CALLBACK_HUMIDITY,
                                                  self.cb_humidity_v2)
                    log.info('Humidity 2.0 initialized')
                except Error as e:
                    log.error('Humidity 2.0 init failed: ' + str(e.description))
                    self.hum_v2 = None
            elif device_identifier == BrickletBarometer.DEVICE_IDENTIFIER:
                try:
                    self.baro = BrickletBarometer(uid, self.ipcon)
                    self.baro.set_air_pressure_callback_period(1000)
                    self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE,
                                                self.cb_air_pressure)
                    log.info('Barometer initialized')
                except Error as e:
                    log.error('Barometer init failed: ' + str(e.description))
                    self.baro = None
            elif device_identifier == BrickletBarometerV2.DEVICE_IDENTIFIER:
                try:
                    self.baro_v2 = BrickletBarometerV2(uid, self.ipcon)
                    self.baro_v2.set_air_pressure_callback_configuration(1000, False, 'x', 0, 0)
                    self.baro_v2.register_callback(self.baro_v2.CALLBACK_AIR_PRESSURE,
                                                   self.cb_air_pressure_v2)
                    log.info('Barometer initialized')
                except Error as e:
                    log.error('Barometer init failed: ' + str(e.description))
                    self.baro_v2 = None

    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
            log.info('Auto Reconnect')

            while True:
                try:
                    self.ipcon.enumerate()
                    break
                except Error as e:
                    log.error('Enumerate Error: ' + str(e.description))
                    time.sleep(1)

if __name__ == "__main__":
    log.info('Weather Station: Start')

    weather_station = WeatherStation()

    if sys.version_info < (3, 0):
        input = raw_input # Compatibility for Python 2.x
    input('Press key to exit\n')

    if weather_station.ipcon != None:
        weather_station.ipcon.disconnect()

    log.info('Weather Station: End')