# Quick script to use HP 3586C SLM
# as a rudimentary spectrum analyzer.

use Device::SerialPort;

# Set up the serial port
# 19200, 81N on the USB ftdi driver
my $port = Device::SerialPort->new("/dev/ttyUSB0");
$port->databits(8);
$port->baudrate(19200);
$port->parity("none");
$port->stopbits(1);

# Initialize Prologix USB-GPIB Controller
$port->write("++mode 1\n");
$port->write("++auto 1\n");
$port->write("++addr 16\n");

# Initialize HP 3586C
$port->write("Remote\n");
$port->write("B3\n"); # Set BW Filter
$port->write("T1\n"); # Terminate in 50 ohms
$port->write("A1\n"); # Average: On

# Frequency Sweep Definition
$freq_start = 9250;
$freq_end = 10250;
$freq_increment = 1;
$freq_index = $freq_start;
while ($freq_index <= $freq_end) {
  push (@frequency, $freq_index);
  $freq_index = $freq_index + $freq_increment;
}

$scan_rep = 70;
$scan_index = 1;
print "#(kHz)         (UNIXtime)              (dBm)\n";
print "Freq           Time                    Amplitude\n";
while ($scan_index <= $scan_rep) {
  print "# Starting Repetition: $scan_index\n";
  # Gather and print the measurements
  # If you want to sweep faster, adjust the two sleep() statements.
  #   Check manual for minimum settling times for your configuration of
  #   BW filter, averaging, etc.
  foreach $freq (@frequency) {
    $port->write("FR,$freq,KZ\n");
    sleep(6);
    $port->write("TR\n");
    sleep(2);
    my $char = $port->lookfor();
    $char =~ s/N//g;
    $char =~ s/\r//g; # To match the newlines from the HP 3586C
    chomp $char;
    $time = time; 
    print "$freq		$time		$char \n";
  }

  $scan_index = $scan_index + 1;
}
