Measurement Studio for .NET Languages

cancel
Showing results for 
Search instead for 
Did you mean: 

Transmit waveform on single port/line on PXIe-6363

Solved!
Go to solution

I'm writing C# code to transmit a digital waveform on a single port/line on PXIe-6363 X-Series DAQ. I want the code to be able to transmit the waveform a single time or repeat it at a specified rate. The code below for Mode.Single successfully transmits the waveform, but Mode.Continuous does not output anything. I'm using port 0 line 5 for the digital output, timePerBit is 104 usec, overSampleFactor is 1, mode is Mode.Continuous, waveformPeriod is 0.010 seconds, counterPeriodicTiming is ctr2 (ctr2InternalOutput for the first parameter in ConfigureSampleClock( ), ctr2 for for first parameter in CreatePulseChannelFrequency( ).

 

        /// <summary>
        /// Generates a digital waveform on the specified DAQ card digital output. Call StopDigitalWaveform() to stop a continuous waveform.
        /// </summary>
        /// <param name="port">Digital port to transmit the waveform (note: some devices may not be able to send waveform on all port)</param>
        /// <param name="line">Digital line of the port to transmit the waveform</param>
        /// <param name="digitalWaveform">List of bits values to output as the digital waveform</param>
        /// <param name="timePerBit">Duration of each bit, in seconds</param>
        /// <param name="overSampleFactor">Oversampling factor. For example, if factor is 3 clock will be 3 times faster (each bit in waveform must have 3 entries to accomodate increased clock speed).</param>
        /// <param name="mode">Generate single or continuous waveform</param>
        /// <param name="waveformPeriod">Waveform period in seconds, if mode is continuous</param>
        /// <param name="counterPeriodicTiming">Counter to use for waveform periodic timing</param>
        /// <returns>Zero for success, negative number for error</returns>
        public int GenerateDigitalWaveform(
            int port,
            int line,
            ref List<int> digitalWaveform,
            double timePerBit,
            int overSampleFactor = 1,
            Mode mode = Mode.Single,
            double waveformPeriod = 0.010,
            string counterPeriodicTiming = "ctr0")
        {
            int status = 0;

            double sampleRate = (1.0 / timePerBit) * overSampleFactor;

            // Calculate pattern duration
            double waveformDuration = digitalWaveform.Count * timePerBit;

            if ((waveformPeriod <= 0) || (waveformPeriod < waveformDuration))
            {
                Console.WriteLine($"Error: Period {waveformPeriod} must be greater than zero and less than the waveform duration {waveformDuration}!");
                return (int)StatusCodes.ERR_INVALID_DIGITAL_WAVEFORM_PERIOD;
            }

            waveformTask = new Task();
            string devicePortLine = $"/{_cardInfo.deviceName}/port{port}/line{line}";
            waveformTask.DOChannels.CreateChannel(devicePortLine,
                                                  "DigitalWaveformOutput",
                                                  ChannelLineGrouping.OneChannelForAllLines);

            waveformTask.Stream.Buffer.OutputBufferSize = digitalWaveform.Count;

            DigitalWaveform waveformData = DigitalWaveform.FromPort(digitalWaveform.ToArray(), 0x01);

            if (mode == Mode.Single)
            {
                // Send waveform one time
                waveformTask.Timing.ConfigureSampleClock("",
                                                         sampleRate,
                                                         SampleClockActiveEdge.Rising,
                                                         SampleQuantityMode.FiniteSamples,
                                                         digitalWaveform.Count);

                writer = new DigitalSingleChannelWriter(waveformTask.Stream);
                writer.WriteWaveform(false, waveformData);
                waveformTask.Start();

                // Wait for finite sample completion
                waveformTask.WaitUntilDone();
                Console.WriteLine($"Single digital waveform generated successfully on {devicePortLine}.");
                StopDigitalWaveform();
            }
            else
            {
                // Send waveform continuously using internal periodic timing

                string counterTerminal = char.ToUpper(counterPeriodicTiming[0]) + counterPeriodicTiming.Substring(1) + "InternalOutput";
                string deviceCounterTerminal = $"/{_cardInfo.deviceName}/{counterTerminal}";

                // Configure for continuous samples using internal timer as sample clock
                waveformTask.Timing.ConfigureSampleClock(deviceCounterTerminal,
                                                         sampleRate,
                                                         SampleClockActiveEdge.Rising,
                                                         SampleQuantityMode.ContinuousSamples,
                                                         digitalWaveform.Count);

                writer = new DigitalSingleChannelWriter(waveformTask.Stream);
                writer.WriteWaveform(false, waveformData);

                // Create counter output task for periodic timing
                timerTask = new Task();

                string deviceCounter = $"/{_cardInfo.deviceName}/{counterPeriodicTiming}";
                timerTask.COChannels.CreatePulseChannelFrequency(deviceCounter,
                                                                 "TimerOutput",
                                                                 COPulseFrequencyUnits.Hertz,
                                                                 COPulseIdleState.Low,
                                                                 0,                     // Initial delay
                                                                 1.0 / waveformPeriod,  // Frequency
                                                                 0.5);                  // Duty cycle

                timerTask.Start();

                // Add a delay to ensure timer is stabilized
                System.Threading.Thread.Sleep(10);

                waveformTask.Start();
                Console.WriteLine($"Continuous digital waveform started on {devicePortLine} with period {waveformPeriod:F3} ms");
                // The application should call StopDigitalWaveform() to stop the digital waveform
            }

            return status;
        }
        /// <summary>
        /// Stops the currently running continuous digital waveform, which was started by GenerateDigitalWaveform().
        /// </summary>
        /// <returns>Zero for success, negative number for error</returns>
        public int StopDigitalWaveform()
        {
            int status = 0;

            if (timerTask != null)
            {
                try
                {
                    timerTask.Stop();
                    Console.WriteLine("Digital waveform periodic timer stopped.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error stopping digital waveform timer: {ex.Message}");
                    status = (int)StatusCodes.ERR_EXCEPTION_OCCURRED;
                }

                timerTask.Dispose();
            }

            if (waveformTask != null)
            {
                try
                {
                    waveformTask.Stop();
                    Console.WriteLine("Digital waveform stopped.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error stopping digital waveform: {ex.Message}");
                    status = (int)StatusCodes.ERR_EXCEPTION_OCCURRED;
                }

                waveformTask.Dispose();
            }

            return status;
        }
0 Kudos
Message 1 of 2
(935 Views)
Solution
Accepted by topic author VNF

I got it working. The code below is basically what I used for sending a continuous digital waveform on a single port/line using a counter as the trigger.

using System;
using NationalInstruments.DAQmx;

class InternalCounterTriggerDO
{
    static void Main()
    {
        // Device and channel names
        string digitalLine = "Dev1/port0/line0";
        string counter = "Dev1/ctr0";
        string triggerSource = "/Dev1/Ctr0InternalOutput"; // Internal route from counter

        // Digital waveform: true = high, false = low
        byte[] waveform = new byte[] { 1, 0, 1, 0, 1, 0 };

        try
        {
            // -------------------------
            // 1. Configure Counter Output Task (Trigger Source)
            // -------------------------
            using (Task counterTask = new Task())
            {
                // Pulse train: 100 Hz (10 ms period), 50% duty cycle
                counterTask.COChannels.CreatePulseChannelFrequency(
                    counter,
                    "CounterTrigger",
                    COPulseFrequencyUnits.Hertz,
                    COPulseIdleState.Low,
                    0.0,      // Initial delay
                    100.0,    // Frequency (Hz)
                    0.5       // Duty cycle
                );

                // Continuous generation
                counterTask.Timing.ConfigureImplicit(SampleQuantityMode.ContinuousSamples);

                // -------------------------
                // 2. Configure Digital Output Task
                // -------------------------
                using (Task digitalTask = new Task())
                {
                    // Single-line DO channel
                    digitalTask.DOChannels.CreateChannel(
                        digitalLine,
                        "SingleLineDO",
                        ChannelLineGrouping.OneChannelForEachLine
                    );

                    // Sample clock: onboard clock
                    digitalTask.Timing.ConfigureSampleClock(
                        "",                               // Onboard clock
                        1000.0,                           // Sample rate in Hz
                        SampleClockActiveEdge.Rising,
                        SampleQuantityMode.FiniteSamples, // Output finite samples per trigger
                        waveform.Length
                    );

                    // Digital start trigger from counter output (internal)
                    digitalTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                        triggerSource,
                        DigitalEdgeStartTriggerEdge.Rising
                    );

                    // Enable retriggering
                    digitalTask.Triggers.StartTrigger.Retriggerable = true;

                    // FIFO regeneration (default) — waveform reused each trigger
                    DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalTask.Stream);
                    DigitalWaveform waveformData = DigitalWaveform.FromPort(waveform.ToArray(), 0x01);
                    writer.WriteWaveform(false, waveformData); // false = don't auto-start

                    // -------------------------
                    // 3. Start tasks
                    // -------------------------
                    digitalTask.Start();
                    counterTask.Start();

                    Console.WriteLine("Outputting waveform every 10 ms from internal counter trigger...");
                    Console.WriteLine("Press any key to stop.");
                    Console.ReadKey();

                    // -------------------------
                    // 4. Stop tasks
                    // -------------------------
                    counterTask.Stop();
                    digitalTask.Stop();
                }
            }
        }
        catch (DaqException ex)
        {
            Console.WriteLine("DAQmx Error: " + ex.Message);
        }
    }
}

 

0 Kudos
Message 2 of 2
(866 Views)