Measurement Studio for .NET Languages

cancel
Showing results for 
Search instead for 
Did you mean: 

The right thread use with NI DAQ measurement

I'm using NI daq for some measurements and i don't have a clue how to use it with thread and for loop

my point is: i have 3 different frequencies, that stored in array , i need that after clicking a START button, function will generate first frequency and will red it and store data to the file, after this it move to second frequency and to same job, and after this will do measurement with third frequency and stop

Example:

for(int i=0; i< 3; i++)

{

   Measurement function();

}

 

I have this code:

//start button function click
private void cmd_start_Click(object sender, EventArgs e)
        {
            cmd_start.Enabled = false;
            taskRunning = true;

            for (int i = 0; i < matrix_data.Count; i++)
            {
                // Change the mouse to an hourglass for the duration of this function.
                Cursor.Current = Cursors.WaitCursor;
                pass_freq = matrix_data[i].freq;
                try
                {
                    // Create the master and slave tasks
                    inputTask = new Task("inputTask");
                    outputTask = new Task("outputTask");

                    // Configure both tasks with the values selected on the UI.
                    inputTask.AIChannels.CreateVoltageChannel("Dev1/ai0",
                        "",
                        AITerminalConfiguration.Differential,
                        inputMinValNumeric,
                        inputMaxValNumeric,
                        AIVoltageUnits.Volts);

                    outputTask.AOChannels.CreateVoltageChannel("Dev1/ao0",
                        "",
                        Convert.ToDouble(outputMinValNumeric),
                        Convert.ToDouble(outputMaxValNumeric),
                        AOVoltageUnits.Volts);

                    // Set up the timing
                    inputTask.Timing.ConfigureSampleClock("",
                        Convert.ToDouble(rateNumeric),
                        SampleClockActiveEdge.Rising,
                        SampleQuantityMode.FiniteSamples,
                        Convert.ToInt32(samplesNumeric));

                    outputTask.Timing.ConfigureSampleClock("",
                        Convert.ToDouble(rateNumeric),
                        SampleClockActiveEdge.Rising,
                        SampleQuantityMode.FiniteSamples,
                        Convert.ToInt32(samplesNumeric));

                    // Set up the start trigger

                    string deviceName = "Dev1";
                    string terminalNameBase = "/" + GetDeviceName(deviceName) + "/";
                    //        outputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(terminalNameBase + "ai/StartTrigger", triggerEdge);

                    // Verify the tasks
                    inputTask.Control(TaskAction.Verify);
                    outputTask.Control(TaskAction.Verify);

                    // Write data to each output channel
                    FunctionGenerator fGen = new FunctionGenerator(/*Convert.ToString(frequencyNumeric)*/matrix_data[i].freq,
                        Convert.ToString(samplesNumeric),
                        Convert.ToString(Convert.ToDouble(frequencyNumeric) / (rateNumeric / samplesNumeric)),
                        "Sine Wave",
                        amplitudeNumeric.ToString());

                    output = fGen.Data;

                    writer = new AnalogSingleChannelWriter(outputTask.Stream);
                    writer.WriteMultiSample(false, output);

                    // Officially start the task
                    StartTask();
                    // Start reading as well
                    inputCallback = new AsyncCallback(InputRead);
                    reader = new AnalogSingleChannelReader(inputTask.Stream);
                    //reader1 = new AnalogMultiChannelReader(inputTask.Stream);
                    // Use SynchronizeCallbacks to specify that the object 
                    // marshals callbacks across threads appropriately.
                    reader.SynchronizeCallbacks = true;

                    outputTask.Done += new TaskDoneEventHandler(outputTask_Done);
                    inputTask.Done += new TaskDoneEventHandler(inputTask_Done);
                   

                    reader.BeginReadMultiSample(Convert.ToInt32(samplesNumeric), inputCallback, inputTask);
                    outputTask.Start();
                    inputTask.Start();
                    // Setup the Task Done event
                    outputTask.WaitUntilDone();
                    inputTask.WaitUntilDone();
                    //lock (runningTask);
                }
                catch (Exception ex)
                {
                    StopTask();
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    inputTask.Dispose();
                    outputTask.Dispose();
                    cmd_start.Enabled = true;
                    cmd_Stop.Enabled = false;
                }
            }
        }

private void InputRead(IAsyncResult ar)
        {

            try
            {
                if (runningTask != null && runningTask == ar.AsyncState)
                {
                    // Read the data
                    double[] data = reader.EndReadMultiSample(ar);

                    // Display the data
                    for (int i = 0; i < inputDataTable.Rows.Count && i < data.Length; i++)
                    {
                        inputDataTable.Rows[i][0] = data[i];
                        WriteTextAsync(data[i].ToString(), tx, pass_freq);
                    }
                    for (int i = data.Length; i < inputDataTable.Rows.Count; i++)
                    {
                        inputDataTable.Rows[i][0] = DBNull.Value;
                    }

                    // Set up next callback
                    reader.BeginReadMultiSample(Convert.ToInt32(samplesNumeric), inputCallback, inputTask);
                }
            }
            catch (Exception ex)
            {
                StopTask();
                MessageBox.Show(ex.Message);
            }
        }

static async void WriteTextAsync(string text, string Name, string freq)
        {
            // Set a variable to the My Documents path.
            //string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string mydocpath = @"E:\code\imp_main\daq_data\WriteData_" + Name +"_" + freq + ".csv";

            // Write the text asynchronously to a new file named "WriteTextAsync.txt".
            using (StreamWriter outputFile = new StreamWriter(mydocpath, true))
            {
                await outputFile.WriteAsync(text+'\n');
            }
        }

with this code i have only last frequency saved to file

and i want to get 3 files with 3 frequencies as well

how i can each time get another frequency?

 

where i'm wrong in the code?

 

thanks for answers

 

0 Kudos
Message 1 of 15
(4,092 Views)

Hi Arbo,

 

If you are expecting 3 different files but only getting one, it is likely that the WriteTextAsync function is only being called once. 

 

Or it is possible that the function is in fact being called 3 times, but the data in the file is being overwritten each time and therefore you only see the data from that last frequency.

 

-Mitchell | NI

0 Kudos
Message 2 of 15
(4,048 Views)

yes indeed , how i can open separate thread for saving data to file each time , and lock the counter till the all data is saved and unlock and increment to new frequency?

0 Kudos
Message 3 of 15
(4,019 Views)

yes indeed , how i can open separate thread for saving data to file each time , and lock the counter till the all data is saved and unlock and increment to new frequency?

0 Kudos
Message 4 of 15
(4,019 Views)

If you are trying to open a new thread for writing data to a file, I suggest you look at this article from MSDN:

 

https://msdn.microsoft.com/en-us/library/ck8bc5c6(v=vs.100).aspx

0 Kudos
Message 5 of 15
(4,006 Views)

thanks

 

but this article more compatible for controls and forms using... that i need is to lock (for loop counter. this loop must wait until thread is ends his measurement and append data to file and after this will increment his value)

 

i saw interlocked.increment method but it very confusing , i did not understand it.

 

 

0 Kudos
Message 6 of 15
(4,002 Views)

I should have asked this before, but what software, OS, and hardware are you using (please include software versions)?

0 Kudos
Message 7 of 15
(3,994 Views)

Hi

 

i'm using Windows 7 64 bit, visual studio 2015, ni daq 15.0

 

hardware: intel core i5, 8gb ram

0 Kudos
Message 8 of 15
(3,992 Views)

Are you using Measurement Studio?

0 Kudos
Message 9 of 15
(3,972 Views)

no

 

i'm using clean visual studio 2015 with reference add-ons:

nationalinstrument.comon.dll and nationalinstrument daqmx.dll

0 Kudos
Message 10 of 15
(3,970 Views)