#!/usr/bin/env perl
use strict;
use warnings;
use Time::HiRes qw(usleep sleep gettimeofday tv_interval);

my $base = do {
    open my $fh,'<','/sys/class/gpio/gpiochip405/base' or die "can't get base: $!";
    my $line = <$fh>;
    chomp($line);
    $line;
};

sub gpio_enable {
    my ($pin,$state) = @_;

    if ($state) {
        open my $fh,'>','/sys/class/gpio/export' or die "Can't export: $!";
        print $fh $pin,"\n";
    }
    else {
        open my $fh,'>','/sys/class/gpio/unexport' or die "Can't unexport: $!";
        print $fh $pin,"\n";
    }
}

sub gpio_direction {
    my ($pin,$direction) = @_;

    my $file = "/sys/class/gpio/gpio$pin/direction";
    open my $fh,'>',$file
        or die "Can't direction $file: $!";
    print $fh ($direction ? 'out' : 'in' ),"\n";
}

sub gpio_write {
    my ($pin,$value) = @_;

    open my $fh,'>',"/sys/class/gpio/gpio$pin/value"
        or die "Can't write: $!";
    print $fh $value,"\n";
}

my $pin = 132; # CSID0
#my $pin = $base+0; # XIO0

gpio_enable($pin,1);
gpio_direction($pin,1);
gpio_write($pin,0);
$SIG{INT} = sub {warn"disabling";gpio_enable($pin,0) };
END { warn"disabling";gpio_enable($pin,0) }

my $width = 400; # this seems to provide pulse widths close enough to
                 # what we need, it's 106 samples at 192kHz
while (1) {
    for (0..50) {
        gpio_write($pin,1);
        usleep($width);
        gpio_write($pin,0);
        usleep($width);
    }
    sleep(0.5);
}
