Saturday, July 12, 2014

Displaying Current Temperature on a Web Page Using a TMP102 & PHP on a Raspberry Pi

Here is an example of using PHP to read the current temperature from a TMP102 I2C temperature sensor and display it (in degrees Fahrenheit) in a Web page.

Prerequisites


Make sure that you have installed the i2c-tools package because this package provides i2cget to read the registers on the TMP102.  The following apt-get command will install it for you:


sudo apt-get install i2c-tools

Install the Apache2 Web server:

apt-get install apache2

Then install PHP5:

apt-get install php5

Granting Access to I2C System Device


By default, and for the sake of security, the account used to run the Apache2 Web server doesn't have permission to access the /dev/i2c-1 device.  To fix this, edit the udev configuration file that controls the file permissions for /dev/i2c-1.

Use nano or your favorite text editor to edit /lib/udev/rules.d/60-i2c-tools.rule. Replace the contents of the file with these two lines.  

KERNEL=="i2c-0", GROUP="i2c", MODE="0660"
KERNEL=="i2c-1", GROUP="i2c", MODE="0666"

This leaves the i2c-0 device with the default permissions and changes the access to i2c-1 to allow a non-privileged user to read the device.

PHP Code


Here is a simple PHP page that reads the temperature data using i2cget, converts it to degrees Fahrenheit and displays it.  Put this code in /var/www/temp.php -

<?php
    $output = `/usr/sbin/i2cget -y 1 0x48 0 w`;
    $msb = hexdec(substr($output, 4, 2));
    $lsb = hexdec(substr($output, 2, 2));
    $tempF = ((($msb << 8) | $lsb) >> 4) * 0.0625 * 1.8 + 32;
    echo "Temp: $tempF&deg;F";
?>

The backticks (` `) tell PHP to run the enclosed command in a (Linux) command shell.  The backtick is on the key to the left of the 1 key near the top of the keyboard (on the same key as the ~).

In the command i2cget -y 1 0x48 0 w

  • -y cancels the user prompt that asks if you really want to read from the device
  • 1 actually refers to the 2nd I2C bus, /dev/i2c-1
  • 0x48 is the default I2C device address for the TMP102
  • 0 is the register with the temperature data
  • w means we want to read a word (rather than just a byte).

Note that when i2cget reads the data, the byte order is reversed.  The first byte is actually the least significant byte (LSB) and the second byte is the most significant byte (MSB).  The string returned by i2cget is something like 0xb01d.  The code uses substr() to pull out the two digits for each byte, and then hexdec() to convert a string representing a hexadecimal value to a decimal numeric value.

From a computer on the same network, access the URL for the page (where the IP address will vary):

http://192.168.0.108/temp.php



1 comment:

  1. Above in the Kernel Rules, did you mean .rules NOT .rule ?

    ReplyDelete