#!/usr/bin/perl # # Usage: fetch_temperature [outfile] # # Nice data fetch script for arduino temperature sensor # # If you call it without arguments, it prints the current temperature to the # console. # # If you pass a filename as argument, it adds the current date, time and temperature # to the end of the file use strict; use warnings; # Set up the serial port use Device::SerialPort; my $port = Device::SerialPort->new("/dev/ttyUSB0"); # Some simple error catch mechanism if(!$port) { my $port = Device::SerialPort->new("/dev/ttyUSB1"); } # If no connection could be made, quit if(!$port) { print "No device found!!\n"; exit 1; } # Initialize communication # # 38400, 81N on the USB ftdi driver $port->baudrate(38400); $port->databits(8); $port->parity("none"); $port->stopbits(1); # Some initialization my $filename = ""; $filename = shift; # Create nice timestamp YYYY-MM-DD HH:MM:SS for file output my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time); my $timestamp = sprintf "%4d-%02d-%02d %02d:%02d:%02d", $year+1900,$mon+1,$mday,$hour,$min,$sec; my $temp = ""; my $starttime = time(); my $written = 0; # Loop while there is no data available while (!$temp) { # If we didn't send anything yet, send signal (a simple '1') to the arduino if(!$written) { $port->write(1); $written = 1; } # Poll to see if any data is coming in $temp = $port->lookfor(); # If there was too much time spent, quit the loop and set error message as result if(time() > $starttime + 5) { $temp = "Sensor not yet ready!"; } } # If a filename has been passed as argument, write the result into this file if($filename) { # Write down temp into file with current timestamp open FILE, ">>$filename" or die "could not open $filename: $!\n"; print FILE "$timestamp $temp\n"; close FILE; } # else print the result to the console else { print "$temp\n"; } # goodbye