Powering an LED That Corresponds to an Encoder Measurement Using an NI DAQ Device

Updated Dec 7, 2023

Environment

Hardware

  • Encoder

Software

  • LabVIEW
  • LabWindows/CVI
  • Measurement Studio

Programming Language

  • C++
  • C
  • C# .NET
  • Visual Basic .NET

You depend on measurements to make key decisions and discoveries. NI offers a wide range of data acquisition products, including the low-cost DAQ family for basic applications such as simple data logging, portable measurements, and academic lab experiments. Choose the right high-quality hardware based on the requirements for your application and budget.

Take advantage of free NI resources to help you get to your measurement faster. In this tutorial, modify one of the hundreds of measurement-specific examples included with your device to learn how to build a basic application that acquires an encoder measurement and powers one of three LEDs that corresponds to the count. NI low-cost DAQ products feature a variety of devices ideal for this type of basic application. For this tutorial, we work with the NI USB-6002; however, you can apply this code to any NI DAQ device that has a basic counter and digital output capabilities.

These devices come with software support for ANSI C, Visual C++, C# .NET, Visual Basic .NET, NI LabVIEW, NI LabWindows™/CVI, and NI Measurement Studio as well as configuration software. We demonstrate the task using C# .NET, but you can complete this same task in other application development environments (ADEs) or programming languages. To see tutorials for other programming languages or ADEs such as C# .NET or LabVIEW, select from the tutorials linked at the bottom of the page.
 

What You Need

Hardware

  1. NI multifunction DAQ device (this tutorial uses a USB-6002)
  2. Encoder
  3. 3 LEDs
  4. Wires

Software

  1. C# .NET compiler (this tutorial uses Microsoft Visual Studio)
  2. NI-DAQmx driver version that supports your device (the USB-6002 requires NI-DAQmx 9.9 or later)

    Hardware Instructions

    Setting Up the Device

    First, make sure you have installed the supporting NI-DAQmx driver software version. If you are using a USB DAQ device, a green or blue LED light should turn on when the device is recognized by your host PC. Open NI Measurement & Automation Explorer and confirm that the device appears under Devices and Interfaces. Select the Self-Test button and confirm that the device passes.


     

    Connecting the Encoder

    In this tutorial, we use the encoder to count edges. Connect the signal wires according to the pinout of your encoder. A sample pinout is below:

    1. Connect the ground to ground.
    2. Connect Channel A to P2.0, which accesses the counter.
    3. Connect the 5 VDC to the 5 V power supply on the device.
    4. Do not connect the index or Channel B pins. These are used when detecting the position of the encoder, which is outside the functionality of the USB-6002 counter.

     

    Connecting the LEDs

    On a standard LED, there are two leads of different lengths. The longer lead is positive and the shorter is negative. We configure the digital output as an active drive digital output driving an LED. Connect signals according to the diagram below. We do not use a resistor in this tutorial; however, many LEDs could be damaged if a resistor is not used to limit the current to the LED. Use your LED specifications to calculate the value of the resistor.

    1. Connect the positive lead of each LED to DO0, DO1, and DO2.
    2. Connect the negative leads to GND. We use the NI USB-6000 Series Prototyping Accessory, which makes it easier to solder the negative leads of the LEDs to a common ground.  

     

    Software Instructions

    Map Your Program Flow and Start With an Example

    For our application, we want to power an LED depending on the number of edges counted. To do this, we want to set up a program that creates and configures a physical counter input and digital output channel, acquires the number of edges counted, and powers the LED that corresponds to the count range. After we have acquired all the readings we want, we can clear the tasks and release the resources.


     

    Instead of building this entire application, we’re going to use one of the example programs that is included with your DAQ device. You can find the location of these example programs for your specific OS by visiting ni.com/info and typing in daqmxexp. We’re working with a C# .NET example. Specifically, we are going to modify a voltage measurement example called Count Digital Events.
     

    Copying the Example Program Into Your Personal Folder

    Copy the example program from its original location to a personal folder so that modifications to your program do not overwrite the original example.


    Opening the Program

    The first thing you should notice in your program is the extensive comments in the code that provide instructions on how to run the program, how to connect your I/O, and where certain functions are executed in your code. The example counts digital events and displays this count in the user interface.
     

    Adding Digital Output to Your Code and Modifying Counter Task

    1. Declare a digital output task and rename your counter task.
      A task is a collection of virtual channels, timing and triggering information, and other properties regarding acquisition or generation. In NI-DAQmx, you must have a unique task dedicated to different functions such as analog input and digital output. In code, we want to declare these tasks with unique identifiers so we can reference them throughout the code. To rename your analog input task, you can use Find and Replace to find all references to your task and replace the reference with the unique identifier. Do this before adding a reference to your digital output task.
           private Task digitalTask;
           private CICountEdgesActiveEdge edgeType;
           private System.Windows.Forms.GroupBox edgeGroupBox;        
           private CICountEdgesCountDirection countDirection;
           private CounterReader myCounterReader;
           private DigitalSingleChannelWriter digitalWriter;
           private System.Windows.Forms.ComboBox counterComboBox;
           private uint reading;
           private bool[] lessThan300Data = {false, false, true};
           private bool[] between300And600Data = {false, true, false};
           private bool[] moreThan600Data = {true, false, false};
     
    1. Configure your counter input and digital output tasks.
    To interact with the device, you first have to create tasks and reserve the channels you want to measure data from or write data to. Leave the default values for the counter input task with the exception of the line myTask.CIChannels.All.CountEdgesTerminal = "/Dev2/PFI0";, which we are eliminating altogether. For the digital output task, add the following code to create the task and reference the physical device and channel that the task applies to:
    try
               {
                   counterTask = new Task();
                   digitalTask = new Task();
                   
                   switch (countDirectionComboBox.SelectedItem.ToString())
                   {
                       case "Count Up":
                           countDirection = CICountEdgesCountDirection.Up;
                           break;
                       case "Count Down":
                           countDirection = CICountEdgesCountDirection.Down;
                           break;
                       case "Externally Controlled":
                           countDirection = CICountEdgesCountDirection.ExternallyControlled;
                           break;
                   }   
    
                   counterTask.CIChannels.CreateCountEdgesChannel (counterComboBox.Text, "",
                       edgeType, Convert.ToInt64(initialCountTextBox.Text), countDirection);
    
                   string deviceName = counterComboBox.Text.Split('/')[0];
    
                   digitalTask.DOChannels.CreateChannel(deviceName + "/line0:2", "", ChannelLineGrouping.OneChannelForAllLines);
    
                   myCounterReader = new CounterReader(counterTask.Stream);
                   digitalWriter = new DigitalSingleChannelWriter(digitalTask.Stream);
                   
                   counterTask.Start();
                   digitalTask.Start();
                   loopTimer.Interval = 100;
                   loopTimer.Enabled = true;
               }
               catch(DaqException exception)
               {
                   loopTimer.Enabled = false;
                   MessageBox.Show(exception.Message);
                   counterTask.Dispose();
                   return;
               }
               startButton.Enabled=false;
               stopButton.Enabled=true;
    
           }
    
           private void stopButton_Click(object sender, System.EventArgs e)
           {
               loopTimer.Enabled = false;
               startButton.Enabled = true;
               stopButton.Enabled = false;
               counterTask.Stop();
               counterTask.Dispose();
               digitalTask.Stop();
               digitalTask.Dispose();
           }
    
     
    1. Configure a Case structure to read and check the number of edges counted with each read.
    For this section of code, we code the logic from scratch. In the following logic, we power a yellow LED when the reading exceeds 300 and a red LED when the reading exceeds 600. Otherwise, the green LED is powered.
    private void loopTimer_Tick(object sender, System.EventArgs e)
         {           
               try
               {
                   reading = myCounterReader.ReadSingleSampleUInt32();
             
                   if(reading < 300)
                   {
                       digitalWriter.WriteSingleSampleMultiLine(true, lessThan300Data);
                   }
                   else if (reading < 600)
                   {
                       digitalWriter.WriteSingleSampleMultiLine(true, between300And600Data);
                   }
                   else
                   {
                       digitalWriter.WriteSingleSampleMultiLine(true, moreThan600Data);
                   }
    
                   countTextBox.Text = Convert.ToString(reading);
               }
               catch (DaqException exception)
               {
                   MessageBox.Show(exception.Message);
                   counterTask.Dispose();
                   digitalTask.Dispose();
                   loopTimer.Enabled = false;
                   startButton.Enabled = true;
                   stopButton.Enabled = false;
                   return;
               }
           }
     

    Running Your Program

    In the video, we used Microsoft Visual Studio as the compiler. To run the program, select the green run arrow labeled Start. Configure the counter that you are using in the user interface and select Start. Notice that the green LED powers on when the program is started. Turn the knob of your encoder and monitor the count. Notice that when the count exceeds 300 the yellow LED powers on. When it exceeds 600 the red LED powers on. Because the 600x is only capable of counting edges, not performing an encoder measurement, the count increases whichever direction the knob is turned.

    The mark LabWindows is used under a license from Microsoft Corporation. Windows is a registered trademark of Microsoft Corporation in the United States and other countries.