Measurement Computing   Easy to Use | Easy to Integrate | Easy to Support catalog banner

Read USB-1616HS Analog, Digital & Counter channels simultaneously...

Expand / Collapse
 

Read USB-1616HS Analog, Digital & Counter channels simultaneously



The following example uses the DaqInScan function to simultaneous read the USB-1616 subsystems. It is configured to read two analog inputs, one digital port, and one encoder channel. It configures a buffer with a size of packet times channel count times multiplier. To make the buffer bigger/smaller change change the multiplier. The sample rate is 1000 samples per second. The loop is set so as to read when a new half buffer is available.  The print routine prints only the first 32 samples to prevent it from consuming available time  

To access the API, add a reference to the MccDaq object. Adding the reference is usually accomplished by right clicking the Project [under the Project Explorer and selecting Add Reference. The complete project is attached to the article and was created with Visual Studio 2008 using CSharp. Compiling and execution is quick as there is minimal Windows overhead and associated code. 

To make the code more readable a few convenience functions were added such as IsError, GetBoardNum, and WaitForKey. The IsError function checks the error number in the ErrorInfo object and if not zero displays the error message.  The GetBoardNum function begins reading the Device strings from each number location and as soon as it finds one that contains the identifying string it exits. The WaitForKey does just that - waits for someone to press a key. To view the complete program project download the attachment below.

Disclaimer:
The attached Code or Example is provided As Is.  It has not been tested or validated as a product, for use in a deployed application or system, or for use in hazardous environments.  You assume all risks for use of the Code or Example.


using System;
using MccDaq; // also, add reference to MccDaq to the project

//This program uses the DaqInScan function to read 2x AI, 1x DigIn, 1x Encoder simultaneously. It configures a 
//buffer with a size of packet times channel count time multiplers. To make the buffer bigger/smaller change
//change the multipler. The sample rate is 1000 samples per second. The program retrieves one half of the 
//buffer when it available. The print routine prints only the first 32 samples to prevent it from consuming 
//available time

namespace CSharp_USB_1616HS_DaqInScan
{
    static class Constants
    {
        public const int ChanCount = 5; //number of channels (2x AI, 1x DigIn, 1x Encoder)
        public const int PACKET = 100;
        public const int BUFFMULTIPLER = 10;
        public const int BUFFSIZE = PACKET * ChanCount * BUFFMULTIPLER;
        public static int bufferSize = BUFFSIZE;
        public static int halfbuf = bufferSize / 2;
        public const int COUNTER = 0;  //first encoder channel
        public static int rows = halfbuf / ChanCount;
        public static MccBoard daq;
        public static int rate = 1000;
        public static int preTrigCount = 0;

    }
    class Program
    {

        static void Main(string[] args)
        {
            int BoardNum = 0;
            int Count = 0;
            int Index = 0;
            short daqStatus = 0;

            short[] ChanArray = new short[Constants.ChanCount];         // array to hold channel queue information
            ChannelType[] ChanTypeArray = new ChannelType[Constants.ChanCount];   // array to hold channel type information
            Range[] GainArray = new Range[Constants.ChanCount];         // array to hold gain queue information

            Console.WriteLine("Locating Device...Please wait\n");

            BoardNum = GetBoardNum("1616");

            if (BoardNum == -1)
            {
                Console.WriteLine("Device not detected!");
                WaitForKey();
                return;
            }
            else
            {
                Constants.daq = new MccDaq.MccBoard(BoardNum);

                Constants.daq.AInputMode(AInputMode.SingleEnded);

                CounterMode CMODE = CounterMode.Encoder | CounterMode.EncoderModeX1;

                IsError(Constants.daq.CConfigScan(Constants.COUNTER,
                                                    CMODE,
                                                    CounterDebounceTime.DebounceNone,
                                                    CounterDebounceMode.TriggerAfterStable,
                                                    CounterEdgeDetection.RisingEdge,
                                                    CounterTickSize.Tick208pt3ns,
                                                    0));

                //Channel configuration array definitions
                int i = 0;
                ChanArray[i] = 0;
                ChanTypeArray[i] = ChannelType.Analog;
                GainArray[i] = Range.Bip10Volts;
                i++;

                ChanArray[i] = 1;
                ChanTypeArray[i] = ChannelType.Analog;
                GainArray[i] = Range.Bip10Volts;
                i++;

                ChanArray[i] = (int)DigitalPortType.FirstPortA;
                ChanTypeArray[i] = ChannelType.Digital8;
                GainArray[i] = Range.NotUsed;
                i++;

                ChanArray[i] = Constants.COUNTER; 
                ChanTypeArray[i] = ChannelType.Ctr32Low;
                GainArray[i] = Range.NotUsed;
                i++;

                ChanArray[i] = Constants.COUNTER; 
                ChanTypeArray[i] = ChannelType.Ctr32High;
                GainArray[i] = Range.NotUsed;
                i++;

                ScanOptions Options = ScanOptions.Default
                                        | ScanOptions.Continuous
                                        | ScanOptions.Background;

                //allocate buffer
                int bufferSize = Constants.bufferSize;

                IntPtr buffer = MccService.WinBufAllocEx(Constants.bufferSize);

  

                IsError(Constants.daq.DaqInScan(ChanArray,
                                                ChanTypeArray,
                                                GainArray,
                                                Constants.ChanCount,
                                                ref Constants.rate,
                                                ref Constants.preTrigCount,
                                                ref Constants.bufferSize,
                                                buffer,
                                                Options));

                System.ConsoleKeyInfo cki = new System.ConsoleKeyInfo();
                Console.WriteLine("Retrieving Data\n");

                //first verify it started
                do
                {
                    IsError(Constants.daq.GetStatus(out daqStatus, out Count, out Index, FunctionType.DaqiFunction));

                } while (Count < Constants.halfbuf);

                // Read Loop
                do
                {
                    IsError(Constants.daq.GetStatus(out daqStatus, out Count, out Index, FunctionType.DaqiFunction));
                    GetData(Count, buffer);
                    System.Threading.Thread.Sleep(10);

                } while (!Console.KeyAvailable);
                cki = Console.ReadKey();

                //stop background operation
                IsError(Constants.daq.StopBackground(FunctionType.DaqiFunction));

                //free up memory
                IsError(MccService.WinBufFreeEx(buffer));

                WaitForKey();
            }
            // end of program
        }

        /*////////////////////////////////////////////////////////////////////////////////////*/

        public static void GetData(int Count, IntPtr pUserData)
        {
            short[] UserBuffer = new short[Constants.halfbuf];

            //Calculate the index of the latest sample in the buffer. 
            int Index = ((int)Count) % Constants.bufferSize;

            if (Index >= Constants.halfbuf - 1) //check for 50% more data
            {
                //get lower half of buffer
                IsError(MccService.WinBufToArray(pUserData, UserBuffer, 0, Constants.halfbuf));

                DisplayData(UserBuffer, Constants.rows);
                Console.WriteLine("\nRead lower half of the buffer. Total sample count {0}", Count.ToString("000,000,000"));

            }
            else if (Index < Constants.halfbuf - 1)
            {

                //get the upper half
                IsError(MccService.WinBufToArray(pUserData, UserBuffer, Constants.halfbuf, Constants.halfbuf));

                DisplayData(UserBuffer, Constants.rows);
                Console.WriteLine("\nRead upper half of the buffer. Total sample count {0}", Count.ToString("000,000,000"));

            }

        }
        /*////////////////////////////////////////////////////////////////////////////////////*/

        public static int GetBoardNum(string dev)
        {

            MccDaq.DaqDeviceManager.IgnoreInstaCal();
            MccDaq.DaqDeviceDescriptor[] inventory = MccDaq.DaqDeviceManager.GetDaqDeviceInventory(MccDaq.DaqDeviceInterface.Any);
            int DevicesFound = inventory.Length;
            if (DevicesFound > 0)
            {
                for (int boardNum = 0; boardNum < DevicesFound; boardNum++)
                {

                    try
                    {

                        if (inventory[boardNum].ProductName.Contains(dev))
                        {
                            MccDaq.MccBoard daqBoard = MccDaq.DaqDeviceManager.CreateDaqDevice(boardNum, inventory[boardNum]);
                            Console.WriteLine("Product Name:    {0}", inventory[boardNum].ProductName);
                            Console.WriteLine("Device Type # :  {0}", inventory[boardNum].ProductID);
                            Console.WriteLine("Serial # :       {0}", inventory[boardNum].UniqueID);
                            return boardNum;
                        }
                    }
                    catch (ULException ule)
                    {
                        Console.WriteLine("Error occured: " + ule.Message);
                    }
                }
            }
            return -1;
        }
        /*////////////////////////////////////////////////////////////////////////////////////*/

        public static void WaitForKey()
        {
            Console.WriteLine("\nPress any key to continue...");
            do
            {   //idle loop
                System.Threading.Thread.Sleep(10);
            } while (!Console.KeyAvailable);
        }

        /*////////////////////////////////////////////////////////////////////////////////////*/

        public static int IsError(ErrorInfo e)
        {
            if (e.Value != 0)
            {
                Console.WriteLine(e.Message);
                WaitForKey();
                return 1;
            }
            return 0;
        }
        //**************************************************************
        public static void DisplayData(short[] datArray, int rows)
        {
            //Writes data to screen and to file
            int i = 0;
            float AI0 = 0;
            float AI1 = 0;
            short Dig = 0;
            int tmp = 0;
            short highVal = 0;
            short lowVal = 0;

            Console.Clear();

            if (rows > 32) rows = 32;
            for (int row = 0; row < rows; row++)
            {
                for (int c = 0; c < Constants.ChanCount; c++)
                {
                    if (c == 0)
                        IsError(Constants.daq.ToEngUnits(Range.Bip10Volts, datArray[i], out AI0));
                    else if (c == 1)
                        IsError(Constants.daq.ToEngUnits(Range.Bip10Volts, datArray[i], out AI1));
                    else if (c == 2)
                        Dig = datArray[i];
                    else if (c == 3)
                    {   //fourth and fifth channels make up the 32 bit encoder value
                        highVal = datArray[i + 1];
                        lowVal = datArray[i];
                        //create 32 bit number
                        tmp = (highVal * 65536) + lowVal;
                        Console.Write("{0}\t{1}\t{2}\t{3}\r\n", 
                            AI0.ToString("00.000"), 
                            AI1.ToString("00.000"), 
                            Dig.ToString("000"),
                            tmp.ToString("000000000"));
                    }
                    i++;
                }
            }
            Console.WriteLine("\nScans of data read {0}\n", Constants.rows);

        }
        /*////////////////////////////////////////////////////////////////////////////////////*/

    }
}






Rate this Article:

Attachments


CSharp_USB_1616HS_DaqInScan.zip CSharp_USB_1616HS_DaqInScan.zip (5.42 KB, 16 views)

Add Your Comments


For comments email TechSupport@mccdaq.com.

Details
Article ID: 50780

Last Modified:5/31/2019 2:45:46 PM

Article has been viewed 149 times.

Options