Using PHP to write to LCD 20x4 Bricklet

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

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

<?php

const HOST = 'localhost';
const 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:

<?php

public function __construct()
{
    $this->ipcon = new IPConnection();
    $this->ipcon->connect(self::HOST, self::PORT);

    $this->ipcon->registerCallback(IPConnection::CALLBACK_ENUMERATE,
                                   array($this, 'cb_enumerate'));
    $this->ipcon->registerCallback(IPConnection::CALLBACK_CONNECTED,
                                   array($this, 'cb_connected'));

    $this->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:

<?php

function cb_connected($connectedReason)
{
    if($connectedReason == IPConnection::CONNECT_REASON_AUTO_RECONNECT) {
        $this->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:

<?php

class WeatherStation
{
    const HOST = 'localhost';
    const PORT = 4223;

    public function __construct()
    {
        $this->ipcon = new IPConnection();
        $this->ipcon->connect(self::HOST, self::PORT);

        $this->ipcon->registerCallback(IPConnection::CALLBACK_ENUMERATE,
                                       array($this, 'cb_enumerate'));
        $this->ipcon->registerCallback(IPConnection::CALLBACK_CONNECTED,
                                       array($this, 'cb_connected'));

        $this->ipcon->enumerate();
    }

    function cb_connected($connectedReason)
    {
        if($connectedReason == IPConnection::CONNECT_REASON_AUTO_RECONNECT) {
            $this->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):

<?php

function cb_enumerate($uid, $connectedUid, $position, $hardwareVersion,
                      $firmwareVersion, $deviceIdentifier, $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:

<?php

if($deviceIdentifier == BrickletLCD20x4::DEVICE_IDENTIFIER) {
    $this->brickletLCD = new BrickletLCD20x4($uid, $this->ipcon);
    $this->brickletLCD->clearDisplay();
    $this->brickletLCD->backlightOn();
}

?>

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

<?php

else if($deviceIdentifier == BrickletAmbientLight::DEVICE_IDENTIFIER) {
    $this->brickletAmbientLight = new BrickletAmbientLight($uid, $this->ipcon);
    $this->brickletAmbientLight->setIlluminanceCallbackPeriod(1000);
    $this->brickletAmbientLight->registerCallback(BrickletAmbientLight::CALLBACK_ILLUMINANCE,
                                                  array($this, 'cb_illuminance'));
} else if($deviceIdentifier == BrickletHumidity::DEVICE_IDENTIFIER) {
    $this->brickletHumidity = new BrickletHumidity($uid, $this->ipcon);
    $this->brickletHumidity->setHumidityCallbackPeriod(1000);
    $this->brickletHumidity->registerCallback(BrickletHumidity::CALLBACK_HUMIDITY,
                                              array($this, 'cb_humidity'));
} else if($deviceIdentifier == BrickletBarometer::DEVICE_IDENTIFIER) {
    $this->brickletBarometer = new BrickletBarometer($uid, $this->ipcon);
    $this->brickletBarometer->setAirPressureCallbackPeriod(1000);
    $this->brickletBarometer->registerCallback(BrickletBarometer::CALLBACK_AIR_PRESSURE,
                                               array($this, 'cb_airPressure'));
}

?>

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

Step 2 put together:

<?php

function cb_enumerate($uid, $connectedUid, $position, $hardwareVersion,
                      $firmwareVersion, $deviceIdentifier, $enumerationType)
{
    if($enumerationType == IPConnection::ENUMERATION_TYPE_CONNECTED ||
       $enumerationType == IPConnection::ENUMERATION_TYPE_AVAILABLE) {
        if($deviceIdentifier == BrickletLCD20x4::DEVICE_IDENTIFIER) {
            $this->brickletLCD = new BrickletLCD20x4($uid, $this->ipcon);
            $this->brickletLCD->clearDisplay();
            $this->brickletLCD->backlightOn();
        } else if($deviceIdentifier == BrickletAmbientLight::DEVICE_IDENTIFIER) {
            $this->brickletAmbientLight = new BrickletAmbientLight($uid, $this->ipcon);
            $this->brickletAmbientLight->setIlluminanceCallbackPeriod(1000);
            $this->brickletAmbientLight->registerCallback(BrickletAmbientLight::CALLBACK_ILLUMINANCE,
                                                          array($this, 'cb_illuminance'));
        } else if($deviceIdentifier == BrickletHumidity::DEVICE_IDENTIFIER) {
            $this->brickletHumidity = new BrickletHumidity($uid, $this->ipcon);
            $this->brickletHumidity->setHumidityCallbackPeriod(1000);
            $this->brickletHumidity->registerCallback(BrickletHumidity::CALLBACK_HUMIDITY,
                                                      array($this, 'cb_humidity'));
        } else if($deviceIdentifier == BrickletBarometer::DEVICE_IDENTIFIER) {
            $this->brickletBarometer = new BrickletBarometer($uid, $this->ipcon);
            $this->brickletBarometer->setAirPressureCallbackPeriod(1000);
            $this->brickletBarometer->registerCallback(BrickletBarometer::CALLBACK_AIR_PRESSURE,
                                                       array($this, 'cb_airPressure'));
        }
    }
}

?>

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

<?php

$text = sprintf("%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.

<?php

function cb_illuminance($illuminance)
{
    $text = sprintf("Illuminanc %6.2f lx", $illuminance/10.0);
    $this->brickletLCD->writeLine(0, 0, $text);
}

function cb_humidity($humidity)
{
    $text = sprintf("Humidity   %6.2f %%", $humidity/10.0);
    $this->brickletLCD->writeLine(1, 0, $text);
}

function cb_airPressure($airPressure)
{
    $text = sprintf("Air Press %7.2f mb", $airPressure/1000.0);
    $this->brickletLCD->writeLine(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_airPressure callback function:

<?php

function cb_airPressure($airPressure)
{
    $text = sprintf("Air Press %7.2f mb", $airPressure/1000.0);
    $this->brickletLCD->writeLine(2, 0, $text);

    $temperature = $this->brickletBarometer->getChipTemperature();
    $text = sprintf("Temperature %5.2f %cC", $temperature/100.0, 0xDF);
    $this->brickletLCD->writeLine(3, 0, $text);
}

?>

Step 3 put together:

<?php

function cb_illuminance($illuminance)
{
    $text = sprintf("Illuminanc %6.2f lx", $illuminance/10.0);
    $this->brickletLCD->writeLine(0, 0, $text);
}

function cb_humidity($humidity)
{
    $text = sprintf("Humidity   %6.2f %%", $humidity/10.0);
    $this->brickletLCD->writeLine(1, 0, $text);
}

function cb_airPressure($airPressure)
{
    $text = sprintf("Air Press %7.2f mb", $airPressure/1000.0);
    $this->brickletLCD->writeLine(2, 0, $text);

    $temperature = $this->brickletBarometer->getChipTemperature();
    // 0xDF == ° on LCD 20x4 charset
    $text = sprintf("Temperature %5.2f %cC", $temperature/100.0, 0xDF);
    $this->brickletLCD->writeLine(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_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 every second triggered by an additional timer. 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:

<?php

while(true) {
    try {
        $this->ipcon->connect(self::HOST, self::PORT);
        break;
    } catch(Exception $e) {
        sleep(1);
    }
}

?>

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

<?php

while(true) {
    try {
        $this->ipcon->enumerate();
        break;
    } catch(Exception $e) {
        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:

<?php

function cb_illuminance($illuminance)
{
    if($this->brickletLCD != null) {
        $text = sprintf("Illuminanc %6.2f lx", $illuminance/10.0);
        $this->brickletLCD->writeLine(0, 0, $text);
        echo "Write to line 0: $text\n";
    }
}

?>

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

<?php

if($deviceIdentifier == BrickletAmbientLight::DEVICE_IDENTIFIER) {
    try {
        $this->brickletAmbientLight = new BrickletAmbientLight($uid, $this->ipcon);
        $this->brickletAmbientLight->setIlluminanceCallbackPeriod(1000);
        $this->brickletAmbientLight->registerCallback(BrickletAmbientLight::CALLBACK_ILLUMINANCE,
                                                      array($this, 'cb_illuminance'));
        echo "Ambient Light initialized\n";
    } catch(Exception $e) {
        $this->brickletAmbientLight = null;
        echo "Ambient Light init failed: $e\n";
    }
}

?>

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

<?php

require_once('Tinkerforge/IPConnection.php');
require_once('Tinkerforge/BrickletLCD20x4.php');
require_once('Tinkerforge/BrickletAmbientLight.php');
require_once('Tinkerforge/BrickletAmbientLightV2.php');
require_once('Tinkerforge/BrickletAmbientLightV3.php');
require_once('Tinkerforge/BrickletHumidity.php');
require_once('Tinkerforge/BrickletHumidityV2.php');
require_once('Tinkerforge/BrickletBarometer.php');
require_once('Tinkerforge/BrickletBarometerV2.php');

use Tinkerforge\IPConnection;
use Tinkerforge\BrickletLCD20x4;
use Tinkerforge\BrickletAmbientLight;
use Tinkerforge\BrickletAmbientLightV2;
use Tinkerforge\BrickletAmbientLightV3;
use Tinkerforge\BrickletHumidity;
use Tinkerforge\BrickletHumidityV2;
use Tinkerforge\BrickletBarometer;
use Tinkerforge\BrickletBarometerV2;

class WeatherStation
{
    const HOST = 'localhost';
    const PORT = 4223;

    public function __construct()
    {
        $this->brickletLCD = null;
        $this->brickletAmbientLight = null;
        $this->brickletAmbientLightV2 = null;
        $this->brickletAmbientLightV3 = null;
        $this->brickletHumidity = null;
        $this->brickletHumidityV2 = null;
        $this->brickletBarometer = null;
        $this->brickletBarometerV2 = null;
        $this->ipcon = new IPConnection();

        while(true) {
            try {
                $this->ipcon->connect(self::HOST, self::PORT);
                break;
            } catch(Exception $e) {
                sleep(1);
            }
        }

        $this->ipcon->registerCallback(IPConnection::CALLBACK_ENUMERATE,
                                       array($this, 'cb_enumerate'));
        $this->ipcon->registerCallback(IPConnection::CALLBACK_CONNECTED,
                                       array($this, 'cb_connected'));

        while(true) {
            try {
                $this->ipcon->enumerate();
                break;
            } catch(Exception $e) {
                sleep(1);
            }
        }
    }

    function cb_illuminance($illuminance)
    {
        if($this->brickletLCD != null) {
            $text = sprintf("Illuminanc %6.2f lx", $illuminance/10.0);
            $this->brickletLCD->writeLine(0, 0, $text);
            echo "Write to line 0: $text\n";
        }
    }

    function cb_illuminanceV2($illuminance)
    {
        if($this->brickletLCD != null) {
            $text = sprintf("Illumina %8.2f lx", $illuminance/100.0);
            $this->brickletLCD->writeLine(0, 0, $text);
            echo "Write to line 0: $text\n";
        }
    }

    function cb_illuminanceV3($illuminance)
    {
        if($this->brickletLCD != null) {
            $text = sprintf("Illumina %8.2f lx", $illuminance/100.0);
            $this->brickletLCD->writeLine(0, 0, $text);
            echo "Write to line 0: $text\n";
        }
    }

    function cb_humidity($humidity)
    {
        if($this->brickletLCD != null) {
            $text = sprintf("Humidity   %6.2f %%", $humidity/10.0);
            $this->brickletLCD->writeLine(1, 0, $text);
            echo "Write to line 1: $text\n";
        }
    }

    function cb_humidityV2($humidity)
    {
        if($this->brickletLCD != null) {
            $text = sprintf("Humidity   %6.2f %%", $humidity/100.0);
            $this->brickletLCD->writeLine(1, 0, $text);
            echo "Write to line 1: $text\n";
        }
    }

    function cb_airPressure($airPressure)
    {
        if($this->brickletLCD != null) {
            $text = sprintf("Air Press %7.2f mb", $airPressure/1000.0);
            $this->brickletLCD->writeLine(2, 0, $text);
            echo "Write to line 2: $text\n";

            try {
                $temperature = $this->brickletBarometer->getChipTemperature();
            } catch(Exception $e) {
                echo "Could not get temperature: $e\n";
                return;
            }

            // 0xDF == ° on LCD 20x4 charset
            $text = sprintf("Temperature %5.2f %cC", $temperature/100.0, 0xDF);
            $this->brickletLCD->writeLine(3, 0, $text);
            $text = str_replace(sprintf("%c", 0xDF), '°', $text);
            echo "Write to line 3: $text\n";
        }
    }

    function cb_airPressureV2($airPressure)
    {
        if($this->brickletLCD != null) {
            $text = sprintf("Air Press %7.2f mb", $airPressure/1000.0);
            $this->brickletLCD->writeLine(2, 0, $text);
            echo "Write to line 2: $text\n";

            try {
                $temperature = $this->brickletBarometerV2->getTemperature();
            } catch(Exception $e) {
                echo "Could not get temperature: $e\n";
                return;
            }

            // 0xDF == ° on LCD 20x4 charset
            $text = sprintf("Temperature %5.2f %cC", $temperature/100.0, 0xDF);
            $this->brickletLCD->writeLine(3, 0, $text);
            $text = str_replace(sprintf("%c", 0xDF), '°', $text);
            echo "Write to line 3: $text\n";
        }
    }

    function cb_enumerate($uid, $connectedUid, $position, $hardwareVersion,
                          $firmwareVersion, $deviceIdentifier, $enumerationType)
    {
        if($enumerationType == IPConnection::ENUMERATION_TYPE_CONNECTED ||
           $enumerationType == IPConnection::ENUMERATION_TYPE_AVAILABLE) {
            if($deviceIdentifier == BrickletLCD20x4::DEVICE_IDENTIFIER) {
                try {
                    $this->brickletLCD = new BrickletLCD20x4($uid, $this->ipcon);
                    $this->brickletLCD->clearDisplay();
                    $this->brickletLCD->backlightOn();
                    echo "LCD 20x4 initialized\n";
                } catch(Exception $e) {
                    $this->brickletLCD = null;
                    echo "LCD 20x4 init failed: $e\n";
                }
            } else if($deviceIdentifier == BrickletAmbientLight::DEVICE_IDENTIFIER) {
                try {
                    $this->brickletAmbientLight = new BrickletAmbientLight($uid, $this->ipcon);
                    $this->brickletAmbientLight->setIlluminanceCallbackPeriod(1000);
                    $this->brickletAmbientLight->registerCallback(BrickletAmbientLight::CALLBACK_ILLUMINANCE,
                                                                  array($this, 'cb_illuminance'));
                    echo "Ambient Light initialized\n";
                } catch(Exception $e) {
                    $this->brickletAmbientLight = null;
                    echo "Ambient Light init failed: $e\n";
                }
            } else if($deviceIdentifier == BrickletAmbientLightV2::DEVICE_IDENTIFIER) {
                try {
                    $this->brickletAmbientLightV2 = new BrickletAmbientLightV2($uid, $this->ipcon);
                    $this->brickletAmbientLightV2->setConfiguration(BrickletAmbientLightV2::ILLUMINANCE_RANGE_64000LUX,
                                                                    BrickletAmbientLightV2::INTEGRATION_TIME_200MS);
                    $this->brickletAmbientLightV2->setIlluminanceCallbackPeriod(1000);
                    $this->brickletAmbientLightV2->registerCallback(BrickletAmbientLightV2::CALLBACK_ILLUMINANCE,
                                                                    array($this, 'cb_illuminanceV2'));
                    echo "Ambient Light 2.0 initialized\n";
                } catch(Exception $e) {
                    $this->brickletAmbientLight = null;
                    echo "Ambient Light 2.0 init failed: $e\n";
                }
            } else if($deviceIdentifier == BrickletAmbientLightV3::DEVICE_IDENTIFIER) {
                try {
                    $this->brickletAmbientLightV3 = new BrickletAmbientLightV3($uid, $this->ipcon);
                    $this->brickletAmbientLightV3->setConfiguration(BrickletAmbientLightV3::ILLUMINANCE_RANGE_64000LUX,
                                                                    BrickletAmbientLightV3::INTEGRATION_TIME_200MS);
                    $this->brickletAmbientLightV3->setIlluminanceCallbackConfiguration(1000, false, 'x', 0, 0);
                    $this->brickletAmbientLightV3->registerCallback(BrickletAmbientLightV3::CALLBACK_ILLUMINANCE,
                                                                    array($this, 'cb_illuminanceV3'));
                    echo "Ambient Light 3.0 initialized\n";
                } catch(Exception $e) {
                    $this->brickletAmbientLight = null;
                    echo "Ambient Light 3.0 init failed: $e\n";
                }
            } else if($deviceIdentifier == BrickletHumidity::DEVICE_IDENTIFIER) {
                try {
                    $this->brickletHumidity = new BrickletHumidity($uid, $this->ipcon);
                    $this->brickletHumidity->setHumidityCallbackPeriod(1000);
                    $this->brickletHumidity->registerCallback(BrickletHumidity::CALLBACK_HUMIDITY,
                                                              array($this, 'cb_humidity'));
                    echo "Humidity initialized\n";
                } catch(Exception $e) {
                    $this->brickletHumidity = null;
                    echo "Humidity init failed: $e\n";
                }
            } else if($deviceIdentifier == BrickletHumidity::DEVICE_IDENTIFIER) {
                try {
                    $this->brickletHumidityV2 = new BrickletHumidityV2($uid, $this->ipcon);
                    $this->brickletHumidityV2->setHumidityCallbackPeriod(1000, true, 'x', 0, 0);
                    $this->brickletHumidityV2->registerCallback(BrickletHumidityV2::CALLBACK_HUMIDITY,
                                                                array($this, 'cb_humidityV2'));
                    echo "Humidity 2.0 initialized\n";
                } catch(Exception $e) {
                    $this->brickletHumidity = null;
                    echo "Humidity 2.0 init failed: $e\n";
                }
            } else if($deviceIdentifier == BrickletBarometer::DEVICE_IDENTIFIER) {
                try {
                    $this->brickletBarometer = new BrickletBarometer($uid, $this->ipcon);
                    $this->brickletBarometer->setAirPressureCallbackPeriod(1000);
                    $this->brickletBarometer->registerCallback(BrickletBarometer::CALLBACK_AIR_PRESSURE,
                                                               array($this, 'cb_airPressure'));
                    echo "Barometer initialized\n";
                } catch(Exception $e) {
                    $this->brickletBarometer = null;
                    echo "Barometer init failed: $e\n";
                }
            } else if($deviceIdentifier == BrickletBarometerV2::DEVICE_IDENTIFIER) {
                try {
                    $this->brickletBarometerV2 = new BrickletBarometerV2($uid, $this->ipcon);
                    $this->brickletBarometerV2->setAirPressureCallbackConfiguration(1000, false, 'x', 0, 0);
                    $this->brickletBarometerV2->registerCallback(BrickletBarometerV2::CALLBACK_AIR_PRESSURE,
                                                                 array($this, 'cb_airPressureV2'));
                    echo "Barometer 2.0 initialized\n";
                } catch(Exception $e) {
                    $this->brickletBarometer = null;
                    echo "Barometer 2.0 init failed: $e\n";
                }
            }
        }
    }

    function cb_connected($connectedReason)
    {
        if($connectedReason == IPConnection::CONNECT_REASON_AUTO_RECONNECT) {
            echo "Auto Reconnect\n";

            while(true) {
                try {
                    $this->ipcon->enumerate();
                    break;
                } catch(Exception $e) {
                    sleep(1);
                }
            }
        }
    }
}

$weatherStation = new WeatherStation();
echo "Press ctrl+c to exit\n";
$weatherStation->ipcon->dispatchCallbacks(-1);

?>