#!/usr/bin/perl -w
use strict;

## log arduino output at ttyACM0 to current dir ardlog.txt

use Device::SerialPort;

my $portname = '/dev/ttyACM0';
my $filename = 'ardlog.txt';
my $port; # instance of Device::SerialPort
my $gotit = "";

sub setupserial
{
 $port = new Device::SerialPort ($portname, 1) || die "Can't open $portname: $!\n";
      $port->databits(8);
      $port->baudrate(115200);
      $port->parity("none");
      $port->stopbits(1);
      $port->handshake("none");
      $port->stty_icanon(1);    # this is what gets us on line boundaries
      $port->are_match("\n");                       # possible end strings
      $port->lookclear;                             # empty the buffer
      $port->write_settings or die "can't open $portname: $!\n"; # die?
sleep(1);
      $port->purge_all;
}

sub openoutfile
{
  my $old_fh;
 open (OUT, "> $filename") or die "couldn't open $filename for logging: $!\n";
  $old_fh = select(OUT);
  $| = 1; # autoflush every time
  select($old_fh); 
}

setupserial; # find ttyACM0 or die
openoutfile;

while (1)
{
 my $match = $port->matchclear;# so we dont keep reading the same line over
 $gotit = "";
   until ("" ne $gotit) {
      $gotit = $port->lookfor;       # poll until data ready
      die "Aborted without match\n" unless (defined $gotit);
      sleep 1;                          # polling sample time
  }

  printf "%s\n", $gotit;                # input BEFORE the match
  printf (OUT "%s\n",$gotit);   
}

close OUT;
print "hello from pi\n";


