How to filter starttrigger on counter output precisely

HW PCI6602
Measurement studio 2008 (C#)NI-DAQmx 9.02I’m trying to trig a camera using the output from a counter.
The camera should be trigged when the counter input pulse width is larger than approx (filterPulseWidth 10us).To do this a have set up the following tasktask.COChannels.CreatePulseChannelTime(counter,                "TriggerTaskChannel", COPulseTimeUnits.Seconds, COPulseIdleState.Low, 0, 80E-6, 0.007);             task.Triggers.StartTrigger.Type = StartTriggerType.DigitalEdge;            task.Triggers.StartTrigger.DigitalEdge.Edge = DigitalEdgeStartTriggerEdge.Rising;             task.Triggers.StartTrigger.Retriggerable = true;task.Triggers.StartTrigger.DigitalEdge.DigitalFilterMinimumPulseWidth = filterPulseWidth;            task.Triggers.StartTrigger.DigitalEdge.DigitalFilterEnable = true;Unfortunatly this filter has the following behaviour”If the period of the filter clock timebase is tfltrclk, this filter guarantees topass pulse widths that are 2*tfltrclk or longer and to block pulse widths thatare tfltrclk or shorter. A pulse with a width between these two ranges may ormay not pass, depending on the phase of the pulse with respect to the filterclock timebase”.It means that I have no sharp distinction on my filter as one would when applying a filter to an ordinary pulse width measuring task. Implementing this with via the software in a callback is to slow.The bottom line is that I would like to generate a pulse on my counter output when the trigger/counter input is greater than say 10us. The output pulse could be predetermind as in the sample code above or as long as the filtered input (I.e counter just pass filtered input to my output).How can this be done? BR
Jongas
Solved!
Go to Solution.

Hi Jongas,
Is it OK if the trigger is sent once the pulse hits 10 us, rather than
on the exact falling edge?  I'll assume the exact timing isn't as important, but you would like the trigger to occur very close to the falling edge (within a couple of us).  The important thing is that we trigger as close as possible to when the PWM has hit 50% duty cycle.
Some brainstorming:
Digital Filtering on the 660x Isn't the Best for This:
Digital filtering might not be as practical here on your 6602 due to the region of uncertainty between 5 and 10 (or 10 and 20) us pulses.  The TIO boards count two consecutive edges of a filter clock to determine when to pass a signal through so the guaranteed rejected pulse width is always half of your guaranteed passed pulse width (providing an external filter clock timebase that is synchronized with your external signal could potentially reduce this uncertainty but I honestly haven't tried this before and I would imagine it is not going to be very straightforward).
X Series Alternative:
Our X Series devices use a different method of digital filtering that would work better for you.  If a hardware change is an option (and you can use PCIe) then you might consider this.  You could use the 20 MHz timebase as your filter clock timebase and could guarantee to pass 10 us (200/20M) and reject 9.95 us (201/20M).  The 6320 is currently our lowest cost X Series board.  A couple of points about this solution:
1.  To configure the PFI filter, you need to use some sort of dummy task to
access the property nodes.  Here is an
example of this (although it is written in LabVIEW).
2.  You can route the filtered PFI signal to be exported on another PFI line, but this will reserve Counter 3.  This is documented in the Device Routes tab of Measurement and Automation Explorer.
3.  The filtered output will be 9.95-10 us delayed from the input signal, so you could trigger the camera off of the rising edge of the filtered output directly and be fairly close to the actual falling edge.
External AND Gate Alternative:
You could configure a Counter Output to generate a re-triggerable pulse with a 10 us initial delay (to be triggered off of the rising edge of your PWM signal).  Assuming the pulse is short enough to complete before the next period of your PWM signal, the counter output would only be high at the same time as the PWM signal if the signal was longer than 10 us.  Use the external AND gate to combine these two signals and the result would be the trigger for your camera (the rising edge would correspond to 10 us after the PWM signal first goes high).
If you wanted to you could make the counter output pulse a little longer (say 8 us) and trigger the camera off of the falling edge out of the AND gate (a.k.a. rising edge out of a NAND gate) which would line up with the exact falling edge of the PWM signal.  Don't make the CO pulse too long or it will overlap with the next period of the PWM.
Another Idea:
One idea that I keep coming back to is to use the internal rollover event of a counter input task (a pulse is generated whenever a counter rolls over on its Internal Output which can be routed to a PFI line).  I don't think this will work, but the idea in theory would be to:
1.  Set Default state to known value (e.g. 2^32-200).
2.  Gate the Counter so it only counts during the time PWM is high.  Have it count the 20 MHz timebase.
3.  Reset the Counter to default state on the falling edge of the PWM signal.
4.  The counter would rollover if 200 pulses occurred of the 20 MHz timebase (10 us), and the Counter Output could be routed to a PFI line to trigger the camera.
The problem is that there is no good way to reset the counter except for an encoder measurement (Kevin has already made a nice suggestion about this).  A Pulse Width Measurement would technically reset the counter, but you cannot currently set the default value of a Pulse Width Measurement task so there is no way to make the rollover happen prematurely).
Configuring an encoder measurement and working with the multiple counters on the 6602 to produce appropriate A,B, and Z signals might be a method to look into further, but at this point I think you'd be better off with an external AND gate.
I don't want to say it's impossible with just the 6602, but I can't think of a straightforward way to go about it without external hardware (although maybe I can sleep on it and think of something later... how many counters do you have to work with?). 
With your current NI Hardware, I think your best bet is to go with an external AND gate.  If you're planning on purchasing an X Series card the digital filtering idea is actually not a bad way to go.
I hope this is helpful!
Best Regards,
John Passiak

Similar Messages

  • How to import 6602's counter output to PFI3 of the 6534 board?

    Dear friends,
    I have the following problem:
    I am trying to import the output of one of the counters of the 6602 board (counter 4) to
    the REQ2 (PFI3) line of the 6543 board (please see the VI attached). But I do
    not see any signal on the PFI3 line though the VI runs without errors.
    The situation is the same if I connect output of the counter to the PFI3 directly in the "Connect Terminals" VI instead of connecting it via PXI_Trig4 line.
    I need your help to understand why is it so and how can I accomplish the
    "import" task.
    Thanks in advance!
    Attachments:
    counterImport.vi ‏28 KB

    Hi Andrew,
    You are absolutely right - there should be PFI20 instead of PFI26.
    It works now. Thank you!
    .....I hope you can give some ideas with regard to the following problem:
    In a program I used four 6602's counters (counters 0-3) to generate single trigger
    pulses on the backplane of the PXI.
    It worked fine.
    Now I want to incorporate the fifth counter into the program (counter 4) to
    generate a finite pulse sequence on the PFI3 line of the 6534 board.
    And I can not do this.
    Code example is in the VI attached.
    When I try to run this VI it gives error:
    Error -89137 occurred at DAQmx Connect Terminals.vi:4
    Possible reason(s):
    Specified route cannot be satisfied, because it requires resources that are
    currently in use by another route.
    Source Device: TimingIO
    Source Terminal: PFI36
    Destination Device: TimingIO
    Destination Terminal: PXI_Trig0
    Required Resources in Use by
    Source Device: TimingIO
    Source Terminal: PFI20
    Destination Device: TimingIO
    Destination Terminal: PXI_Trig4
    I do not understand why it happens and how to correct this....
    Thanks!
    Attachments:
    counterImport 2.vi ‏79 KB

  • How to use counter output pulses to trigger analog input?

    Hello all,
    I hope the kind people using this forum can help me, a lowly beginner LV programmer! I have been attempting to create a VI that produces a user defined number of TTL pulses, separated by every n seconds. Each TTL would be outputted to a stimulator, which in turn generates its own TTL. Using the stimulator-generated TTL, I would like to trigger finite analog data acquisition (e.g. for every TTL, trigger the collection of a data sweep that contains 4000 samples (collected at 4000 Hz), with 1000 samples collected pre-trigger. I would like to also be able to see each data sweep as it is triggered on a chart. As I understand things (lots of online/book/forum reading), I should be using the counter output to generate my TTL pulses, and syncing each counter produced TTL with analog input, as well as using a reference trigger. Also, the AI part should be started first, so that I don' t miss any counter outputs. If it matters, I also need to use one of the AI channels to acquire the TTL, so I can see my stimulator-induced responses to the stimulator in time.
    I am able to generate the TTL pulses from the counter output, but I am having a problem with the AI part. I am unsure how to sync the counter output with AI. Also, since I need to acquire pre-trigger samples, I would be needing to acquire samples continuously, but when I set 'continuous samples' on daqmx timing, the VI doesn't work (hence why's its set to 'finite samples').
     I hope someone out there can help, as I have been at this for what seems ages, with limited success. I am using a USB-6259 and LabView v8.2. Thanks!
    Attachments:
    RC001 v_1.vi ‏49 KB

    Hello,
    Due to the fact that analog tasks themselves are not retriggerable, a
    pulse train produced by a counter is always used as the sample clock
    for the analog input task in order to recreate a retriggerable effect
    for analog input. This can be done by creating a finite pulse train set
    to retriggerable using the DAQmx Trigger Property Node, or the pulse
    train could be continuous and just be gated by another signal. Neither
    of these methods can be properly applied in hardware to create a
    retriggerable reference trigger. You can however implement something
    similar in software by just stopping and restarting your reference
    triggered analog input task within a loop. There will be some delay
    between when the task is stopped and restarted, as these events require
    software intervention, but if there is enough time between when each
    trigger signal is generated, there should not be any noticeable delay
    or missed samples.
    I have attached an example of this!
    Mark B
    ===If this fixes your problem, mark as solution!===
    Attachments:
    RC001 v_1mod.vi ‏25 KB

  • I am using the dynamic signal analyzer.vi but this vi has the output as single precision. How can I change this to DBL precision?

    I am using the dynamic signal analyzer.vi but this vi has the output as single precision. How can I change this to DBL precision? If I change the representation from single to double in the AI buffer read.vi labview returns ilegal operation and crash. I have labview 5.1 on windows 95 and one AT-MIO16XE50 DAQ board.
    Thanks in advance
    Ricardo.

    Probably by changing the data type that lvdaq.dll expects to write to is causing the crash. I can't test this since I have only 6.1 installed now. In any case, since the daq card is only 16 bits, the single precision is probably adequate for AI Buffer Read. If you do need the greater precision later on, you should be able to change representation in any one of the upper level VIs.

  • How to Immediately Change Counter Output Rate?

    I have a piece of code that largely works like this example: http://zone.ni.com/devzone/cda/epd/p/id/5493
    In other words, I set up the Counter Output with some initial frequency and duty cycle, but then during the main loop of my program I continuously change the frequency to a new value based on other criteria.
    I'm using an M-series PXI card and LabVIEW RT.
    The problem I'm having is that the card waits for the next edge before changing the counter output rate. For instance, lets say it is going at a low frequency and I am upping to a high frequency. If the command arrives in the middle of the current pulse, it will wait to complete the low-rate pulse before starting the high frequency output. Is there a way to make it interrupt the current count and immediately start counting at the new rate?
    Thanks,
    Isaac

    Hi Isaac,
    I posted the code in LV 8.2 so you should be able to open it now (it sometimes takes several minutes to upload).
    There are a few limitations to using the digital lines instead of the counters:
    1.  The digital lines are updated off of a sample clock which will be much slower than a timebase.  For example, on the 6221 the maximum update rate is 1 MHz, while the counter output has a max timebase of 80 MHz. As a result, the number of frequencies you can generate are going to be more restricted (divide down from 1 MHz vs. 80 MHz).
    2.  On M series devices, the digital lines must be clocked from an external source.  This could be generated from a counter
    3.  You have to build the digital waveform, which is a bit tricky (I think the example code should help out with that but I haven't had time to thoroughly test it).
    4.  If you are generating digital lines at fast rates, you will need to write quite a few samples at a time to the output buffer to ensure the data does not underflow.  If the buffer includes multiple periods of the digital signal, you would have the case that using the counter output would still update more immediately.
    Again, to determine the best course of action it would be useful to know what frequencies you want to generate and which exact hardware you are using. I just mentioned the digital lines as an alternative to the counters, but it might not be ideal for your situation.
    -John
    John Passiak

  • How to disable (turn off) a counter output

    I have a similar question up on the the board but I thought I would ask it in another way to make it simple and straightforward. 
    Can an E-series counter output be disabled (and enabled) quickly through some software command?  When I say " disabled" I mean switched off to a TTL low state.  I have tried both the "disable" counter control command and gating the counter with a TTL signal.  Both methods leave the output pin in whatever state the output happens to be in at the time of the command or gating.  I need a disable function where "disabled" automatically sets an OFF or LOW on the output.  I am using this to generate a pulse train where the pulse train switches off at certain times, and I cannot have the output remain high at these times.
    I am using traditional DAQ but if there is a method in DAQmx that works I'd be willing to try it...

    Have you tried using the following vi with a reset command (search in help, it works with the E series counters)
    Counter Control
    This VI controls groups of counters. Control operations include starting, stopping, and setting the state of active acquisitions. This VI works with DAQ-STC and NI-TIO-based devices.
    Control code 1 (reset) reinitializes the counter back to the default settings.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    "It’s the questions that drive us.”
    ~~~~~~~~~~~~~~~~~~~~~~~~~~

  • How to copy, rather than export, a Counter output?

    Hi,
    In DAQmx (in C++), using an E-Series board, I have exported a Counter output to an RTSI line. This works fine. However, perhaps to be expected, the signal disappears from the Ctr0 output. For debugging and logging purposes, I would like to retain a copy of the original Counter pulse, while Exporting it to the RTSI line.
    Is there a way to copy, say, a control signal? i.e. set up a 1-to-2 terminal routing?
    Specifically, I want /Dev/Ctr0 to still be accessible on PFI6 and the SAME signal to be copied/routed/exported to an RTSI line.
    Thanks for any advice.
     - Per

    Hi Per,
    Yes, you can do this using DAQmx connect terminals.
    int32 DAQmxConnectTerms (const char sourceTerminal[], const char destinationTerminal[], int32 signalModifiers);
    You can locate this in the DAQmx C reference help by searching "route terminals".
    Regards,
    Greg H.
    Applications Engineer
    National Instruments

  • Counter Output/Counter Input PXI Signals Behaving Erratically

    Question for all your LabVIEW guru's out there,
    I am running a frequency loopback test using the NI PXI 6229 MIO DAQ card.  I am generating a "Counter Output" pulse train signal which feeds through my device under test and then back out of my device under test and back into the PXI 6229 for a "Counter Input" frequency measurement.  Both the "Counter Output" and the "Counter Input" are assigned different PFI lines using DAQmx in LabVIEW.
    I have 4 lines to test on my DUT.  All four lines run this same frequency measurement but with different PFI lines on the PXI 6229.  Each line is test independently.
    This is my setup for the 4 lines:
    Path 1: P2.0 (Counter Output - Pulse Train) -> DUT (Device Under Test) -> P2.1 (Counter Input - Frequency Measurement)
    Path 2: P2.2 (Counter Output - Pulse Train) -> DUT (Device Under Test) -> P2.3 (Counter Input - Frequency Measurement)
    Path 3: P2.4 (Counter Output - Pulse Train) -> DUT (Device Under Test) -> P2.5 (Counter Input - Frequency Measurement)
    Path 4: P2.6 (Counter Output - Pulse Train) -> DUT (Device Under Test) -> P2.7 (Counter Input - Frequency Measurement)
    where:
    P2.0 = PFI8
    P2.1 = PFI9
    P2.2 = PFI10
    P2.3 = PFI11
    P2.4 = PFI12
    P2.5 = PFI13
    P2.6 = PFI14
    P2.7 = PFI15
    I have a LabVIEW VI which generates the "Counter Output" and reads the "Counter Input" frequency.  I am seeing weird behavior from the PXI 6229 card. I can test "Path 1" and "Path 2" and the frequency I read is what I generated. No issue there. However, when I test "Path 3" and "Path 4" the frequency measurement is erratic.  The readings are two different frequencies repeated over and over again and none of those frequencies are the expected frequency which was generated out of the "Counter Output."  If I reset the card, and start by testing "Path 3" and "Path 4" the frequency readings are correct and the erratic behavior is gone.  However, when I try to then test "Path 2" and "Path 1" now those lines have the erratic frequency issue. I can continue resetting the card and see same issue. The PFI lines that I test first will always pass.
    To summarize:
    Steps Taken:
    1. Test Path 1 = SUCCESS
    2. Test Path 2 = SUCCESS
    3. Test Path 3 = Erratic Frequency (Two Frequencies repeated over and over again in my frequency results array)
    4. Test Path 4 = Erratic Frequency (Two Frequencies repeated over and over again in my frequency results array)
    5. Reset the PXI 6229 Card
    6. Test Path 3 = SUCCESS
    7. Test Path 4 = SUCCESS
    8. Test Path 3 = Erratic Frequency (Two Frequencies repeated over and over again in my frequency results array)
    9. Test Path 4 = Erratic Frequency (Two Frequencies repeated over and over again in my frequency results array)
    I am wondering if Port 2 (P2.0-P2.7) on the 6229 card has certain dependecies and this is why I am seeing issues.  I am trying to get around this issue so that I don't have to always reset the card.
    Are P2.0-P2.3 (PFI8-PFI11) and P2.4-P2.7 (PFI12-PFI15) treated differently or require different setup?  How do I resolve this issue?
    Thanks so much!

    I have a theory...
    The DAQ card follows a policy called "lazy uncommit" wherein the terminal used for the output will continue to be connected to the counter even after the task has completed (until the terminal is needed for something else).  So as you run more tests, the counter output will end up driving more lines.  This behavior should be easy enough to confirm.
    As the DAQ card drives more lines, I'd imagine this affects the actual signal.  You could scope it to check, but it sounds like either the rise/fall times are becoming longer or some extra noise is being introduced on the line.  
    The readings are two different frequencies repeated over and over again and none of those frequencies are the expected frequency which was generated out of the "Counter Output."
    This implies you are picking up an extra edge during transitions--this isn't too uncommon if the signal is noisy since there is no built-in hysteresis on the DAQ card.  I would expect the measured frequencies to have periods that sum to either the full period or the semi-period of your actual signal (depending on how many duplicate edges are detected).
    Suggestions are as follows:
    To stop the DAQ card from driving multiple PFI lines, it would probably be easiest to just programmatically reset the device in between your tests (using DAQmx Reset Device).  If you can't reset the device (e.g. because you are running some other task that can't be interrupted) then you can instead configure a dummy task that uses the PFI line in question as an input.
    To stop the DAQ card from picking up multiple edges during transitions, you should configure a digital filter on the input terminals.  If you reset the device it sounds like this might not be necessary... it's up to you if you want to configure this or not.
    Best Regards,
    John Passiak

  • Counter Output as Sample Clock of Digital Signals

    I have a situation where I need to use a hardware counter as sample clock of digital output signals.
    How do you specify the "Counter Internal Output" signal as a sample clock of digital output?
    I want to do something like this:
      // Create counter task
      CNiDAQmxTask m_Task(_T("ATask"));
      m_Task.COChannels.CreatePulseChannelTicks(_T("Dev1/ctr0"), "", _T("20MHzTimebase"), DAQmxCOPulseIdleStateLow, 0, 10, 10);
      m_Task.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("PFI0", DAQmxDigitalEdgeStartTriggerEdgeRising);
      // Create digital output task                     
      CNiDAQmxTask m_Task2(_T("ATask2"));
      m_Task2.DOChannels.CreateChannel("Dev1/port0/line0", "", DAQmxOneChannelForAllLines);
      m_Task2.Timing.ConfigureSampleClock("XXXXXX", 0, DAQmxSampleClockActiveEdgeRising, DAQmxSampleQuantityModeFiniteSamples, 400);
    How do I specificy "counter 0 Internal Output signal" instead of "XXXXXX" above, i.e. the sample clock of the digital output signal. Can't find the name of the signal anywhere in the documentation and help files. I have a 6259 DAQ board. 
    /pek

    Thank you for your answers, but I can't get it to work.
    When I use "ai/SampleClock" as sample clock everything works correct. When I try to use a counter as sample clock the task completes imediately, before any digital signals has been sent/measured. The task even completes before I have started the trigger, which is very confusing. No error appears.
    I think that something is wrong about how I setup the counter. I use the code below:
    // Create counter task
    CNiDAQmxTask m_Task(_T("ATask"));
    m_Task.COChannels.CreatePulseChannelTicks(_T("Dev1/ctr0"), "", _T("20MHzTimebase"), DAQmxCOPulseIdleStateLow, 0, 100, 100);
    m_Task.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("PFI0", DAQmxDigitalEdgeStartTriggerEdgeRising);
    // Create digital output task
    // The code below works with "ai/SampleClock" as sample clock
    CNiDAQmxTask m_Task3(_T("ATask3"));
    m_Task3.DOChannels.CreateChannel("Dev1/port0/line0", "", DAQmxOneChannelForAllLines);
    m_Task3.Timing.ConfigureSampleClock("Dev1/Ctr0InternalOutput" /*"ai/SampleClock"*/, 0, DAQmxSampleClockActiveEdgeRising, DAQmxSampleQuantityModeFiniteSamples, 400);
    // Create samples
    CNiUInt32Vector ui_data;
    for(int i = 0; i < 200; i++)
      for(unsigned int j = 0; j < 2; j++)
        ui_data.Append(j);
    // Create digital writer
    CNiDAQmxDigitalSingleChannelWriter m_writer3(m_Task3.Stream);
    m_writer3.WriteMultiSamplePortAsync(true, ui_data);
    // Wait until task completes
    m_Task3.WaitUntilDone(-1);

  • Can I generate pulse trains on more than one counter output at the same time?

    I have a PCI 6601 card with a BNC 2121 to connect the signals to two devices. The card is used as a trigger for both devices and I want to be able to generate pulse trains on two output channels at the same time, with a time delay between the two. How do I do that in Labview 7.1 Development with DAQmx?

    I feel foolish for not being able to figure this out, but it still doesn't work. Attached is the VI I use now. Counter 0 generates a finite pulse train and I programmed Counter 1 to generate a retriggerable single pulse triggered by CtrOinternaloutput. I still get the same error message: -50103 The specified resource is reserved. The operation could not be completed as specified.
    The same happens if I set the trigger for counter 1 at PFI36 (default output of counter 0) or any other PFI line. If I try a pulse train generation on only one of the counters, both work fine.
    If I try the example in traditional DAQ for multiple counter outputs with phase delay, it works fine.
    Can you tell me what I'm doing wrong?
    Attachments:
    Shutter_AND_lamp_trigger.vi ‏103 KB

  • How to filter datagridview from 3 textboxes?

    hey, would you help me 
    so, i have a form and connects to mdb database.
    this is my code
    Imports System.IO
    Imports System.Data.OleDb
    Public Class Form1
    Private DBPath As String
    Private conn As OleDbConnection
    Private adapter As OleDbDataAdapter
    Private dtMain As DataTable
    Public Sub New()
    InitializeComponent()
    End Sub
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    DBPath = Application.StartupPath + "\db.mdb"
    If Not File.Exists(DBPath) Then
    Dim cat As New ADOX.Catalog()
    cat.Create(Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") & DBPath)
    cat = Nothing
    End If
    conn = New OleDbConnection(Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") & DBPath)
    conn.Open()
    Try
    Using cmd As New OleDbCommand("CREATE TABLE [Table_1] ([id] COUNTER PRIMARY KEY, [text_column] MEMO, [int_column] INT);", conn)
    cmd.ExecuteNonQuery()
    End Using
    Catch ex As Exception
    If ex IsNot Nothing Then
    ex = Nothing
    End If
    End Try
    Using dt As DataTable = conn.GetSchema("Tables")
    For i As Integer = 0 To dt.Rows.Count - 1
    If dt.Rows(i).ItemArray(dt.Columns.IndexOf("TABLE_TYPE")).ToString() = "TABLE" Then
    ComboBoxTables.Items.Add(dt.Rows(i).ItemArray(dt.Columns.IndexOf("TABLE_NAME")).ToString())
    End If
    Next
    End Using
    End Sub
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    If ComboBoxTables.SelectedItem Is Nothing Then
    Return
    End If
    adapter = New OleDbDataAdapter("SELECT * FROM [" + ComboBoxTables.SelectedItem.ToString() + "]", conn)
    Dim builder = New OleDbCommandBuilder(adapter)
    dtMain = New DataTable()
    adapter.Fill(dtMain)
    DataGridView1.DataSource = dtMain
    End Sub
    End Class
    and now i have 4 textbox and 4 column table of database.
    for example, this is my table :
    and if i type :
    textbox 1 : "1"
    textbox 2 : "2"
    textbox 3 : "1" then i press button2.
    the result is textbox4 display : "C"
    other example, if i type textbox1 : "3", textbox2 : "3", textbox3 : "2" then textbox4 diplay "J".
    of course, if i type textbox1 : "3", textbox2 : "3", textbox3 : "2" then i'll get msgbox "max for column 2 is 2" or 
    if i type textbox1 : "3", textbox2 : "4", textbox3 : "2" i'll get msgbox "max of column 1 is 3"
    well, now im stuck, how to filter this. 
    thanks before. sorry for bad english.

    Hello,
    The following uses Lamda and LINQ to query three text box controls where each one has a unique tag value, TextBox1.Tag = 1, TextBox2.Tag = 2, TextBox3.Tag =3. The Tag is used to dictate the order of the columns in the where condition.
    In values, a where condition is used to determine any TextBox controls with Text then in the select I create a condition suitable for use in the SQL SELECT. In the variable WhereClause the conditions are combined. There is one or more conditions they are
    appended to the SQL statement.
    Now if we have to deal with columns of type string we need to surround them in apostrophes which opens up a can or worms if a string contains apostrophes so food for thought.
    Code suitable for VS2012 or higher, for VS2010 line continuation is needed.
    ''' <summary>
    ''' Each TextBox (three of them) have their tag set to 1,2,3 for ordering columns
    ''' in the where clause.
    ''' The Where conditions are using "and", you can also do "or" instead
    ''' </summary>
    ''' <remarks></remarks>
    Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) _
    Handles Button1.Click
    Dim SelectStatement As String = "SELECT * FROM SomeTable"
    Dim Values = Me.Controls.OfType(Of TextBox).Where(
    Function(tb) Not String.IsNullOrWhiteSpace(tb.Text)).Select(
    Function(tb)
    Return New Item With
    .Index = CInt(tb.Tag),
    .Value = tb.Tag.ToString & " = " & tb.Text
    End Function).ToList.OrderBy(Function(item) item.Index)
    Dim WhereClause = String.Join(" and ",
    (From T In Values Select T.Value).ToArray)
    If Not String.IsNullOrWhiteSpace(WhereClause) Then
    SelectStatement &= " WHERE " & WhereClause
    Else
    ' Nothing to append
    End If
    Console.WriteLine(SelectStatement)
    End Sub
    End Class
    ''' <summary>
    ''' Strong type data in the select part of the
    ''' lambda statement above
    ''' </summary>
    ''' <remarks></remarks>
    Public Class Item
    Public Property Index As Integer
    Public Property Value As String
    Public Sub New()
    End Sub
    End Class
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

  • How do I configure a counter to generate pulses using DAQmx?

    How do I configure a counter to generate pulses using DAQmx?
    Is says in the DAQmx C reference help
    "CtrnInternalOutput—The signal at this internal terminal is where the pulsed or toggled output of the counter appears. The output of a counter pulses or toggles when the counter reaches terminal count. When counting down, the counter reaches terminal count when the count reaches zero. When counting up, the counter reaches terminal count when the counter rolls over. To configure the counter to toggle or generate pulses, use the Export Signal function/VI with Counter Output Event as the signal name."
    I've tried this but can't get it to work, I may have the parameters wrong or something. The DAQmxExportSignal() function is very unintuitive to me. Here is my counter config code...
    int ret = 0;
    ret = DAQmxCreateTask("",&task_);
    errorMsg(ret);
    if (ret != 0)
    throw ret;
    // Configure the counter
    ret = DAQmxCreateCOPulseChanTicks( task_, "Dev1/ctr0", "", "/Dev1/PFI8", DAQmx_Val_Low, 0, divider, divider );
    errorMsg(ret);
    ret = DAQmxCfgImplicitTiming( task_, DAQmx_Val_ContSamps, 1000 );
    errorMsg(ret);
    // Change to pulse mode
    ret = DAQmxExportSignal( task_, DAQmx_Val_CounterOutputEvent, "/Dev1/Ctr0InternalOutput" );
    errorMsg(ret);
    // Start the counter
    ret = DAQmxStartTask(task_);
    errorMsg(ret);
    The above code works fine, in toggle mode, if I just comment out the DAQmxExportSignal() part.
    HELP!!!
    Stefan

    The problem is due to the DAQmxExportSignal call.  By default, when you create a counter output pulse train task, the driver will automatically set the output of the counter to toggle when the count for each high ticks and low ticks expire.  The driver also automatically routes the signal present at Ctr0InternalOutput terminal (the output of the counter internal to the device) to the Ctr0Out terminal (the I/O pin available externally).  Using the line
     ret = DAQmxExportSignal( task_, DAQmx_Val_CounterOutputEvent, "/Dev1/Ctr0InternalOutput" );
    will tell the driver to tristate the Ctr0Out terminal and not output the signal to the external I/O pin.  Using the DAQmxExportSignal function is generally only useful if you want to route the signal to some other terminal internal to the board without having the output show up on the external connector, route the signal to some other external pin other than the default pin, or if you want to have the output show up at multiple locations. 
    If you want to change the output behavior from toggle to pulse, you need to use the DAQmxSetExportedCtrOutEventOutputBehavior function.  However, this is generally only useful if all you care about are edges (not the duty cycle of the pulse train), and you want to generate higher frequency signals.  For example, with a 20 MHz timebase as the source of your counter, you can only generate a 5 MHz pulse train by default.  This is because the minimum value for the low and high ticks parameter is 2 (20 MHz / 4 = 5 MHz).  By changing the output behavior form toggle to pulse, you can generate a pulse train at 10 MHz since the output is now pulsing instead of toggling.  However, the width of each pulse is not programmable so you will no longer have a 50% duty cycle signal.  I don't remember exactly what the width of each pulse is, but I believe it's in the neighborhood of 50 - 100 nanoseconds in width.  I hope this information helps.

  • Variable frequency counter output

    I found this example of how to vary the frequency of a counter output, but it appears this is not supported and i receive the following error. Can anyone tell me if there is an alternative method at all? my device is a usb6341 which has 4 COs
    thanks
    Attachments:
    Capture.JPG ‏118 KB

    If you found that code in an NI-provided example, it's probably more likely that the operation is not supported by your specific hardware.
    What is the range of frequencies you want to create?
    How accurate does the clock need to be?
    How often will the frequency be changing?
    Can the hardware receiving the clock tolerate and "discontinuities" in the pulse train?
    You could momentarily stop the clock, change the setting and then restart it.
    MIke...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • How to filter Key Figures - not using the GUIDs

    An example How to filter Key Figures may look like this:
    http://XXX.com:8000/sap/bw/BEx?sap-language=DE&bsplanguage=DE&CMD=LDOC&TEMPLATE_ID=XXX&FILTER_IOBJNM=41F68RV4ZB5VYSARODYU70CAQ&FILTER_VALUE=41F68SAI18DB01DO023IR49QA
    The GUIDs consume the space in the URl. Is there a way to work with an alias.
    To use the technical name of a Key Figure defined in the Query does not work.

    Hi Cherie,
    This is exactly the type of problem that I'm currently trying to figure out. I'm trying to following your solution but I'm not clear on how you actually achieved this in you last note. I want to dynamically select actuals/budget column fields based on what period I enter. I thought about creating 12 separate RKF fields for actuals and 12 separate RKF fields for the budget reforecast and outputting these all and then doing some VBA to hide the fields not required based on which period was selected... how is your variable ZFYAPER7 defined and calculated?
    Cheers

  • Please help with C code to synchronize counter output to analog input

    Hi All,
    I am using NI DAQ USB-6353 with text-based C code to control it. I would like to send a continuous pulse train from the DAQ to pulse a power supply, which then activates an electron beam producing current to be read by the analog input port of the same DAQ. I would like to keep only the analog samples during the pulse peak and samples of a couple pulse widths right after. I am successfully to generate a pulse train using the sampled clock from a counter output channel, but fail to use the same clock to synchronize the pulse train with the analog input. DAQmxReadAnalogF64 is not called by the static function EveryNCallback set for the analog input task. Am I doing something wrong with the following codes? It would be great if it turns out only I am using the wrong sampled clock name of the counter ("dev1/PFI8") for the analog input. Or is something more fundamental that a counter cannot be sync. with an analog input?
    Would someone be able to send me a link to an example in C or C++ or visual basic showing how to synchronize a buffered sample clocked digital pulse train from a counter output channel to an analog input? To simplify the post, the below codes do not include the static functions EveryNCallback and DoneCallBack, but I can send them if needed.
    Many thanks in advance for your help,
    Thuc Bui
    //setting operation parameters
    double initDelay = 0.0, freq = 10;
    double dutyCycle = 0.0001;           //thus pulse width is 10 microsec
    unsigned highTicks = 4;   //per period
    unsigned numSamplesPerPeriod = highTicks / dutyCycle;   //40000 samples/period
    unsigned lowTicks = numSamplesPerPeriod - highTicks;      //per period
    unsigned sampleRate = 2*numSamplesPerPeriod*freq;       //800000 samples/s
    //create counter
    TaskHandle counterTask;
    int errCode = DAQmxCreateTask("", & counterTask);
    errCode = DAQmxCreateCOPulseChanFreq(counterTask, "dev1/ctr0", "",
                                     DAQmx_Val_Hz, DAQmx_Val_Low,
                                     initDelay, freq, dutyCycle);
    errCode = DAQmxCfgSampClkTiming(counterTask, "dev1/PFI8", sampleRate, DAQmx_Val_Rising,
                               DAQmx_Val_ContSamp, numSamplesPerPeriod);
    //create analog input
    TaskHandle aiTask;
    double minVolt = 0.0, maxVolt = 1.0;
    errCode = DAQmxCreateAIVoltageChan(aiTask, "dev1/ai0", "", DAQmx_Val_Diff,
                                     minVolt, maxVolt, DAQmx_Val_Volts, "");
    unsigned bufferSize = 10* numSamplesPerPeriod;
    errCode = DAQmxSetBufInputBufSize(aiTask, bufferSize);
    errCode = DAQmxCfgSampClkTiming(aiTask, "dev1/PFI8", sampleRate, DAQmx_Val_Rising, DAQmx_Val_ContSamp, numSamplesPerPeriod);
    errCode = DAQmxRegisterEveryNSamplesEvent(aiTask, DAQmx_Val_Acquired_Into_Buffer,
                                            numSamplesPerPeriod, 0, EveryNCallback, 0);
    errCode = DAQmxRegisterDoneEvent(aiTask, 0, DoneCallBack, 0)
    //start aiTask first
    errCode = DAQmxStartTask(aiTask);
    //then counterTask
    errCode = DAQmxStartTask(counterTask);

    Hi Xavier,
    Thank you very much for getting back to me. I really appreciate it. I followed your advice with the option 2 and simplified my code by using one of the NI C example templates to generate the below codes (also attached). I was able to see the pulses generated with an oscilloscope, and on the same oscilloscope I could see the ouput pulses of the electron beam probe. Unfortunately, the below code via DAQmxReadAnalogF64 reports of no data read from the probe and finally times out. Below is the error message given by this function. I did check the connection of the analog input wires to make sure they were connected to pin 1 (A0+) and 2 (A0-) because I was using the terminal configuration DAQmx_Val_Diff. Do you see any obvious errors I have made in my codes?
    Thanks a lot for your help,
    Thuc Bui
    Task started, waiting for trigger...
    Acquired 0 analog samples DAQmx Error: Some or all of the samples requested have not yet been acquired.
    To wait for the samples to become available use a longer read timeout or read later in your program. To make the samples available sooner, increase the sample rate. If your task uses a start trigger,  make sure that your start trigger is configured correctly. It is also possible that you configured the task for external timing, and no clock was supplied. If this is the case, supply an external clock.
    Property: DAQmx_Read_RelativeTo
    Corresponding Value: DAQmx_Val_CurrReadPos
    Property: DAQmx_Read_Offset
    Corresponding Value: 0
    Task Name: _unnamedTask<1>
    Status Code: -200284
    End of program, press Enter key to quit
    ********************** C Code **************************************************
    #include <stdio.h>
    #include "NIDAQmx.h"
    #include <math.h>
    #define DAQmxErrChk(functionCall) { if( DAQmxFailed(error=(functionCall)) ) { goto Error; } }
    int main(void) {  
    int32 error = 0;  
    char errBuff[2048]={'\0'};
    TaskHandle  taskHandleDig=0;  
    TaskHandle taskHandleAna=0;    
    double  timeout=10;  
    double minVol = -1.0, maxVol = 1.0;
    double initDelay = 0.0;  
    double freq = 10.0;  
    double pulseWidth = 1.0e-5; //10us  
    double dutyCycle = pulseWidth * freq;
    unsigned hiTicks = 4;  
    double sampleRate = hiTicks/pulseWidth; //samples/s  
    unsigned lowTicks = ceil(sampleRate/freq) - hiTicks;  
    unsigned nSpPeriod = hiTicks + lowTicks;
    unsigned numPulses = 1;  
    unsigned nSpCh = numPulses*nSpPeriod;    
    double sampleRate2 = ceil(2.0*sampleRate);  
    unsigned sampleMode = DAQmx_Val_FiniteSamps;
     /*********************************************/  /*/ DAQmx Configure Code  /*********************************************/  
    DAQmxErrChk(DAQmxCreateTask("", &taskHandleDig));  DAQmxErrChk(DAQmxCreateTask("", &taskHandleAna));    
    DAQmxErrChk(DAQmxCreateAIVoltageChan(taskHandleAna, "Dev2/ai0", "", DAQmx_Val_Diff, minVol, maxVol, DAQmx_Val_Volts, ""));  
    DAQmxErrChk(DAQmxCfgSampClkTiming(taskHandleAna, "/Dev2/Ctr0InternalOutput", sampleRate2, DAQmx_Val_Rising, sampleMode, nSpCh));
    DAQmxErrChk(DAQmxCreateCOPulseChanFreq(taskHandleDig, "Dev2/ctr0", "", DAQmx_Val_Hz, DAQmx_Val_Low, initDelay, freq, dutyCycle));  
    DAQmxErrChk(DAQmxCfgSampClkTiming(taskHandleDig, "/Dev2/PFI12", sampleRate2, DAQmx_Val_Rising, sampleMode, nSpCh));    
    unsigned bufferSize = nSpCh;  
    DAQmxErrChk(DAQmxSetBufInputBufSize(taskHandleAna, bufferSize));  
    DAQmxErrChk(DAQmxSetBufOutputBufSize(taskHandleDig, bufferSize));
    /*********************************************/  /*/ DAQmx Write Code  /*********************************************/  
    DAQmxErrChk(DAQmxWriteCtrTicksScalar(taskHandleDig, 0, timeout, hiTicks, lowTicks, NULL));
    /*********************************************/  /*/ DAQmx Start Code  /*********************************************/  
    DAQmxErrChk(DAQmxStartTask(taskHandleAna));  DAQmxErrChk(DAQmxStartTask(taskHandleDig));
    printf("Task started, waiting for trigger...\n");
    /*********************************************/  /*/ DAQmx Read Code  /*********************************************/  
    double* dataAna = new double[nSpCh];  
    int32 numReadAna = 0;  
    int errCode = DAQmxReadAnalogF64(taskHandleAna, -1, timeout, DAQmx_Val_GroupByChannel, dataAna, nSpCh, &numReadAna, NULL);  
    printf("Acquired %d analog samples\n",numReadAna);  
    if (numReadAna) {   
        unsigned nPts = (numReadAna < hiTicks)? numReadAna : hiTicks;  
        for (unsigned n = 0; n < nPts; ++n) {    
             printf("%6.3f ", dataAna[n]);   
        printf("\n");  
    delete [] dataAna;
    DAQmxErrChk(errCode);
    Error:  
    if( DAQmxFailed(error) )   DAQmxGetExtendedErrorInfo(errBuff,2048);  
    if( taskHandleDig!=0 && taskHandleAna!=0 ) {   
    /*********************************************/   /*/ DAQmx Stop Code   /*********************************************/   
        DAQmxStopTask(taskHandleDig);   
        DAQmxClearTask(taskHandleDig);   
        DAQmxStopTask(taskHandleAna);   
        DAQmxClearTask(taskHandleAna);  
    if( DAQmxFailed(error) )   printf("DAQmx Error: %s\n",errBuff);  
    printf("End of program, press Enter key to quit\n");  
    getchar();  
    return 0;
    Attachments:
    Correlated DIO AI_Sample_Clock Dig Start.c ‏6 KB

Maybe you are looking for