OscilloscopeGeneratorTrigger.cpp

/**
 * OscilloscopeGeneratorTrigger.cpp - for LibTiePie 0.5+
 *
 * This example sets up the generator to generate a 1 kHz triangle waveform, 4 Vpp.
 * It also sets up the oscilloscope to perform a block mode measurement, triggered on "Generator new period".
 * A measurement is performed and the data is written to OscilloscopeGeneratorTrigger.csv.
 *
 * Find more information on http://www.tiepie.com/LibTiePie .
 */

#include <iostream>
#include <fstream>
#include "libtiepie++.h"
#include "PrintInfo.h"

#if defined(__linux) || defined(__unix)
  #include <cstdlib>
  #include <unistd.h>
#endif

using namespace std;
using namespace LibTiePie;

int main()
{
  int status = EXIT_SUCCESS;

  // Initialize library:
  Library::init();

  // Print library information:
  printLibraryInfo();

  // Update device list:
  DeviceList::update();

  // Try to open an oscilloscope with block measurement support and a generator in the same device:
  Oscilloscope* scp = 0;
  Generator*    gen = 0;

  for(uint32_t index = 0; index < DeviceList::count(); index++)
  {
    DeviceListItem* item = DeviceList::getItemByIndex(index);

    if(item->canOpen(DEVICETYPE_OSCILLOSCOPE) && item->canOpen(DEVICETYPE_GENERATOR))
    {
      scp = item->openOscilloscope();

      // Check for valid pointer and block measurement support:
      if(scp && scp->measureModes() & MM_BLOCK)
      {
        gen = item->openGenerator();
      }
      else
      {
        delete scp;
        scp = 0;
      }
    }

    delete item;

    if(scp && gen)
    {
      break;
    }
  }

  if(scp && gen)
  {
    float** channelData = 0;
    uint16_t channelCount = 0;

    try
    {
      // Oscilloscope settings:

      // Get the number of channels:
      channelCount = scp->channels.count();

      // Set measure mode:
      scp->setMeasureMode(MM_BLOCK);

      // Set sample frequency:
      scp->setSampleFrequency(1e6); // 1 MHz

      // Set record length:
      const uint64_t recordlength = scp->setRecordLength(10000); // 10 kS

      // Set pre sample ratio:
      scp->setPreSampleRatio(0); // 0 %

      // For all channels:
      for(uint16_t ch = 0; ch < channelCount; ch++)
      {
        OscilloscopeChannel& channel = scp->channels[ch];

        // Enable channel to measure it:
        channel.setEnabled(true);

        // Set range:
        channel.setRange(8); // 8 V

        // Set coupling:
        channel.setCoupling(CK_DCV); // DC Volt
      }

      // Set trigger timeout:
      scp->setTriggerTimeOut(1); // 1 s

      // Disable all channel trigger sources:
      for(uint16_t ch = 0; ch < channelCount; ch++)
        scp->channels[ch].trigger->setEnabled(false);

      // Locate trigger input:
      TriggerInput* triggerInput = scp->triggerInputs.getById(TIID_GENERATOR_NEW_PERIOD); // or TIID_GENERATOR_START || TIID_GENERATOR_STOP

      if(!triggerInput)
        throw runtime_error("Unknown trigger input!");

      // Enable trigger input:
      triggerInput->setEnabled(true);

      // Generator settings:

      // Set signal type:
      gen->setSignalType(ST_TRIANGLE);

      // Set frequency:
      gen->setFrequency(1e3); // 1 kHz

      // Set amplitude:
      gen->setAmplitude(2); // 2 V

      // Set offset:
      gen->setOffset(0); // 0 V

      // Enable output:
      gen->setOutputOn(true);

      // Print oscilloscope info:
      printDeviceInfo(scp);

      // Print generator info:
      printDeviceInfo(gen);

      // Start measurement:
      scp->start();

      // Start signal generation:
      gen->start();

      // Wait for measurement to complete:
      while(!scp->isDataReady())
      {
        // 10 ms delay, to save CPU time:
#if defined(_WIN32) || defined(_WIN64)
        Sleep(10);
#elif defined(__linux) || defined(__unix)
        usleep(10000);
#endif
      }

      // Stop generator:
      gen->stop();

      // Disable output:
      gen->setOutputOn(false);

      // Create data buffer:
      channelData = new float*[channelCount];
      for(uint16_t ch = 0; ch < channelCount; ch++)
        channelData[ch] = new float[recordlength] ;

      // Get the data from the scope:
      uint64_t samplesRead = scp->getData(channelData, channelCount , 0 , recordlength);

      // Open file with write/update permissions:
      const std::string filename("OscilloscopeGeneratorTrigger.csv");
      ofstream csv(filename.c_str() , std::ofstream::out);

      if(csv.is_open())
      {
        // Write csv header:
        csv << "Sample";
        for(uint16_t ch = 0; ch < channelCount; ch++)
          csv << ";Ch" << (ch + 1);
        csv << endl;

        // Write the data to csv:
        for(uint64_t i = 0; i < samplesRead; i++)
        {
          csv << i;
          for(uint16_t ch = 0; ch < channelCount; ch++)
            csv << ";" << (float)channelData[ch][i];
          csv << endl;
        }

        cout << "Data written to: " << filename << endl;

        // Close file:
        csv.close();
      }
      else
      {
        cerr << "Couldn't open file: " << filename;
        status = EXIT_FAILURE;
      }
    }
    catch(const exception& e)
    {
      cerr << "Exception: " << e.what() << endl;
      status = EXIT_FAILURE;
    }

    // Delete data buffer:
    if(channelData)
      for(uint16_t ch = 0; ch < channelCount; ch++)
        delete [] channelData[ch];
    delete [] channelData;

    // Close oscilloscope:
    delete scp;

    // Close generator:
    delete gen;
  }
  else
  {
    cerr << "No oscilloscope available with block measurement support or generator available in the same unit!" << endl;
    status = EXIT_FAILURE;
  }

  // Exit library:
  Library::exit();

  return status;
}