Search code examples
perlcronraspberry-pii2c

perl program run from crontab yields wrong values i2cget raspberry pi


I've read a number of other Q&A's that seem to be related, but haven't been able to track down the issue here.

I have the following perl script that I use on my Raspberry Pi. I'm hoping to log temperature data from an I2C sensor to a sqlite3 database. The program below works when being run from the command line but not when run from cron.

I'm assuming that the value from i2cget is incorrect when run from cron, but I'm not sure how to figure out what part of my environment i2cget needs to work properly.

#!/usr/bin/perl

#printf '%d\n' `i2cget -y 1 0x48 0x0`
$temp = `i2cget -y 1 0x48 0x0`;
#$temp = sprintf("%d\n", $temp);
$temp = hex($temp);
#print $temp, "\n";

use DBI;

#/home/techplex/ece331/project2_temp_data_grapher/
$dbh = DBI->connect( "dbi:SQLite:tempdata.db" ) or die "Cannot connect: $DBI::errstr";

$dbh->do( "CREATE TABLE IF NOT EXISTS temperature (timestamp datetime, temperature float);" );
$dbh->do( "INSERT INTO temperature (timestamp, temperature) VALUES (datetime('now', 'localtime'), $temp);" );

$dbh->disconnect;

I've added this line to my crontab:

*/1 * * * * cd /home/techplex/temp_data_grapher; ./datalogger.pl

Solution

  • You need full path to i2c inside your perl script:

    $temp = `/full/path/to/i2cget -y 1 0x48 0x0`;