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

C# USB-2416 thermocouple example

Expand / Collapse
 

C# USB-2416 thermocouple example


The following program continuously acquires data from the USB-2416.  Before the acquisition is starts it further check to make sure that InstaCal was used to configure the channels for temperature and voltage - see comment in code. Modifying the Device string to 2408 this program should work with the USB-2408 as it is of the same hardware design.

To access the MccDaq 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 recreate the project use Visual Studio's File->New Project, select Visual C# and select Console Application. Create the new project and add the reference to the MccDaq Dot Net component. The easiest way to do this is to right mouse click the project in the Project Explorer and choose Add Reference. Select MccDaq from the NET list. Of course this assumes that you have installed the InstaCal software.

Although not shown below, a few convenience functions were added such as IsError, GetBoardNum, DisplayData, CreateFileHeader and WaitForKey. To view all the functions download the complete Visual Studio 2008 project by extracting the zip file at the bottom. 

The IsError function checks the error number in the ErrorInfo object and if not zero displays the error message.  The GetBoardNum function searches for a device matching the identifying string.  The CreateFileHeader writes acquisition information to the beginning of the output file. The Display data writes the data to the file and console screen. And WaitForKey does just that - waits for someone to press the spacebar.

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 System.Runtime.InteropServices;
using MccDaq;//Project must have reference to MccDaq
using System.IO;

namespace TemperatureVoltageReadBackground
{
    class Program
    {
        public const int CHANCOUNT = 4;
        public const int FIRSTCHANNEL = 0;
        public const int LASTCHANNEL = 3;
        public const int SAMPLERATE = 1;
        public const int BUFFERSIZE = CHANCOUNT * 100;

        //this program works with both the USB-2408 & USB-2416. Uncomment the appropriate string
        public const string DEVICE = "USB-2416";
        //public const string DEVICE = "USB-2408";

  
        public static StreamWriter fStream;


        static void Main(string[] args)
        {
            //Project must have reference to MccDaq
            MccDaq.ErrorInfo RetVal;
            int BoardNum = 0;
            int Rate = SAMPLERATE;

            BoardNum = GetBoardNum(DEVICE);

            if (BoardNum == -1)
            {
                Console.WriteLine("No {0} detected!", DEVICE);
                WaitForKey();
                return;
            }

            MccBoard daq = new MccDaq.MccBoard(BoardNum);

            IntPtr buffer = MccService.ScaledWinBufAllocEx(BUFFERSIZE);

            if (buffer == IntPtr.Zero)
            {
                Console.WriteLine("Bad Memory Handle");
                WaitForKey();
                return;
            }

            daq.AInputMode(AInputMode.Differential);
            daq.BoardConfig.SetDetectOpenTc(1);
            daq.BoardConfig.SetTempScale(TempScale.Fahrenheit);
   
            //configure TC channels for type K
            for (int Channel = 0; Channel < CHANCOUNT; Channel++)
            {
                daq.BoardConfig.SetAIChanType(Channel, AIChanType.Thermocople);
                daq.BoardConfig.SetChanTcType(Channel, TcType.K);
                //set channel filter to 60Hz
                daq.BoardConfig.SetAdDataRate(Channel, 60);

            }
            
            //Range parameter ignored when using TC inputs
            RetVal = daq.AInScan(FIRSTCHANNEL,
                                    LASTCHANNEL,
                                    BUFFERSIZE,
                                    ref Rate,
                                    Range.Bip10Volts,
                                    buffer,
                                    ScanOptions.Background | ScanOptions.ScaleData | ScanOptions.Continuous
                                );

            IsError(RetVal);
            //creat data file
            fStream = new StreamWriter(@"C:\Users\Public\Documents\DataFile.asc");
            CreateFileHeaders(); //writes basic info to the beginning of the file

            int Count = 0;
            int Index = 0;
            short daqStatus;
            double[] temps = new double[BUFFERSIZE];
            int LastIndex = 0;
            System.ConsoleKeyInfo cki = new System.ConsoleKeyInfo();

            //Loop until key press
            do
            {
                RetVal = daq.GetStatus(out daqStatus, out Count, out Index, FunctionType.AiFunction);
                if (Index > LastIndex)
                {
                        RetVal = MccService.ScaledWinBufToArray(buffer, temps, Index, CHANCOUNT);

                        DisplayData(temps, 1);
                        LastIndex = Index;
                }
            } while (!Console.KeyAvailable);

            cki = Console.ReadKey();

            //flush any buffered data out to disk
            fStream.Close();

            //stop the  acquisition
            RetVal = daq.StopBackground(FunctionType.AiFunction);

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

            WaitForKey();


        }
        /************************************ Check Error *********************************************/
        public static int IsError(ErrorInfo e)
        {
            if (e.Value != 0)
            {
                if (e.Value == ErrorInfo.ErrorCode.BadRate)
                    Console.WriteLine("Bad Sample Rate! Run InstaCal and increase Data Rates or lower sample rate");
                else
                    Console.WriteLine(e.Message);
                WaitForKey();
                return 1;
            }
            return 0;
        }
        /************************************ Finds Device *******************************************/
        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;
        }
        /***************************** Waits for SpaceBar keypress **********************************/
        public static void WaitForKey()
        {
            Console.WriteLine("\nPress <SpaceBar> to continue...");

            System.ConsoleKeyInfo cki;
            do
            {
                cki = Console.ReadKey();
            } while (cki.Key != ConsoleKey.Spacebar);
        }
        /************************************ Displays Data *********************************************/
        public static void DisplayData(double[] datArray, int rows)
        {
            //Writes data to screen and to file
            int i = 0;

            for (int row = 0; row < rows; row++)
            {
                for (int c = 0; c < CHANCOUNT; c++)
                {
                    Console.Write("{0}\t", datArray[i].ToString("0.0000").PadLeft(10));
                    fStream.Write("{0}\t", datArray[i].ToString("0.0000"));
                    i++;
                }
                Console.Write("\r\n");
                fStream.Write("\r\n");
            }
            fStream.Flush();
        }
        /************************************ Create File Header *********************************************/

        public static void CreateFileHeaders()
        {
            Console.WriteLine("This program reads channels {0} through {1}\n", FIRSTCHANNEL, LASTCHANNEL);

            //''''''''''''''''''''' create text file header strings ''''''''''''''''
            string[] hdr = new string[5];
            hdr[0] = "Recording date     : {0}";
            hdr[1] = "Block length       : {0}";
            hdr[2] = "Delta              : {0} sec.";
            hdr[3] = "Number of channels : {0}";

            //''''''''''''''''''''''' build column headers string '''''''''''''''''''

            for (int j = 0; j < CHANCOUNT; j++)
            {
                hdr[4] = hdr[4] + String.Format("In{0} [deg]", j);
                hdr[4] = hdr[4] + "\t";

            }
            hdr[4].Trim('\t');

            //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            DateTime MyDate = DateTime.Now;

            fStream.WriteLine(hdr[0], MyDate);
            fStream.WriteLine(hdr[1], 1);
            fStream.WriteLine(hdr[2], (1 / SAMPLERATE));
            fStream.WriteLine(hdr[3], CHANCOUNT);
            fStream.WriteLine(hdr[4]);

            Console.WriteLine(hdr[0], MyDate);
            Console.WriteLine(hdr[1], 1);
            Console.WriteLine(hdr[2], (1 / SAMPLERATE));
            Console.WriteLine(hdr[3], CHANCOUNT);
            Console.WriteLine(hdr[4]);

        }

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

    }
}



Rate this Article:

Attachments


CSharp_USB_2416_TC_Inputs.zip CSharp_USB_2416_TC_Inputs.zip (9.42 KB, 50 views)

Add Your Comments


For comments email TechSupport@mccdaq.com.

Details
Article ID: 50846

Last Modified:8/20/2021 8:44:11 AM

Article has been viewed 330 times.

Options