private double tempApproach(ctData ctprogin)
        {
            double approach;
            double temp = 0;

            while (tempData.Count == 0)
            {
                System.Threading.Thread.Sleep(1000);
            }

            /*for (int i = 0; i < tempaveraging; i++)
             * {
             * // MessageBox.Show("tempData.Count: " + tempData.Count + "\ntempaveraging: " + tempaveraging + "\ni: " + i);
             *  temp += tempData.ElementAt<double>(tempData.Count - 3 + i);
             * } */
            temp = tempData.Last();
            //approach = Math.Round( 100*(100 * (ctprogin.temperature - temp / tempaveraging) / (temp / tempaveraging)))/100;
            //approach =Math.Round(10*(ctprogin.temperature - temp/tempaveraging))/10;
            approach = ctprogin.temperature - temp;
            return(approach);
        }
        private void treadButton_Click(object sender, EventArgs e)
        {
            if (!treading)
            {
                treadButton.Enabled = false;
                this.dataGridView1.SelectAll();
                foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
                {
                    ctData ctdata1 = row.DataBoundItem as ctData;
                    if (ctdata1 != null)
                    {
                        // MessageBox.Show("ctDAta" + ctdata1.maximumCurr);
                        ctprog.Add(ctdata1);
                    }
                }
                ctprog.Reverse();
                try
                {
                    double control = ctprog.Last <ctData>().maximumCurr;



                    /* if (ctprog.Count != 0)
                     * {
                     *  MessageBox.Show("You have programmed " + ctprog.Count + " steps");
                     * }
                     * else if (ctprog.Count == 0)
                     * {
                     *  MessageBox.Show("You don't have any programmed step for Auto mode");
                     * }*/
                }
                catch
                {
                    MessageBox.Show("You don't have any programmed step for Auto mode");
                }
                try
                {
                    myTask = new Task();
                    AIChannel          myChannel;
                    AIThermocoupleType thermocoupleType;
                    AIAutoZeroMode     autoZeroMode;

                    switch (thermocoupleTypeSelector.SelectedIndex)
                    {
                    case 0:
                        thermocoupleType = AIThermocoupleType.T;
                        break;

                    case 1:
                        thermocoupleType = AIThermocoupleType.K;
                        break;

                    case 2:
                        thermocoupleType = AIThermocoupleType.B;
                        break;

                    case 3:
                        thermocoupleType = AIThermocoupleType.E;
                        break;

                    case 4:
                        thermocoupleType = AIThermocoupleType.J;
                        break;

                    case 5:
                        thermocoupleType = AIThermocoupleType.R;
                        break;

                    case 6:
                        thermocoupleType = AIThermocoupleType.S;
                        break;

                    case 7:
                    default:
                        thermocoupleType = AIThermocoupleType.N;
                        break;
                    }

                    myChannel = myTask.AIChannels.CreateThermocoupleChannel(tempReaderChannel.Text,
                                                                            "", Convert.ToDouble(minimumValueNumeric), Convert.ToDouble(maximumValueNumeric),
                                                                            thermocoupleType, AITemperatureUnits.DegreesC, Convert.ToDouble(cjcValueNumeric));
                    autoZeroMode           = AIAutoZeroMode.None;
                    myChannel.AutoZeroMode = autoZeroMode;
                    myTask.Timing.ConfigureSampleClock("", Convert.ToDouble(rateNumeric),
                                                       SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000);



                    myTask.Control(TaskAction.Verify);

                    analogInReader = new AnalogMultiChannelReader(myTask.Stream);

                    runningTask = myTask;
                    InitializeDataTable(myTask.AIChannels, ref dataTable);
                    //acquisitionDataGrid.DataSource = dataTable;

                    // Use SynchronizeCallbacks to specify that the object
                    // marshals callbacks across threads appropriately.
                    analogInReader.SynchronizeCallbacks = true;
                    analogInReader.BeginReadWaveform(10, myAsyncCallback, myTask);
                }
                catch (DaqException exception)
                {
                    MessageBox.Show("Exception at TC Initialization" + exception.Message);
                    myTask.Dispose();
                    autostartButton.Enabled = true;
                    autostopButton.Enabled  = false;
                    runningTask             = null;
                }
                treading = true;
            }
        }
        private void bgwauto_DoWork(object sender, DoWorkEventArgs e)
        {
            double voltageauto  = 5;
            double currentlimit = 0;

            //int autotimer = 0;
            try
            {
                ctData cttest = ctprog.Last <ctData>();
                // MessageBox.Show("Current Auto" + cttest.maximumCurr);
                BackgroundWorker worker = sender as BackgroundWorker;
                if (fileopened)
                {
                    fs_writer.WriteLine("TIME,   CURRENT, VOLTAGE,   TEMPERATURE, SETPOINT, PREAPPROACHER, APPROACHER, INTEGRAL, DERIVATIVE , PROGRAM NO, MAX. CURRENT,PROG. DURATION");
                }
                foreach (ctData ctprog1 in this.ctprog)
                {
                    autoloopbreak = true;


                    derivative = 0;
                    integral   = 0;

                    preapproacher = ctprog1.temperature;
                    currentmax    = ctprog1.maximumCurr;
                    double currentmin = ctprog1.minimumCurr;
                    currentlimit = currentmax;
                    setpoint     = ctprog1.temperature;
                    autoduration = ctprog1.duration;
                    autotimer    = 0;

                    currentauto = (currentmax + currentmin) / 3;
                    //MessageBox.Show("burda" + currentauto);
                    derivative = 0;
                    //pSC1.getOutputHandler(pSC1).VoltageLimit = 5;
                    if (iterator == 0)
                    {
                        pSC1.getOutputHandler(pSC1).VoltageLevel = voltageauto;
                        pSC1.getOutputHandler(pSC1).CurrentLimit = 20;
                        pSC1.getOutputHandler(pSC1).Enabled      = true;
                    }
                    else
                    {
                    }

                    //approacher = setpoint - tempData.Last();
                    preapproacher = approacher;
                    //MessageBox.Show("Current Auto" + currentauto +"\nDuration: "+autotimer);
                    //MessageBox.Show("iterotor is :" + iterator + "\nCount is : "+ ctprog1);
                    while (autoloopbreak)
                    {
                        System.Threading.Thread.Sleep(1000);
                        // MessageBox.Show("iterotor is :" + iterator + "\n" + "Approach is:" + tempApproach(iterator));\
                        //approacher = tempApproach(setpoint);
                        while (tempData.Count < 3)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        temp = 0;

                        /* for (int i = 0; i < tempaveraging; i++)
                         * {
                         *   // MessageBox.Show("tempData.Count: " + tempData.Count + "\ntempaveraging: " + tempaveraging + "\ni: " + i);
                         *   temp += tempData.ElementAt<double>(tempData.Count - 3 + i) / tempaveraging;
                         * }*/
                        temp = tempData.Last();
                        worker.ReportProgress(50);
                        //approach = Math.Round( 100*(100 * (ctprogin.temperature - temp / tempaveraging) / (temp / tempaveraging)))/100;
                        approacher = setpoint - temp;// tempData.Last();

                        integral += approacher;
                        if (autotimer < 1)
                        {
                            preapproacher = approacher;
                            derivative    = (approacher - preapproacher);
                        }
                        else
                        {
                            derivative    = (approacher - preapproacher);
                            preapproacher = approacher;
                        }
                        //label10.Text = "Preapprocher= " + preapproacher + " APproacher= " + approacher;
                        //derivative = (approacher - preapproacher);

                        currentauto = approacher * kp * 1 + integral * ki * 0.001 + derivative * kd;

                        //MessageBox.Show("approacher * kp*0.1" + (approacher * kp * 0.1) + " integral*ki*0.01" + (integral * ki * 0.01) + " derivative*kd" + (derivative * kd));
                        //currentauto = approacher * kp;
                        if (currentauto > currentmax)
                        {
                            currentauto = currentmax;
                        }
                        else if (currentauto < currentmin)
                        {
                            currentauto = currentmin;
                        }
                        else
                        {
                            currentauto = currentauto;
                        }

                        pSC1.getOutputHandler(pSC1).CurrentLimit = currentauto;

                        //MessageBox.Show("while in icinde", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        //MessageBox.Show("for in icinde i=" + i, "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);


                        worker.ReportProgress(0);

                        if ((worker.CancellationPending == true))
                        {
                            break;
                        }
                        if (autotimer <= autoduration)
                        {
                            //MessageBox.Show("simdi true");
                            autoloopbreak = true;
                        }
                        else
                        {
                            //MessageBox.Show("simdi false");
                            pSC1.getOutputHandler(pSC1).CurrentLimit = 20;
                            autoloopbreak = false;
                        }

                        autotimer++;
                        totaltimer++;
                    }
                    iterator++;
                }
                if (contcooling.Enabled)
                {
                    double currentdecreaserate = (double)currentdown.Value;
                    //MessageBox.Show("Control Cooling State= "+contcooling.Enabled, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    int currentstep = (int)(100 / (currentdecreaserate));
                    //MessageBox.Show("istep= " + currentstep);
                    if (currentstep > 0)
                    {
                        for (int innerstep = 1; innerstep <= currentstep; innerstep++)
                        {
                            currentauto -= currentauto * currentdecreaserate / 100;
                            //MessageBox.Show("I= " + currentauto + " innerstep= " + innerstep + " currentdecreaserate= " + currentdecreaserate);
                            if (currentauto < currentlimit && currentauto > 0)
                            {
                                pSC1.getOutputHandler(pSC1).CurrentLimit = currentauto;
                                System.Threading.Thread.Sleep(1000);
                                worker.ReportProgress(0);
                                totaltimer++;
                                coolingtime++;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
                currentauto = 0;
                pSC1.getOutputHandler(pSC1).CurrentLimit = currentauto;
                pSC1.getOutputHandler(pSC1).Enabled      = false;
            }

            catch (Exception ex1)
            {
                // pSC1.disable();
                MessageBox.Show("Auto Start  Button Exception occured :\n" + ex1.Message + " " + ex1.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }