Пример #1
0
        //Button to send OFF command to DAC
        private void BDACOFF_Click(object sender, RoutedEventArgs e)
        {
            int  size          = 2;                       //Size of transmit and receive
            int  DeviceNumber  = DacDevice.SelectedIndex; //Device chosen by user on GUI
            uint baudRate      = 1000000;                 //Baud rate of device
            uint idleCsVal     = 0x1ff;                   //Bit is 1 for clock idle low
            uint activeCsVal   = 0x1ef;                   //Bit is 0 for CS active low, GP4 set as active low CS
            uint csToDataDly   = 0;                       //Time delay from CS to data
            uint dataToDataDly = 0;                       //Time delay from data to data
            uint dataToCsDly   = 0;                       //Time delay from data to CS
            uint txferSize     = (uint)(size);            //tXfer size set to size bytes
            byte spiMd         = 0;                       //SPI mode from connected devices datasheet
            uint csmask        = 0x10;                    //1 represents CS, set GP4 as CS

            //Setup transfer and receive bytes
            byte[] txData1 = new byte[size], rxData1 = new byte[size];
            txData1[0] = 0x70;
            txData1[1] = 0x00;

            //Start communication with DAC
            error = MCP2210.M_Mcp2210_xferSpiDataEx(deviceHandle[DeviceNumber], txData1, rxData1, ref baudRate, ref txferSize, csmask, ref idleCsVal, ref activeCsVal,
                                                    ref csToDataDly, ref dataToCsDly, ref dataToDataDly, ref spiMd);
            //Check for error and update status if required
            if (error != MCP2210.M_E_SUCCESS)
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("Device Disconnected!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }
        }
Пример #2
0
        public static void GetGpioDir()         //Ch
        {
            int err;

            err = MCP2210.M_Mcp2210_GetGpioPinDir(d1.Handle, ref d1.uinGpioDir);
            Console.WriteLine("The Pin Directions are {0} \r\n", d1.uinGpioDir);
        }
Пример #3
0
        public static void GetGpioVal()         //Ah
        {
            int err;

            err = MCP2210.M_Mcp2210_GetGpioPinVal(d1.Handle, ref d1.pgpioPinVal);
            Console.WriteLine("The Pin Values are {0} \r\n", d1.pgpioPinVal);
        }
Пример #4
0
        public static async Task <int> IncrementOrDecrementStrain(SgAdjust sgAdjust)
        {
            if (_deviceCount == 0)
            {
                await Init();
            }


            // set the SPI xFer params for I/O expander
            uint baudRate2      = 250000; //1000000
            uint idleCsVal2     = 0x1ff;
            uint activeCsVal2   = 0x1fd;  //GP1 CS PIN, remaining pins are GP //0x1ee GP4 and GP0 set as active low CS
            uint csToDataDly2   = 0;
            uint dataToDataDly2 = 0;
            uint dataToCsDly2   = 0;
            uint txFerSize2     = 3;    // I/O expander xFer size set to 4
            byte spiMd2         = 0;
            uint csMask4        = 0x02; //GP1 as CS  // 0x10 set GP4 as CS

            byte[] txData = new byte[3], rxData = new byte[3];
            switch (sgAdjust)
            {
            // set the expander config params
            case SgAdjust.Increment:
                txData[0] = 0x60;
                break;

            case SgAdjust.Decrement:
                txData[0] = 0xE0;
                break;

            case SgAdjust.Save:
                txData[0] = 0x20;
                //SmartLog.WriteLine(
                //    $"txData:{txData.ToHex()}\nrxData:{rxData.ToHex()}\nbaudRate2:{baudRate2}\ntxFerSize2:{txFerSize2}\ncsMask4:{csMask4}\nidleCsVal2:{idleCsVal2}\nactiveCsVal2:{activeCsVal2}\ncsToDataDly2:{csToDataDly2}\ndataToCsDly2:{dataToCsDly2}\ndataToDataDly2:{dataToDataDly2}\nspiMd2:{spiMd2}");
                break;
            }

            txData[1] = 0x00;
            txData[2] = 0x00;
            // send the data
            // use the extended SPI xFer API first time in order to set all the parameters
            // the subsequent xFer with the same device may use the simple API in order to save CPU cycles
            _response = MCP2210.M_Mcp2210_xferSpiDataEx(_deviceHandle, txData, rxData, ref baudRate2, ref txFerSize2,
                                                        csMask4, ref idleCsVal2, ref activeCsVal2, ref csToDataDly2,
                                                        ref dataToCsDly2, ref dataToDataDly2, ref spiMd2);
            if (_response != MCP2210.M_E_SUCCESS)
            {
                MCP2210.M_Mcp2210_Close(_deviceHandle);
                SmartLog.WriteErrorLine($"Sg ({sgAdjust.ToString()}) transfer error: " + _response);
                _deviceCount = 0;
                return(_response);
            }

            SmartLog.WriteLine($"Sg ({sgAdjust.ToString()}) transfer response: " + _response);
            return(0);
        }
Пример #5
0
        public static void Mcp2210Password()    //Eh
        {
            int err;

            Console.WriteLine("Please input the Device Password, 8 Character Maximum \r\n");
            d1.sPassword = Console.ReadLine();
            err          = MCP2210.M_Mcp2210_EnterPassword(d1.Handle, d1.sPassword);
            Console.WriteLine("Error is {0}", err);
        }
Пример #6
0
        public static void SetPassword()        //Dh
        {
            int            err;
            ConsoleKeyInfo passwrdConfig;
            string         soldPassword;
            string         snewPassword;

            Console.WriteLine("What Type of Access Control Would You " +
                              "like to Set the Device to? \r\n0 : No Password \r\n" +
                              "1 : Enable the Password \r\n2 : Change the Password \r\n" +
                              "3: Permanent Lock");
            passwrdConfig = Console.ReadKey();
            if (passwrdConfig.Key == ConsoleKey.D0) // disable password
            {
                d1.AccessConfig = 0x00;
            }
            else if (passwrdConfig.Key == ConsoleKey.D1) // enable password
            {
                d1.AccessConfig = 0x40;
            }
            else if (passwrdConfig.Key == ConsoleKey.D2) // change password
            {
                d1.AccessConfig = 0xA5;
            }
            else if (passwrdConfig.Key == ConsoleKey.D2) // change password
            {
                Console.WriteLine("Are You Sure You Want to PERMANENTLY LOCK ALL SETTINGS on This Device");
                if (Console.ReadKey().Key == ConsoleKey.Y)
                {
                    d1.AccessConfig = 0xFF;
                    err             = MCP2210.M_Mcp2210_SetPermanentLock(d1.Handle);
                    return; // handle the error
                }
            }
            Console.WriteLine("Please Insert the Current Password. " +
                              "8 Characters Max \r\n" +
                              "Please input any 8 Character string if it currently does not have a password");
            soldPassword = Console.ReadLine();

            Console.WriteLine("Please Insert the New Password. 8 Characters Max");
            snewPassword = Console.ReadLine();

            err = MCP2210.M_Mcp2210_SetAccessControl(d1.Handle, d1.AccessConfig, soldPassword, snewPassword);
            if (0 == err)
            {
                d1.sPassword = snewPassword;
            }
            else
            {
                PullbackException oops = new PullbackException();
                oops.Mcp2210Error = err;
                throw oops;
            }
        }
Пример #7
0
        //Timer setup and communication for ADC
        private void dispatcherTimerADC_Tick(object sender, EventArgs e)
        {
            double Vref          = 5.00;              //Reference voltage provided to ADC from circuit
            int    size          = 2;                 //Size of txfers
            int    DeviceNumber  = ADC.SelectedIndex; //Device chosen by user on GUI
            uint   baudRate      = 1000000;           //Baud rate
            uint   idleCsVal     = 0x1ff;             //Bit is 1 for clock idle low
            uint   activeCsVal   = 0x1df;             //Bit is 0 for CS active low, GP5 set as active low CS
            uint   csToDataDly   = 0;                 //Time delay from CS to data
            uint   dataToDataDly = 0;                 //Time delay from data to data
            uint   dataToCsDly   = 0;                 //Time delay from data to CS
            uint   txferSize     = (uint)(size);      //Xfer size set to size bytes
            byte   spiMd         = 0;                 //SPI mode from connected devices datasheet
            uint   csmask        = 0x20;              //1 represents CS, set GP5 as CS

            //Setup transfer and receive bytes
            byte[] txData1 = new byte[size], rxData1 = new byte[size];
            //ADC does not take input, tx is don't care
            txData1[0] = 0x00;
            txData1[1] = 0x00;

            //Start communication with ADC
            error = MCP2210.M_Mcp2210_xferSpiDataEx(deviceHandle[DeviceNumber], txData1, rxData1, ref baudRate, ref txferSize, csmask, ref idleCsVal, ref activeCsVal,
                                                    ref csToDataDly, ref dataToCsDly, ref dataToDataDly, ref spiMd);

            //Convert 16 bit receive to 10 bit unsigned value
            byte[] tempADC = new byte[1];
            tempADC[0] = rxData1[1];
            rxData1[1] = rxData1[0];
            rxData1[0] = tempADC[0];
            UInt16 value = (UInt16)(BitConverter.ToInt16(rxData1, 0));

            value = (UInt16)((value & 0x1FF8) >> 3);
            //Convert 10 bit unsigned to 0-Vref double
            double Volt = value * Vref / 1023;

            //Check for error and update status
            if (error != MCP2210.M_E_SUCCESS)
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("Device Disconnected!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }
            else
            {
                ADCV.Text    = Volt.ToString("0.00");
                ADCBar.Value = Volt * 20;
            }

            //Forcing the CommandManager to raise the RequerySuggested event
            CommandManager.InvalidateRequerySuggested();
        }
Пример #8
0
        //Button to turn on 7seg
        private void SegStart_Click(object sender, RoutedEventArgs e)
        {
            //Checking whether timer is already on
            if (!timerSeg)
            {
                timerSeg = true;
            }
            //Get value entered by user on GUI
            Digit = SegNum.Text.ToCharArray();
            int DeviceNumber = SevenSeg.SelectedIndex;  //Device selected by user on GUI

            //Checking if values entered can be displayed
            if (Digit.Length > 1)
            {
                DigitOne = Digit[0];
                DigitTwo = Digit[1];
            }
            else if (Digit.Length > 0)
            {
                DigitOne = '0';
                DigitTwo = Digit[0];
            }
            else
            {
                DigitOne = '0';
                DigitTwo = '0';
            }

            //converting two digit chars to unsigned int
            digitOne = (uint)(0x100 | CharToSeg[DigitOne]);
            digitTwo = (uint)(0x080 | CharToSeg[DigitTwo]);
            //Declare new background thread
            BackgroundWorker bw = new BackgroundWorker();

            error = MCP2210.M_Mcp2210_SetGpioConfig(deviceHandle[DeviceNumber], 0, GpioPinDes, digitOne,
                                                    0x000, 0x1, 0x0, 0x1);
            //Background thread event specified
            bw.DoWork += new DoWorkEventHandler(
                delegate(object o, DoWorkEventArgs args)
            {
                BackgroundWorker b = o as BackgroundWorker;
                //Do some simple processing until timerSeg is set to false
                while (timerSeg)
                {
                    error = MCP2210.M_Mcp2210_SetGpioPinVal(deviceHandle[DeviceNumber], digitOne, ref check);
                    error = MCP2210.M_Mcp2210_SetGpioPinVal(deviceHandle[DeviceNumber], digitTwo, ref check);
                }
            });
            //Start asynchronous thread
            bw.RunWorkerAsync();
        }
Пример #9
0
        //Timer setup and communication for Motor control using ADC voltage
        private void dispatcherTimerMotor_Tick(object sender, EventArgs e)
        {
            int    DeviceNumber  = Motor.SelectedIndex; //Device chosen by user on GUI
            double Vref          = 5.00;                //Reference voltage provided to Motor DAC by circuit
            int    size          = 2;                   //Size of txfers
            uint   baudRate      = 1000000;             //Baud rate
            uint   idleCsVal     = 0x1ff;               //Bit is 1 for clock idle low
            uint   activeCsVal   = 0x1ef;               //Bit is 0 for CS active low, GP4 set as active low CS
            uint   csToDataDly   = 0;                   //Time delay from CS to data
            uint   dataToDataDly = 0;                   //Time delay from data to data
            uint   dataToCsDly   = 0;                   //Time delay from data to CS
            uint   txferSize     = (uint)(size);        //tXfer size set to size bytes
            byte   spiMd         = 0;                   //SPI mode from connected devices datasheet
            uint   csmask        = 0x10;                //1 represents CS, set GP4 as CS

            //Setup transfer and receive bytes
            byte[] txData1 = new byte[size], rxData1 = new byte[size];
            //Read value from ADC textbox and parse it
            double value = Double.Parse(ADCV.Text);

            //Set boundaries for DAC input
            if (value > Vref)
            {
                value = Vref;
            }
            else if (value < 0)
            {
                value = 0;
            }
            //Make 0-5V input into 10 bit transfer for DAC
            int DAC = (int)(value * 1023.0 / Vref);

            txData1[0] = (byte)((DAC & 0x03C0) >> 6);
            txData1[0] = (byte)(txData1[0] | 0x70);
            txData1[1] = (byte)((DAC & 0x3F) << 2);

            //Start communication with Motor
            error = MCP2210.M_Mcp2210_xferSpiDataEx(deviceHandle[DeviceNumber], txData1, rxData1, ref baudRate, ref txferSize, csmask, ref idleCsVal, ref activeCsVal,
                                                    ref csToDataDly, ref dataToCsDly, ref dataToDataDly, ref spiMd);
            //Check for error and update status if required
            if (error != MCP2210.M_E_SUCCESS)
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("Device Disconnected!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }

            //Forcing the CommandManager to raise the RequerySuggested event
            CommandManager.InvalidateRequerySuggested();
        }
Пример #10
0
        //Button sends command to DAC, representing 0-VREF voltage output
        private void BDACON_Click(object sender, RoutedEventArgs e)
        {
            double Vref          = 5.00;                    //Reference voltage provided to DAC from circuit
            int    DeviceNumber  = DacDevice.SelectedIndex; //Device chosen by user on GUI
            int    size          = 2;                       //Size of transmit and receive
            uint   baudRate      = 1000000;                 //Baud rate of device
            uint   idleCsVal     = 0x1ff;                   //Bit is 1 for clock idle low
            uint   activeCsVal   = 0x1ef;                   //Bit is 0 for CS active low, GP4 set as active low CS
            uint   csToDataDly   = 0;                       //Time delay from CS to data
            uint   dataToDataDly = 0;                       //Time delay from data to data
            uint   dataToCsDly   = 0;                       //Time delay from data to CS
            uint   txferSize     = (uint)(size);            //tXfer size set to size bytes
            byte   spiMd         = 0;                       //SPI mode from connected devices datasheet
            uint   csmask        = 0x10;                    //1 represents CS, set GP4 as CS

            //Setup transfer and receive bytes
            byte[] txData1 = new byte[size], rxData1 = new byte[size];
            //Read value from DAC textbox and parse it
            double value = Double.Parse(TextBoxDAC.Text);

            //Set boundaries for DAC input
            if (value > Vref)
            {
                value = Vref;
            }
            else if (value < 0)
            {
                value = 0;
            }
            //Make 0-5V input into 12 bit transfer for DAC
            int DAC = (int)(value * 4095.0 / Vref);

            txData1[0] = (byte)((DAC & 0x0F00) >> 8);
            txData1[0] = (byte)(txData1[0] | 0x70);
            txData1[1] = (byte)(DAC & 0xFF);

            //Start communication with DAC
            error = MCP2210.M_Mcp2210_xferSpiDataEx(deviceHandle[DeviceNumber], txData1, rxData1, ref baudRate, ref txferSize, csmask, ref idleCsVal, ref activeCsVal,
                                                    ref csToDataDly, ref dataToCsDly, ref dataToDataDly, ref spiMd);
            //Check for error and update status if required
            if (error != MCP2210.M_E_SUCCESS)
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("Device Disconnected!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }
        }
Пример #11
0
        //Disconnect function
        private void Disconnect(string Device)
        {
            int DeviceNumber; //Device number used to select which device will be disconnected

            //Use input string to select Device number
            if (Device == "SevenSeg")
            {
                DeviceNumber = SevenSeg.SelectedIndex;
            }
            else if (Device == "ADC")
            {
                DeviceNumber = ADC.SelectedIndex;
            }
            else if (Device == "Temp")
            {
                DeviceNumber = Temp.SelectedIndex;
            }
            else if (Device == "Motor")
            {
                DeviceNumber = Motor.SelectedIndex;
            }
            else
            {
                DeviceNumber = DacDevice.SelectedIndex;
            }

            //Disconnect command
            MCP2210.M_Mcp2210_Close(deviceHandle[DeviceNumber]);
            //Get error
            error = MCP2210.M_Mcp2210_GetLastError();
            //Update error and connection status
            if (error != MCP2210.M_E_SUCCESS)
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("Device Error!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }
            else
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("Device Disconnected!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }
        }
Пример #12
0
        public static void ReadEeprom()
        {
            string sEeprom;

            byte[] baAddress;
            byte   bContent = 0;
            int    err;

            Console.WriteLine("What Address would you like to read from? Writen in Hex");
            sEeprom   = Console.ReadLine();
            baAddress = Converter.ToByteArray(sEeprom);
            err       = MCP2210.M_Mcp2210_ReadEEProm(d1.Handle, baAddress[0], ref bContent);
            if (err != 0)
            {
                //Handle it
            }
            d1.eepromData[baAddress[0]] = bContent;
            Console.WriteLine(" your Error response is {0} \r\n Your content is {1] for address {2}", err, baAddress[0], bContent);
        }
Пример #13
0
        public static void GetSpiConfig()       //6h
        {
            ConsoleKeyInfo memType;
            int            err;

            Console.WriteLine("Would you like to see SPI settings for [1] NVRAM or [2] Volitile Memory \r\n");
            memType = Console.ReadKey();
            if (memType.Key == ConsoleKey.D1)
            {
                d1.bFgSelector = (byte)MCP2210.M_MCP2210_NVRAM_CONFIG;
            }
            else if (memType.Key == ConsoleKey.D2)
            {
                d1.bFgSelector = (byte)MCP2210.M_MCP2210_VM_CONFIG;
            }
            err = MCP2210.M_Mcp2210_GetSpiConfig(d1.Handle, d1.bFgSelector, ref d1.uinBaudRate, ref d1.uinIdleCsVal, ref d1.uinActiveCsVal, ref d1.uinCsToDataDly, ref d1.uinDataToCsDly, ref d1.uinDataToDataDly, ref d1.uinTxferSize, ref d1.bSpiMd);
            Console.WriteLine("The baud rate is {0}.\r\n The Idle CS Values are {1}.\r\n The Active CS Values are {2}.\r\n The CS to First Data Byte Delay is {3} * 100 uS.\r\n The Last Data Byte to CS Delay is {4} * 100 uS.\r\n The Data to Data Byte Delay is {5} * 100uS.\r\n The Transfer Size is {6}. SPI Mode{7}\r\n ", d1.uinBaudRate, d1.uinIdleCsVal, d1.uinActiveCsVal, d1.uinCsToDataDly, d1.uinDataToCsDly, d1.uinDataToDataDly, d1.uinTxferSize, d1.bSpiMd);
            Console.WriteLine(" \r\n Error is {0}", err);
            //handle error
        }
Пример #14
0
        public static async Task <int> Init()
        {
            _deviceCount = MCP2210.M_Mcp2210_GetConnectedDevCount(DefaultVid, DefaultPid);
            SmartLog.WriteLine(_deviceCount + " SPI Module Device(s) found");
            if (_deviceCount <= 0)
            {
                return(_response);
            }
            StringBuilder path = new StringBuilder();

            _deviceHandle = MCP2210.M_Mcp2210_OpenByIndex(DefaultVid, DefaultPid, 0, path);
            _response     = MCP2210.M_Mcp2210_GetLastError();
            if (_response != MCP2210.M_E_SUCCESS)
            {
                SmartLog.WriteErrorLine("Failed to open connection");
                return(await Task.FromResult(-1));
            }

            return(_response);
        }
Пример #15
0
        public static bool ConnectUSB() // 0h and 1h

        {
            bool confirmation = false;


            uint i = (uint)MCP2210.M_Mcp2210_GetConnectedDevCount(Mcp2210Device.VID, Mcp2210Device.PID);

            if (i == 1)
            {
                Console.WriteLine("yeah Baby, Press any Button to Connect to Single Devices in your Area");  //assuming that the index for 1 device is always 0
                // Console.Read();
                d1.Handle = MCP2210.M_Mcp2210_OpenByIndex(Mcp2210Device.VID, Mcp2210Device.PID, i - 1, null);
                Console.WriteLine("Handle is {0}", d1.Handle);
                int Error = MCP2210.M_Mcp2210_GetLastError();
                Console.WriteLine("Response is {0} \r\n", Error);
            }



            return(confirmation);
        }
Пример #16
0
        public static void SetGpioDir()         //Bh
        {
            ConsoleKeyInfo gpioTemp;
            int            err;

            for (int i = 0; i < 9; i++)
            {
                Console.WriteLine("Please Indicate the Direction of Pin GPIO{0}\r\n 1 is In, 0 is Out \r\n", i);
                gpioTemp = Console.ReadKey();
                if (gpioTemp.Key == ConsoleKey.D1)
                {
                    d1.uinGpioDir += (uint)1 << i;
                }
                Console.WriteLine("\r\n");
            }
            Console.WriteLine("The chosen direction is {0}", d1.uinGpioDir);
            err = MCP2210.M_Mcp2210_SetGpioPinDir(d1.Handle, d1.uinGpioDir);
            if (err != 0)
            {
                //Handle it
            }
        }
Пример #17
0
        //Modify function
        private void Modify(string Device)
        {
            //Check if any devices are connected
            int count = MCP2210.M_Mcp2210_GetConnectedDevCount(DEFAULT_VID, DEFAULT_PID);

            //If any devices are connected open the modify window
            if (count > 0)
            {
                string DeviceString;
                string SN;
                if (Device == "SevenSeg")
                {
                    DeviceString = SevenSeg.SelectedItem.ToString();
                    SN           = SegSN.Text;
                }
                else if (Device == "ADC")
                {
                    DeviceString = ADC.SelectedItem.ToString();
                    SN           = ADCSN.Text;
                }
                else if (Device == "Temp")
                {
                    DeviceString = Temp.SelectedItem.ToString();
                    SN           = TempSN.Text;
                }
                else if (Device == "Motor")
                {
                    DeviceString = Motor.SelectedItem.ToString();
                    SN           = MotorSN.Text;
                }
                else
                {
                    DeviceString = DacDevice.SelectedItem.ToString();
                    SN           = ADCSN.Text;
                }
                Window1 subWindow = new Window1(SN, DeviceString);
                subWindow.Show();
            }
        }
Пример #18
0
        public static void WriteEeprom()
        {
            byte[] baContentTemp;
            string sEeprom;

            byte[] baAddress;
            byte   bContent;
            int    err;

            Console.WriteLine("What Adrress would you like to write to? Writen in Hex");
            sEeprom   = Console.ReadLine();
            baAddress = Converter.ToByteArray(sEeprom);
            Console.WriteLine("What would you like to write? Writen in Hex");
            sEeprom       = Console.ReadLine();
            baContentTemp = Converter.ToByteArray(sEeprom);
            bContent      = baContentTemp[0];
            d1.eepromData[baAddress[0]] = baContentTemp[0]; // fills in a byte array that correlates to the memory of the EEPROM. Utility for large reads
            err = MCP2210.M_Mcp2210_WriteEEProm(d1.Handle, baAddress[0], bContent);
            if (err != 0)
            {
                //Handle it
            }
            Console.WriteLine(" your Error response is {0} \r\n Your content is {1] for address {2}", err, baAddress[0], bContent);
        }
Пример #19
0
        public static void SetGpioVal()         //9h
        {
            int            err;
            ConsoleKeyInfo gpioTemp;

            for (int i = 0; i < 9; i++)
            {
                Console.WriteLine("Please Indicate the Output Value of Pin GPIO{0} \r\n", i);
                gpioTemp = Console.ReadKey();
                if (gpioTemp.Key == ConsoleKey.D1)
                {
                    d1.uinGpioVal += (uint)1 << i;
                }
                Console.WriteLine("\r\n");
            }
            Console.WriteLine("The chosen indication is {0} \r\n", d1.uinGpioVal);
            uint pgpioPinVal = d1.uinGpioVal;

            err = MCP2210.M_Mcp2210_SetGpioPinVal(d1.Handle, d1.uinGpioVal, ref d1.pgpioPinVal);
            if (err != 0)
            {
                //handle
            }
        }
Пример #20
0
        public static void SetSpiConfig()       //5h
        {
            ConsoleKeyInfo memType;
            ConsoleKeyInfo spiTemp;
            string         sSpi;
            int            err;

            Console.WriteLine("Would you like to edit [1] NVRAM or [2] Volitile Memory \r\n");
            memType = Console.ReadKey();
            if (memType.Key == ConsoleKey.D1)
            {
                d1.bFgSelector = (byte)MCP2210.M_MCP2210_NVRAM_CONFIG;
            }
            else if (memType.Key == ConsoleKey.D2)
            {
                d1.bFgSelector = (byte)MCP2210.M_MCP2210_VM_CONFIG;
            }
            Console.WriteLine(" What is your requested baud rate \r\n 12 Mb is Maximum");
            sSpi = Console.ReadLine();
            if (Int32.TryParse(sSpi, out int baud))
            {
                d1.uinBaudRate = (uint)baud;
            }
            else
            {
                //Do something
            }
            for (int i = 0; i < 9; i++)
            {
                Console.WriteLine("Please Indicate the Idle Chip Select Values of CS{0}\r\n 1 or 0 \r\n", i);
                spiTemp = Console.ReadKey();
                if (spiTemp.Key == ConsoleKey.D1)
                {
                    d1.uinIdleCsVal += (uint)1 << i;
                }
                Console.WriteLine("\r\n");
            }
            for (int i = 0; i < 9; i++)
            {
                Console.WriteLine("Please Indicate the Active Chip Select Values of CS{0}\r\n 1 or 0 \r\n", i);
                spiTemp = Console.ReadKey();
                if (spiTemp.Key == ConsoleKey.D1)
                {
                    d1.uinActiveCsVal += (uint)1 << i;
                }
                Console.WriteLine("\r\n");
            }
            Console.WriteLine("Select the Delay between Chip Select and Data in Decimal Value , quanta of 100 uS \r\n");
            sSpi = Console.ReadLine();
            if (Int32.TryParse(sSpi, out int cs_data_delay))
            {
                d1.uinCsToDataDly = (uint)cs_data_delay;
            }
            else
            {
                //Do something
            }
            Console.WriteLine("Select the Delay between Last Data Byte and Chip Select in Decimal Value , quanta of 100 uS \r\n");
            sSpi = Console.ReadLine();
            if (Int32.TryParse(sSpi, out int data_cs_delay))
            {
                d1.uinDataToCsDly = (uint)data_cs_delay;
            }
            else
            {
                //Do something
            }
            Console.WriteLine("Select the Delay between Subsequent Data Bytes in Decimal Value , quanta of 100 uS \r\n");
            sSpi = Console.ReadLine();
            if (Int32.TryParse(sSpi, out int data_data_delay))
            {
                d1.uinDataToDataDly = (uint)data_data_delay;
            }
            else
            {
                //Do something
            }
            Console.WriteLine("Select the Total Number of Bytes to Transfer in Decimal Value \r\n");
            sSpi = Console.ReadLine();
            if (Int32.TryParse(sSpi, out int bytes_to_tx))
            {
                d1.uinTxferSize = (uint)bytes_to_tx;
            }
            else
            {
                //Do something
            }
            Console.WriteLine("Please Select the Desired Spi Mode [0] [1] [2] [3] \r\n");
            spiTemp = Console.ReadKey();
            if (spiTemp.Key == ConsoleKey.D0)
            {
                d1.bSpiMd = (byte)MCP2210.M_MCP2210_SPI_MODE0;
            }
            else if (spiTemp.Key == ConsoleKey.D1)
            {
                d1.bSpiMd = (byte)MCP2210.M_MCP2210_SPI_MODE1;
            }
            else if (spiTemp.Key == ConsoleKey.D2)
            {
                d1.bSpiMd = (byte)MCP2210.M_MCP2210_SPI_MODE2;
            }
            else if (spiTemp.Key == ConsoleKey.D3)
            {
                d1.bSpiMd = (byte)MCP2210.M_MCP2210_SPI_MODE3;
            }
            err = MCP2210.M_Mcp2210_SetSpiConfig(d1.Handle, d1.bFgSelector, ref d1.uinBaudRate, ref d1.uinIdleCsVal, ref d1.uinActiveCsVal, ref d1.uinCsToDataDly, ref d1.uinDataToCsDly, ref d1.uinDataToDataDly, ref d1.uinTxferSize, ref d1.bSpiMd);
            Console.WriteLine(" \r\n Error is {0}", err);
            //Handle Error
        }
Пример #21
0
        public static int SetUpDeviceSettings( ) //2h
        {
            int temp = MCP2210.M_Mcp2210_SetUsbKeyParams(d1.Handle, Mcp2210Device.VID, Mcp2210Device.PID, d1.pwr, d1.wake, d1.current);

            return(temp);
        }
Пример #22
0
 public static void Close()
 {
     MCP2210.M_Mcp2210_Close(_deviceHandle);
     _deviceCount = 0;
 }
Пример #23
0
        //Timer setup and communication for Temperature sensor
        private void dispatcherTimerTemp_Tick(object sender, EventArgs e)
        {
            int  DeviceNumber     = Temp.SelectedIndex; //Device chosen by user on GUI
            uint pbaudRate77      = 1000000;            //baud rate
            uint pidleCsVal77     = 0x1ff;              //Bit is 1 for clock idle low
            uint pactiveCsVal77   = 0x1ef;              //GP4 set as active low CS
            uint pcsToDataDly77   = 0;                  //time delay from CS to data, quanta of 100us
            uint pdataToDataDly77 = 0;                  //time delay from data to data, quanta of 100us
            uint pdataToCsDly77   = 0;                  //time delay from data to CS, quanta of 100us
            uint ptxferSize77     = 2;                  //TC77 txfer size set to 2 bytes
            byte pspiMd77         = 0;                  //SPI mode from connected devices datasheet
            uint csmask77         = 0x10;               //1 represents CS, set GP4 as CS

            //Setup transfer and receive bytes
            byte[] txData77 = new byte[2], rxData77 = new byte[2];
            txData77[0] = 0x00;
            txData77[1] = 0x00;
            rxData77[0] = 0x00;
            rxData77[1] = 0x00;

            //Tx and Rx data from TC77
            error = MCP2210.M_Mcp2210_xferSpiDataEx(deviceHandle[DeviceNumber], txData77, rxData77, ref pbaudRate77, ref ptxferSize77, csmask77, ref pidleCsVal77, ref pactiveCsVal77,
                                                    ref pcsToDataDly77, ref pdataToCsDly77, ref pdataToDataDly77, ref pspiMd77);
            if (error != MCP2210.M_E_SUCCESS)
            {
                MCP2210.M_Mcp2210_Close(deviceHandle[DeviceNumber]);
                LastError.Items.Add(" Transfer error: " + error);
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }

            //Setting last three bits to zero as they are don't cares from datasheet
            rxData77[1] = (byte)(rxData77[1] & 0xF8);

            byte[] temper = new byte[1];
            temper[0]   = rxData77[1];
            rxData77[1] = rxData77[0];
            rxData77[0] = temper[0];

            //Calculations and display
            temp  = BitConverter.ToInt16(rxData77, 0);
            temp /= 128;
            //GUI string display
            Temperature.Text = temp.ToString("0.00");
            //7-Seg display setup
            temp1     = (int)temp;
            DigitTemp = temp1.ToString().ToCharArray();
            if (DigitTemp.Length > 1)
            {
                DigitOneTemp = DigitTemp[0];
                DigitTwoTemp = DigitTemp[1];
            }
            else if (DigitTemp.Length > 0)
            {
                DigitOneTemp = '0';
                DigitTwoTemp = Digit[0];
            }

            if (CharToSeg.ContainsKey(DigitOneTemp) && CharToSeg.ContainsKey(DigitTwoTemp))
            {
                digitOneTemp = (uint)(0x100 | CharToSeg[DigitOneTemp]);
                digitTwoTemp = (uint)(0x080 | CharToSeg[DigitTwoTemp]);
            }
            else
            {
                digitOneTemp = (uint)(0x100 | CharToSeg['0']);
                digitTwoTemp = (uint)(0x080 | CharToSeg['0']);
            }

            //GUI bar display
            if (temp < 15)
            {
                temp = 15;
            }
            else if (temp > 40)
            {
                temp = 40;
            }
            temp          = (temp - 15) * 100 / 25;
            TempBar.Value = temp;

            //Forcing the CommandManager to raise the RequerySuggested event
            CommandManager.InvalidateRequerySuggested();
        }
Пример #24
0
        public static void SetGpioConfig()      //7h
        {
            ConsoleKeyInfo memType;
            ConsoleKeyInfo gpioTemp;
            string         temp_gp;
            int            err;

            Console.WriteLine("Would you like to set the GPIO settings for [1] NVRAM or [2] Volitile Memory \r\n");
            memType = Console.ReadKey();
            if (memType.Key == ConsoleKey.D1)
            {
                d1.bFgSelector = (byte)MCP2210.M_MCP2210_NVRAM_CONFIG;
            }
            else if (memType.Key == ConsoleKey.D2)
            {
                d1.bFgSelector = (byte)MCP2210.M_MCP2210_VM_CONFIG;
            }
            Console.WriteLine("Please Indicate the GP Pin Designation in Hex Format, GP0 is First & GP8 is Last \r\n 00 : GPIO \r\n 01 : Chip Select \r\n 02 : Dedicated Pin Function \r\n ");
            temp_gp        = Console.ReadLine();
            d1.baGpSetting = Converter.ToByteArray(temp_gp);
            for (int i = 0; i < 9; i++)
            {
                Console.WriteLine("Please Indicate the Output Value of Pin GPIO{0} \r\n", i);
                gpioTemp = Console.ReadKey();
                if (gpioTemp.Key == ConsoleKey.D1)
                {
                    d1.uinGpioVal += (uint)1 << i;
                }
                Console.WriteLine("\r\n");
            }
            Console.WriteLine("The chosen indication is {0} \r\n", d1.uinGpioVal);
            for (int i = 0; i < 9; i++)
            {
                Console.WriteLine("Please Indicate the Direction of Pin GPIO{0}\r\n 1 is In, 0 is Out \r\n", i);
                gpioTemp = Console.ReadKey();
                if (gpioTemp.Key == ConsoleKey.D1)
                {
                    d1.uinGpioDir += (uint)1 << i;
                }
                Console.WriteLine("\r\n");
            }
            Console.WriteLine("The chosen direction is {0}", d1.uinGpioDir);
            Console.WriteLine("\r\n Would You Like the Device to Be Remote Wake Enababled [Y] or [N] /r/n");
            gpioTemp = Console.ReadKey();
            if (gpioTemp.Key == ConsoleKey.Y)
            {
                d1.bRmtWkupEn = (byte)MCP2210.M_MCP2210_REMOTE_WAKEUP_ENABLED;
            }
            if (gpioTemp.Key == ConsoleKey.N)
            {
                d1.bRmtWkupEn = (byte)MCP2210.M_MCP2210_REMOTE_WAKEUP_DISABLED;
            }
            Console.WriteLine("\r\n How would you like the interupt pin to count interupts, GP6 \r\n 0 : NONE \r\n 1 : High Pulses \r\n 2 : Low Pulses \r\n 3 : Rising Edges \r\n 4 : Falling Edges \r\n");
            gpioTemp = Console.ReadKey();
            if (gpioTemp.Key == ConsoleKey.D0)
            {
                d1.bPinMode = (byte)MCP2210.M_MCP2210_INT_MD_CNT_NONE;
            }
            else if (gpioTemp.Key == ConsoleKey.D1)
            {
                d1.bPinMode = (byte)MCP2210.M_MCP2210_INT_MD_CNT_HIGH_PULSES;
            }
            else if (gpioTemp.Key == ConsoleKey.D2)
            {
                d1.bPinMode = (byte)MCP2210.M_MCP2210_INT_MD_CNT_LOW_PULSES;
            }
            else if (gpioTemp.Key == ConsoleKey.D3)
            {
                d1.bPinMode = (byte)MCP2210.M_MCP2210_INT_MD_CNT_RISING_EDGES;
            }
            else if (gpioTemp.Key == ConsoleKey.D4)
            {
                d1.bPinMode = (byte)MCP2210.M_MCP2210_INT_MD_CNT_FALLING_EDGES;
            }
            Console.WriteLine("\r\n Would you like your device to release the SPI Bus to another master when not broadcasting [Y] or [N] \r\n");
            gpioTemp = Console.ReadKey();
            if (gpioTemp.Key == ConsoleKey.Y)
            {
                d1.bSpiBusRelEn = (byte)MCP2210.M_MCP2210_SPI_BUS_RELEASE_ENABLED;
            }
            if (gpioTemp.Key == ConsoleKey.N)
            {
                d1.bSpiBusRelEn = (byte)MCP2210.M_MCP2210_SPI_BUS_RELEASE_DISABLED;
            }
            err = MCP2210.M_Mcp2210_SetGpioConfig(d1.Handle, d1.bFgSelector, d1.baGpSetting, d1.uinGpioVal, d1.uinGpioDir, d1.bRmtWkupEn, d1.bPinMode, d1.bSpiBusRelEn);
            if (err != 0)
            {
                PullbackException oops = new PullbackException();
                oops.Mcp2210Error = err;

                throw oops;
            }
            Console.WriteLine("\r\n Error is {0}", err);
        }
Пример #25
0
        public static void GetGpioConfig()      //8h
        {
            int  err;
            uint tempuinGpioVal   = 0;
            uint tempuinGpioDir   = 0;
            byte tempbRmtWkupEn   = 0;
            byte tempbPinMode     = 0;
            byte tempbSpiBusRelEn = 0;



            ConsoleKeyInfo memType;

            Console.WriteLine("Would you like to see GPIO settings for [1] NVRAM or [2] Volitile Memory \r\n");
            memType = Console.ReadKey();
            if (memType.Key == ConsoleKey.D1)
            {
                d1.bFgSelector = (byte)MCP2210.M_MCP2210_NVRAM_CONFIG;
            }
            else if (memType.Key == ConsoleKey.D2)
            {
                d1.bFgSelector = (byte)MCP2210.M_MCP2210_VM_CONFIG;
            }
            err = MCP2210.M_Mcp2210_GetGpioConfig(d1.Handle, d1.bFgSelector, d1.baGpSetting, ref tempuinGpioVal, ref tempuinGpioDir, ref tempbRmtWkupEn, ref tempbPinMode, ref tempbSpiBusRelEn);
            Converter.CheckByteArray(d1.baGpSetting);
            d1.uinGpioVal   = tempuinGpioVal;
            d1.uinGpioDir   = tempuinGpioDir;
            d1.bRmtWkupEn   = tempbRmtWkupEn;
            d1.bPinMode     = tempbPinMode;
            d1.bSpiBusRelEn = tempbSpiBusRelEn;

            Console.WriteLine("The chosen indication is {0} \r\n", d1.uinGpioVal);
            Console.WriteLine("The chosen direction is {0} \r\n", d1.uinGpioDir);
            if (d1.bRmtWkupEn == (byte)MCP2210.M_MCP2210_REMOTE_WAKEUP_ENABLED)
            {
                Console.WriteLine("Remote Wake Up is Enabled");
            }
            else if (d1.bRmtWkupEn == (byte)MCP2210.M_MCP2210_REMOTE_WAKEUP_DISABLED)
            {
                Console.WriteLine("Remote Wake Up is Disabled");
            }
            if (d1.bPinMode == (byte)MCP2210.M_MCP2210_INT_MD_CNT_NONE)
            {
                Console.WriteLine("Interupt pin is Disabled");
            }
            else if (d1.bPinMode == (byte)MCP2210.M_MCP2210_INT_MD_CNT_HIGH_PULSES)
            {
                Console.WriteLine("Interrupt is High Pulse Triggered");
            }
            else if (d1.bPinMode == (byte)MCP2210.M_MCP2210_INT_MD_CNT_LOW_PULSES)
            {
                Console.WriteLine("Interrupt is Low Pulse Triggered");
            }
            else if (d1.bPinMode == (byte)MCP2210.M_MCP2210_INT_MD_CNT_RISING_EDGES)
            {
                Console.WriteLine("Interrupt is Rising Edge Triggered");
            }
            else if (d1.bPinMode == (byte)MCP2210.M_MCP2210_INT_MD_CNT_FALLING_EDGES)
            {
                Console.WriteLine("Interrupt is Falling Edge Triggered");
            }
            if (d1.bSpiBusRelEn == (byte)MCP2210.M_MCP2210_SPI_BUS_RELEASE_ENABLED)
            {
                Console.WriteLine("SPI Bus Release is Enabled");
            }
            if (d1.bSpiBusRelEn == (byte)MCP2210.M_MCP2210_SPI_BUS_RELEASE_DISABLED)
            {
                Console.WriteLine("SPI Bus Release is Disabled");
            }
            if (err != 0)
            {
                PullbackException oops = new PullbackException();
                oops.Mcp2210Error = err;
                throw oops;
            }
            Console.WriteLine("Error is {0}", err);
        }
Пример #26
0
        public MainWindow()
        {
            InitializeComponent();

            //Setup dictionary of known devices
            var fs = File.Open("SerialNumber.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            var SR = new StreamReader(fs);

            using (SR)
            {
                string line;
                while ((line = SR.ReadLine()) != null)
                {
                    string[] parts = line.Split(',');
                    if (parts.Length > 1)
                    {
                        SerialtoName.Add(parts[0], parts[1]);
                        NametoSerial.Add(parts[1], parts[0]);
                    }
                }
            }
            SR.Close();

            //check for connected devices
            int count = MCP2210.M_Mcp2210_GetConnectedDevCount(DEFAULT_VID, DEFAULT_PID);

            if (count > 0)
            {
                deviceHandle = new IntPtr[count];
            }
            //Display devices available
            DeviceCount.Text = count.ToString();
            //Check that atleast one device is avalaible, then check if they are stored in memory with a given name
            //If they are not stored, label them with SPI#
            //Connect to all available devices
            if (count > 0)
            {
                for (uint i = 0; i < count; i++)
                {
                    deviceHandle[i] = MCP2210.M_Mcp2210_OpenByIndex(DEFAULT_VID, DEFAULT_PID, i, path);
                    MCP2210.M_Mcp2210_GetSerialNumber(deviceHandle[i], SN);
                    //Check for any errors
                    error = MCP2210.M_Mcp2210_GetLastError();
                    //Display any error and connection status
                    if (error != MCP2210.M_E_SUCCESS)
                    {
                        LastError.Items.Add(error.ToString());
                        LastError.Items.Add("Device cannot be opened!");
                        LastError.SelectedIndex = LastError.Items.Count - 1;
                        LastError.ScrollIntoView(LastError.SelectedItem);
                    }
                    else
                    {
                        LastError.Items.Add(error.ToString());
                        LastError.Items.Add("Device(s) Found!");
                        LastError.SelectedIndex = LastError.Items.Count - 1;
                        LastError.ScrollIntoView(LastError.SelectedItem);
                    }
                    //Check for stored device name
                    if (SerialtoName.ContainsKey(SN.ToString()))
                    {
                        Temp.Items.Add(SerialtoName[SN.ToString()]);
                        SevenSeg.Items.Add(SerialtoName[SN.ToString()]);
                        ADC.Items.Add(SerialtoName[SN.ToString()]);
                        DacDevice.Items.Add(SerialtoName[SN.ToString()]);
                        Motor.Items.Add(SerialtoName[SN.ToString()]);
                    }
                    //assign temperary device name
                    else
                    {
                        bool check = true;
                        int  spi   = 0;
                        while (check)
                        {
                            spi++;
                            if (!NametoSerial.ContainsKey("SPI" + spi.ToString()))
                            {
                                check = false;
                                SerialtoName.Add(SN.ToString(), ("SPI" + spi.ToString()));
                                NametoSerial.Add(("SPI" + spi.ToString()), SN.ToString());
                            }
                        }
                        Temp.Items.Add("SPI" + spi.ToString());
                        SevenSeg.Items.Add("SPI" + spi.ToString());
                        ADC.Items.Add("SPI" + spi.ToString());
                        DacDevice.Items.Add("SPI" + spi.ToString());
                        Motor.Items.Add("SPI" + spi.ToString());
                    }
                }
            }
            else
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("No Devices Found!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }

            //Setup GPIO array
            for (int i = 0; i < 9; i++)
            {
                GpioPinDes[i] = 0;
            }
        }
Пример #27
0
        //Connect function
        private void Connect(string Device)
        {
            int    DeviceNumber; //Device number used to select which device will be connected
            string Serial;       //Selected device Serial Number

            //Use input string to select Device number and selected device Serial Number
            if (Device == "SevenSeg")
            {
                DeviceNumber = SevenSeg.SelectedIndex;
                Serial       = SevenSeg.SelectedItem.ToString();
            }
            else if (Device == "ADC")
            {
                DeviceNumber = ADC.SelectedIndex;
                Serial       = ADC.SelectedItem.ToString();
            }
            else if (Device == "Temp")
            {
                DeviceNumber = Temp.SelectedIndex;
                Serial       = Temp.SelectedItem.ToString();
            }
            else if (Device == "Motor")
            {
                DeviceNumber = Motor.SelectedIndex;
                Serial       = Motor.SelectedItem.ToString();
            }
            else
            {
                DeviceNumber = DacDevice.SelectedIndex;
                Serial       = DacDevice.SelectedItem.ToString();
            }

            //Check if selected device serial number is in our stored list
            if (NametoSerial.ContainsKey(Serial))
            {
                //open device
                deviceHandle[DeviceNumber] = MCP2210.M_Mcp2210_OpenBySN(DEFAULT_VID, DEFAULT_PID, NametoSerial[Serial], path);
                //check for any errors
                error = MCP2210.M_Mcp2210_GetLastError();
            }
            //////////////////////////////
            else
            {
                //open device
                deviceHandle[DeviceNumber] = MCP2210.M_Mcp2210_OpenBySN(DEFAULT_VID, DEFAULT_PID, Serial, path);
                //check for any errors
                error = MCP2210.M_Mcp2210_GetLastError();
            }
            //Update error and connection status
            if (error != MCP2210.M_E_SUCCESS)
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("Device cannot be opened!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }
            else
            {
                LastError.Items.Add(error.ToString());
                LastError.Items.Add("Device Connected!");
                LastError.SelectedIndex = LastError.Items.Count - 1;
                LastError.ScrollIntoView(LastError.SelectedItem);
            }
        }
Пример #28
0
        static int Main(string[] args)
        {
            // Default SPI parameters
            bool   shouldShowHelp  = false;
            uint   deviceIndex     = 0;
            uint   pbaudRate2      = 1000000;
            uint   pidleCsVal2     = 0xfff; // Idle value for CS
            uint   pactiveCsVal2   = 0x000; // Active value for CS
            uint   pcsToDataDly2   = 0;     // CS to data delay
            uint   pdataToCsDly2   = 0;     // Last data byte to CS delay
            uint   pdataToDataDly2 = 0;     // Delay between bytes
            uint   ptxferSize2     = 4;     // Bytes to Transfer per SPI Transaction
            byte   pspiMd2         = 0;     // SPI Mode
            uint   csIndex         = 0;
            String gpio            = null;
            String data            = null;

            // Set the command line parser
            var options = new OptionSet {
                { "i|index=", $"index of the MCP2210 device (defaults to {deviceIndex})", (uint i) => deviceIndex = i },
                { "b|baud=", $"baud rate in MHz (defaults to {pbaudRate2})", (uint b) => pbaudRate2 = b },
                { "csToDataDly=", $"delay between CS assertion and data send in units of 100 us (defaults to {pcsToDataDly2})", (uint d) => pcsToDataDly2 = d },
                { "dataToCsDly=", $"delay between the last byte sent and CD deassert in units of 100 us (defaults to {pdataToCsDly2})", (uint d) => pdataToCsDly2 = d },
                { "dataToDataDly=", $"delay between bytes in units of 100 us (defaults to {pdataToDataDly2})", (uint d) => pdataToDataDly2 = d },
                { "m|mode=", $"SPI mode (defaults to {pspiMd2})", (byte m) => pspiMd2 = m },
                { "cs=", $"CS index (defaults to {csIndex})", (uint i) => csIndex = i },
                { "d|data=", "Array of bytes to send in hex format separated by commas", s => data = s },
                { "gpioW=[number][1|0]", "Write 1 or 0 to the specified GPIO (example: gpioW=21, write 1 to GPIO 2)", s => gpio = s },
                { "h|help", "show this message and exit", h => shouldShowHelp = h != null },
            };

            try
            {
                // Parse the command line
                options.Parse(args);

                // Show help menu
                if (shouldShowHelp)
                {
                    options.WriteOptionDescriptions(Console.Out);
                    return(0);
                }

                // We always need data
                if (data == null)
                {
                    return(0);
                }
            }
            catch (OptionException e)
            {
                // output some error message
                Console.Write("greet: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `greet --help' for more information.");
            }

            // Search connected MCP2210 devices
            int devCount = MCP2210.M_Mcp2210_GetConnectedDevCount(DEFAULT_VID, DEFAULT_PID);

            if (DEBUG)
            {
                Console.WriteLine(devCount + " devices found");
            }

            if (devCount > 0)
            {
                // Connect to the MCP2210
                StringBuilder path         = new StringBuilder();
                IntPtr        deviceHandle = new IntPtr();
                int           res;

                // Open the device first
                deviceHandle = MCP2210.M_Mcp2210_OpenByIndex(DEFAULT_VID, DEFAULT_PID, deviceIndex, path);
                res          = MCP2210.M_Mcp2210_GetLastError();
                if (res != MCP2210.M_E_SUCCESS)
                {
                    Console.WriteLine("Failed to open connection");
                    return(-1);
                }

                // Check if any GPIO must be written
                if (gpio != null && gpio.Length == 2)
                {
                    uint   gpioNumber = uint.Parse(gpio[0].ToString());
                    uint   value      = uint.Parse(gpio[1].ToString());
                    byte[] pins       = new byte[MCP2210.M_MCP2210_GPIO_NR];

                    uint gpioValue = (uint)(1 << (int)gpioNumber);

                    // Set everything as GPIO
                    for (int n = 0; n < pins.Length; ++n)
                    {
                        pins[n] = (byte)MCP2210.M_MCP2210_PIN_DES_GPIO;
                    }

                    // Set GPIO
                    MCP2210.M_Mcp2210_SetGpioConfig(deviceHandle, (byte)MCP2210.M_MCP2210_VM_CONFIG, pins, gpioValue, 0, (byte)MCP2210.M_MCP2210_REMOTE_WAKEUP_DISABLED,
                                                    (byte)MCP2210.M_MCP2210_INT_MD_CNT_NONE, (byte)MCP2210.M_MCP2210_SPI_BUS_RELEASE_DISABLED);
                }

                // Convert the data string to bytes to send
                string[] hexStrings = data.Split(',');
                byte[]   txData     = new byte[hexStrings.Length], rxData = new byte[hexStrings.Length];
                for (int n = 0; n < hexStrings.Length; ++n)
                {
                    txData[n] = Convert.ToByte(hexStrings[n], 16);
                }

                // Create the CS mask
                uint csmask = (uint)((int)1 << (int)csIndex);

                // Set the SPI transaction length to the number of bytes that will be sent
                ptxferSize2 = (uint)(txData.Length > 65535 ? 65535 : txData.Length);

                // Configure the MCP2210 and send the data, everything in one call
                res = MCP2210.M_Mcp2210_xferSpiDataEx(deviceHandle, txData, rxData, ref pbaudRate2, ref ptxferSize2, csmask, ref pidleCsVal2, ref pactiveCsVal2, ref pcsToDataDly2,
                                                      ref pdataToCsDly2, ref pdataToDataDly2, ref pspiMd2);
                if (res != MCP2210.M_E_SUCCESS)
                {
                    MCP2210.M_Mcp2210_Close(deviceHandle);
                    Console.WriteLine(" Transfer error: " + res);
                    return(res);
                }

                // Write the output data in hex format
                var txString = new StringBuilder(">TxData: ");
                var rxString = new StringBuilder(">RxData: ");
                for (int n = 0; n < txData.Length; ++n)
                {
                    txString.Append(txData[n].ToString("X"));
                    txString.Append(",");
                    rxString.Append(rxData[n].ToString("X"));
                    rxString.Append(",");
                }

                // Remove last comma
                txString.Length -= 1;
                rxString.Length -= 1;

                Console.WriteLine(txString);
                Console.WriteLine(rxString);

                MCP2210.M_Mcp2210_Close(deviceHandle);
            }

            return(0);
        }