Demo entry 6634630

control

   

Submitted by anonymous on Aug 12, 2017 at 11:25
Language: C#. Code size: 38.6 kB.

namespace TempController
{
    public partial class MainForm : Form
    {
        
        
        
        private SerialPort com_Control = new SerialPort();
        
        private Adam4000Config m_adamConfig;
        private Adam4000Type m_Adam4000Type;
        private AdamCom adamCom;

        private ConfigClass config = new ConfigClass();
        private bool SystemRun = false;
        private bool ControlConnected = false;
        private bool DetectConnected = false;

        private double TempTolerance = 0.1;
        private double TempBase = 0.0;
        private double Dh = 1.0;
        private double u = 1.0;
        private double Kp = 1.0;
        private double Kd = 0.01;
        private double Ki = 0.1;
        private double Voltage = 12.0;

        private double TempIn = 0;
        private double TempEnvironment = 25.0;     //环境温度
        private double TempMax = 0;
        private double TempMin = 0;
        private double TempAve = 0;
        
        private double MassFlow = 0;
        private double PressIn = 0;
        private double Reynolds = 0;

        private double PowerSum = 0.0;
        private double CurrentSum = 0.0;

        private int[,] TempColour;
        private double TempRange = 2;

        private int NumberUnits;
        private int NumberChannels;
        private int NumberPID;
        
        private int[] MoudleAddress;
        private string[] SensorForTempIn;
        private string[] SensorForTempEnvironment;
        private string[] SensorForPress;
        private string[] SensorForFlow;
        private string[] SensorForUint;
        private string[] ResistencesForPort;
        

        private TempForm[] TForm;
        private double[,] DetectValue;
        private double[,] VoltageToTempTable;
        private double[,] VoltageToMassFlowTable;
        private double[] ValuePolarity;
        private double[] ValueOffset;

        private UInt16 PWM_Top = 5000;
        private UInt16 PWM_Max = 1000;
        private UInt16 [] PWM;
        private double[,] E;



        int SavePoint = 10; //存储计数器
        int SaveCounter = 0;
        //源文件连接串  
        string strConn_source;
        OleDbConnection ole_conn;
        OleDbCommand ole_cmd;
        string Label, Title, LabelTotal, TitleTotal;


        public MainForm()
        {
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler(this.Form1_FormClosing);
        }//初始化窗体



        //初始化通讯端口:这段代码的主要功能是获取当前电脑的可用串口名称,
        //并且以列表的形式展现在窗体的控制和检测端口列表中,如COM1,COM3等
        public void InitializePorts()
        {
            string[] p = SerialPort.GetPortNames();//获取当前计算机所有可用串行端口名称的数组
            Array.Sort(p);//排序
            comboBox_Control.Items.AddRange(p);
            comboBox_Detect.Items.AddRange(p);
        }


        //这是在打开控制端口并且在打开之前对控制串口做的一些相关的配置。控制串口是连接FPGA的串口
        public void ControlComOpen()
        {
            if (!com_Control.IsOpen)
            {
                com_Control.PortName = comboBox_Control.Text;
                com_Control.BaudRate = 19200;//设置波特率9600,115200等等,必须和FPGA的波特率相同
                com_Control.DataBits = 8;//每个字节的标准数据长度;
                com_Control.StopBits = StopBits.One;//设置停止位长度,可以为1,1.2,2;(one,onepintfive,two);
                com_Control.Parity = System.IO.Ports.Parity.None;//设置奇偶校验,可以为奇校验或者偶校验,此处没有设置校验位
                com_Control.ReadBufferSize = 512;
                com_Control.WriteBufferSize = 512;//设置读写缓存区大小
                com_Control.Open();//打开串口
                com_Control.DiscardInBuffer();
                com_Control.DiscardOutBuffer();//将初始的缓存区的内容清除
                ControlConnected = true;
            }
            else MessageBox.Show("控制串口打开失败!");

        
        }


        ////这是在打开打开检测串口之前的一些设置,检测串口连接的是Adam
        public void DetectComOpen()
        {

            //m_Adam4000Type = Adam4000Type.Adam4017; // the sample is for ADAM-4017
            m_Adam4000Type = Adam4000Type.Adam4018; // the sample is for ADAM-4018
            adamCom = new AdamCom(Convert.ToInt16(comboBox_Detect.Text.Substring(3)));
            adamCom.Checksum = false; // disbale checksum

            if (adamCom.OpenComPort())
            {
                // set COM port state, 9600,N,8,1
                adamCom.SetComPortState(Baudrate.Baud_115200, Databits.Eight, Advantech.Common.Parity.None, Stopbits.One);//设置波特率、数据位、奇偶校验位、停止位
                // set COM port timeout
                adamCom.SetComPortTimeout(500, 500, 0, 500, 0);//设置读取时间间隔、读取持续时间、读取倍增数、写入持续时间、写入倍增等
                // get module config

                for (int i = 0; i < MoudleAddress.Count(); i++)
                {
                    if (!adamCom.Configuration(MoudleAddress[i]).GetModuleConfig(out m_adamConfig))
                    {
                        adamCom.CloseComPort();
                        MessageBox.Show("获取模块" + MoudleAddress[i] + "数据失败!");
                        return;
                    }
                }//逐个获取Adam模块配置,如果获取不成果说明连接失败
                DetectConnected = true;
            }
            else MessageBox.Show("监测串口打开失败!");

        }

        //此段代码的功能是线性插值
        private double LinearInterp(double X1, double Y1, double X2, double Y2, double X)
        { 
            double Y = 0;
            if (X1 != X2) Y = ((Y2 - Y1) / (X2 - X1)) * (X - X1) + Y1;
            return (Y);
        }
        
        /*该函数实现的是温度转化的功能,即将电压值转化成温度值。具体做法就是利用预设的电压温度表进行线性插值‘
         具体实现过程很简单,如果待插值的电压值在两端用对应端点两个值插值;如果在中间则找到介于两个之间的电进行插值,
         因此由三个分支结构构成*/
        private double TempConvert(double Voltage)
        {
            double Temp = 0;
            int i,n;
            n = VoltageToTempTable.GetLength(0);
            if(Voltage < VoltageToTempTable[0,0]) Temp = LinearInterp(VoltageToTempTable[0,0], VoltageToTempTable[0,1], VoltageToTempTable[1,0], VoltageToTempTable[1,1], Voltage);
            else if(Voltage > VoltageToTempTable[n-1,0]) Temp = LinearInterp(VoltageToTempTable[n-2,0], VoltageToTempTable[n-2,1], VoltageToTempTable[n-1,0], VoltageToTempTable[n-1,1], Voltage);
            else
            {
                for(i=1; i<n; i++)
                {
                    if (Voltage < VoltageToTempTable[i, 0])
                    {
                        Temp = LinearInterp(VoltageToTempTable[i-1,0], VoltageToTempTable[i-1,1], VoltageToTempTable[i,0], VoltageToTempTable[i,1], Voltage);
                        break;
                    }
                }
            }
            return(Temp);
        }


        /*和上面类似*/
        private double MassFlowConvert(double Voltage)
        {
            double  MassFlow = 0;
            int i, n;
            n = VoltageToMassFlowTable.GetLength(0);
            if (Voltage < VoltageToMassFlowTable[0, 0]) MassFlow = 0;
            else if (Voltage > VoltageToMassFlowTable[n - 1, 0]) MassFlow = 200;
            else
            {
                for (i = 1; i < n; i++)
                {
                    if (Voltage < VoltageToMassFlowTable[i, 0])
                    {
                        MassFlow = LinearInterp(VoltageToMassFlowTable[i - 1, 0], VoltageToMassFlowTable[i - 1, 1], VoltageToMassFlowTable[i, 0], VoltageToMassFlowTable[i, 1], Voltage);
                        break;
                    }
                }
            }
            return (MassFlow);
        }


        /*获取当前的温补温度和每个Adam模块的8个探测到的温度,存放在 DetectValue中,
        DetectValue是一个二维数组,第一维度表示模块序号,第二维度表示对应序号下的8个探测值 */
        private void GetData()
        {
            Adam4000_ChannelStatus[] Status;
            float[] Values;
            DetectValue = new double[MoudleAddress.Count(), 8];

            TempBase = Convert.ToDouble(maskedTextBox_TempBase.Text);
            for (int i = 0; i < MoudleAddress.Count(); i++)
            {
                if (adamCom.AnalogInput(MoudleAddress[i]).GetValues(8, out Values, out Status))
                {
                    for(int j=0; j<8; j++)
                    {
                        if (Status[j] == Adam4000_ChannelStatus.Normal) DetectValue[i, j] = Values[j];
                    }
                }
            }
        
        }



        private void CalculateAndDisplay()
        {
            double TempSet, TempNow, Resistences;
            int PWM_Result;
            Int16 Moudle, Channel;
            string[] str;
            double Integration;
            int UnitCount;
            double Power = 0.0;
            bool Flag = false;

            if (maskedTextBox_TempTolerance.Text == null) TempTolerance = 0;
            else TempTolerance = Convert.ToDouble(maskedTextBox_TempTolerance.Text);
            
            if (maskedTextBox_Dh.Text == null) Dh = 0;
            else Dh = Convert.ToDouble(maskedTextBox_Dh.Text);
            
            if (maskedTextBox_Kp.Text == null) Kp = 0;
            else Kp = Convert.ToDouble(maskedTextBox_Kp.Text);
            
            if (maskedTextBox_Kd.Text == null) Kd = 0;
            else Kd = Convert.ToDouble(maskedTextBox_Kd.Text);

            if (maskedTextBox_Ki.Text == null) Ki = 0;
            else Ki = Convert.ToDouble(maskedTextBox_Ki.Text);

            if (maskedTextBox_Voltage.Text == null) Voltage = 0;
            else Voltage = Convert.ToDouble(maskedTextBox_Voltage.Text);/*从界面上对应的文本框获取温度容差、Dh,Kp,ki,kd,电压等值*/

            TempAve = 0;
            UnitCount = 0;
            PowerSum = 0.0;

            for (int i = 0; i < SensorForUint.Count(); i++)
            {

                //获得当前该通道的温度以及加热到的目标温度以及电阻
                str = SensorForUint[i].Split('.');
                Moudle = Convert.ToInt16(str[0]);
                Channel = Convert.ToInt16(str[1]);
                if (TForm[i].maskedTextBox_TempSet.Text == null) TempSet = 0;
                else TempSet = Convert.ToDouble(TForm[i].maskedTextBox_TempSet.Text);
                TempNow = ValuePolarity[i] * (TempConvert(DetectValue[Moudle, Channel]) + TempBase) + ValueOffset[i];
                // ValuePolarity是当前通道温度的极性,在APP.config文件中可以修改,应该是热电偶正负极不统一,导致有些温度是负数
                TForm[i].label_TempNow.Text = TempNow.ToString("F2");
                TForm[i].maskedTextBox_TempSet.Text = TempSet.ToString("F2");
                Resistences = Convert.ToDouble(ResistencesForPort[i]);
                //ResistencesForPort的来源也是通过APP.config文件,具体的值可以通过该文件相关位置修改


                //显示温度颜色,根据不同的温度显示不同的颜色
                if ((TempNow - TempSet) < -TempRange)
                {
                    TForm[i].maskedTextBox_TempSet.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(TempColour[0, 0])))), ((int)(((byte)(TempColour[0, 1])))), ((int)(((byte)(TempColour[0, 2])))));
                }
                else if ((TempNow - TempSet) > TempRange)
                {
                    TForm[i].maskedTextBox_TempSet.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(TempColour[2, 0])))), ((int)(((byte)(TempColour[2, 1])))), ((int)(((byte)(TempColour[2, 2])))));
                }
                else if (Math.Abs(TempNow - TempSet) < TempTolerance)
                {
                    TForm[i].maskedTextBox_TempSet.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(TempColour[1, 0])))), ((int)(((byte)(TempColour[1, 1])))), ((int)(((byte)(TempColour[1, 2])))));
                }
                else if (TempSet > TempNow)
                {
                    TForm[i].maskedTextBox_TempSet.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(TempColour[1, 0] + (TempColour[0, 0] - TempColour[1, 0]) * (TempSet - TempNow) / TempRange)))), ((int)(((byte)(TempColour[1, 1] + (TempColour[0, 1] - TempColour[1, 1]) * (TempSet - TempNow) / TempRange)))), ((int)(((byte)(TempColour[1, 2] + (TempColour[0, 2] - TempColour[1, 2]) * (TempSet - TempNow) / TempRange)))));
                }
                else if (TempNow > TempSet)
                {
                    TForm[i].maskedTextBox_TempSet.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(TempColour[1, 0] + (TempColour[2, 0] - TempColour[1, 0]) * (TempNow - TempSet) / TempRange)))), ((int)(((byte)(TempColour[1, 1] + (TempColour[2, 1] - TempColour[1, 1]) * (TempNow - TempSet) / TempRange)))), ((int)(((byte)(TempColour[1, 2] + (TempColour[2, 2] - TempColour[1, 2]) * (TempNow - TempSet) / TempRange)))));
                }

                if (TForm[i].checkBox_Enable.Checked == true)
                {
                    //计算平均、最大、最小壁温
                    UnitCount++;
                    TempAve += TempNow;
                    if (Flag == false)
                    {
                        TempMax = TempNow;
                        TempMin = TempNow;
                    }
                    else
                    {
                        if (TempMax < TempNow) TempMax = TempNow;
                        if (TempMin > TempNow) TempMin = TempNow;
                    }
                    Flag = true;
                    
                    
                    //进行控制量的计算,利用PID控制算法
                    Integration = 0;
                    for (int j = NumberPID - 1; j > 0; j--)
                    {
                        Integration += E[i, j - 1];
                        E[i, j] = E[i, j - 1];
                    }

                    E[i, 0] = TempSet - TempNow;
                    //PWM_Result = PWM[i] + (int)(Kp * E[i, 0] + Kd * (E[i, 0] - E[i, 1]) + Ki * Integration);
                    PWM_Result = (int)(Kp * E[i, 0] + Kd * (E[i, 0] - E[i, 1]) + Ki * Integration);
                    if (PWM_Result < 0) PWM[i] = 0;
                    else if (PWM_Result < PWM_Max) PWM[i] = (UInt16)PWM_Result;
                    else PWM[i] = PWM_Max;

                    //计算功率
                    Power = (1000 * (1.0 * PWM[i] / PWM_Top) * Voltage * Voltage / Resistences);
                    TForm[i].label_Power.Text = Power.ToString("F2");
                    PowerSum += Power;
                }
                else
                {
                    PWM[i] = 0;
                    TForm[i].label_Power.Text = "0.00";
                }
            }
            if (UnitCount > 0) TempAve = TempAve / UnitCount;
            TempIn = TempConvert(DetectValue[Convert.ToInt16(SensorForTempIn[0]), Convert.ToInt16(SensorForTempIn[1])])+ TempBase;
            TempEnvironment = TempConvert(DetectValue[Convert.ToInt16(SensorForTempEnvironment[0]), Convert.ToInt16(SensorForTempEnvironment[1])])+ TempBase;

            PressIn = (DetectValue[Convert.ToInt16(SensorForPress[0]), Convert.ToInt16(SensorForPress[1])] - 4) * 62.16 / 16;
            MassFlow = MassFlowConvert(DetectValue[Convert.ToInt16(SensorForFlow[0]), Convert.ToInt16(SensorForFlow[1])]);
            //Reynolds = (MassFlow / 5) * 4 / (3.14159 * Dh) / u;  //17.6*10^-6为10℃时空气动力粘度 或者μ=0.0000181
            Reynolds = MassFlow / 0.016455;

            //将计算结果显示在右侧的标签区域
            label_TempIn.Text = TempIn.ToString("F2") + " ℃";
            label_TempEnvironment.Text = TempEnvironment.ToString("F2") + " ℃";
            label_TempAve.Text = TempAve.ToString("F2") + " ℃";
            label_TempMax.Text = TempMax.ToString("F2") + " ℃";
            label_TempMin.Text = TempMin.ToString("F2") + " ℃";
            label_PressIn.Text = PressIn.ToString("F2") + " KPa";
            label_MassFlow.Text = MassFlow.ToString("F2") + " Kg/h";
            label_Re.Text = Reynolds.ToString("F2");
            label_PowerSum.Text = (PowerSum / 1000).ToString("F2") + " W";

            CurrentSum = PowerSum/Voltage;
            label_CurrentSum.Text = (CurrentSum / 1000).ToString("F2") + " A";
        }
        /*将得到的控制量进行加工,通过控制端口发送给FPGA进行电压控制*/
        private void Control()
        {
            byte Temp=0,Sum=0;
            byte[] Buf = new byte[2*NumberUnits+3];
            Buf[0] = 0xAA;
            Buf[1] = 0xAA;
            for(int i=0; i<NumberUnits; i++)
            {
                Temp = (byte)(PWM[i]>>8);
                Buf[2*i+2] = Temp; 
                Sum += Temp;
                Temp = (byte)(PWM[i]);
                Buf[2*i+3] = Temp; 
                Sum += Temp;
            }
            Buf[2 * NumberUnits + 2] =(byte)(Sum + Buf[0] + Buf[1]);
            com_Control.Write(Buf, 0, 2*NumberUnits + 3);
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            string StrTempSet="";
            string StrUnitEnable = "";
            if (SystemRun == true)
            {
                timer.Enabled = false; // disable timer
                adamCom.CloseComPort(); //关闭监测串口
                com_Control.Close();    //关闭控制串口
                config.SaveConfig("ControlNO", comboBox_Control.SelectedItem.ToString());
                config.SaveConfig("DetectNO", comboBox_Detect.SelectedItem.ToString());

            }
            //关闭窗口的时候保存相关配置
            config.SaveConfig("TempTolerance", maskedTextBox_TempTolerance.Text);
            config.SaveConfig("TempBase", maskedTextBox_TempBase.Text);
            config.SaveConfig("Dh", maskedTextBox_Dh.Text);
            config.SaveConfig("u", maskedTextBox_u.Text);
            config.SaveConfig("Kp", maskedTextBox_Kp.Text);
            config.SaveConfig("Kd", maskedTextBox_Kd.Text);
            config.SaveConfig("Ki", maskedTextBox_Ki.Text);
            config.SaveConfig("Voltage", maskedTextBox_Voltage.Text);

            //保存设定温度和单元使能状态
            for (int n = 0; n < NumberUnits; n++)
            {
                StrTempSet += TForm[n].maskedTextBox_TempSet.Text + ',';
                if (TForm[n].checkBox_Enable.Checked == true) StrUnitEnable += n.ToString() + ',';
            }
            if (StrUnitEnable.Length > 0)
            {
                StrUnitEnable = StrUnitEnable.Substring(0, StrUnitEnable.Length - 1);
            }
            StrTempSet = StrTempSet.Substring(0, StrTempSet.Length - 1);      
            config.SaveConfig("UnitTempSet", StrTempSet);
            //config.SaveConfig("UnitEnable", StrUnitEnable);

            ole_conn.Close();

        }


        private void Form1_Load(object sender, EventArgs e)
        {
            string[] str;
            int i;
            InitializePorts();
            //设置配置文件名,读取配置文件(APP.config)中的一些配置
            config.SetConfigName("TempController.exe.config");
            maskedTextBox_TempTolerance.Text = config.ReadConfig("TempTolerance");
            maskedTextBox_TempBase.Text = config.ReadConfig("TempBase");

            maskedTextBox_Dh.Text = config.ReadConfig("Dh");
            maskedTextBox_u.Text = config.ReadConfig("u");
            
            maskedTextBox_Kp.Text = config.ReadConfig("Kp");
            maskedTextBox_Kd.Text = config.ReadConfig("Kd");
            maskedTextBox_Ki.Text = config.ReadConfig("Ki");
            maskedTextBox_Voltage.Text = config.ReadConfig("Voltage");
            

            
            NumberUnits = Convert.ToInt16(config.ReadConfig("NumberUnits"));
            NumberPID = Convert.ToInt16(config.ReadConfig("NumberPID"));
            NumberChannels = Convert.ToInt16(config.ReadConfig("NumberChannels"));
            SavePoint = Convert.ToInt16(config.ReadConfig("SavePoint"));
            SensorForTempEnvironment = config.ReadConfig("SensorForTempEnvironment").Split('.');
            SensorForTempIn = config.ReadConfig("SensorForTempIn").Split('.');
            SensorForPress = config.ReadConfig("SensorForPress").Split('.');
            SensorForFlow = config.ReadConfig("SensorForFlow").Split('.');

            PWM_Max = (UInt16)(PWM_Top * Convert.ToDouble(config.ReadConfig("PWMMax")));

            SensorForUint= new string[NumberUnits] ;
            TForm= new TempForm[NumberUnits] ;
            PWM= new UInt16[NumberUnits] ;
            E= new double[NumberUnits,NumberPID];
            ValuePolarity = new double[NumberUnits];
            ValueOffset = new double[NumberUnits];

            //温度设定
            TempColour = new int[3, 3];
            //低温 蓝色
            TempColour[0, 0] = 128;
            TempColour[0, 1] = 128;
            TempColour[0, 2] = 255;

            //目标温度颜色 绿色
            TempColour[1, 0] = 128;
            TempColour[1, 1] = 255;
            TempColour[1, 2] = 128;
            
            //高温 红色
            TempColour[2, 0] = 255;
            TempColour[2, 1] = 128;
            TempColour[2, 2] = 128;


            /*获取电压温度插值映射表,表中具体数值存储在APP.config文件中,如果需要修改可以在该文件的对应KEY值下修改,
          映射表的格式是一对温度和电压用短线连接,不同对之间用逗号隔开,例如“0-0, 0.391-10, 0.789-20, 1.196-30, 1.611-40”
          因此下面的程序就是按照这样的逻辑将config文件中的字符串形式的映射表转化成了二维数组*/
            string[] result;
            str = config.ReadConfig("VoltageToTempTable").Split(',');
            VoltageToTempTable = new double[str.Count(), 2];
            i = 0;
            if (str[0] != "")
            {
                foreach (string s in str)
                {
                    result = s.Split('-');
                    VoltageToTempTable[i, 0] = Convert.ToDouble(result[0]);
                    VoltageToTempTable[i, 1] = Convert.ToDouble(result[1]);
                    i++;
                }
            }


            str = config.ReadConfig("VoltageToMassFlowTable").Split(',');
            VoltageToMassFlowTable = new double[str.Count(), 2];
            i = 0;
            if (str[0] != "")
            {
                foreach (string s in str)
                {
                    result = s.Split('-');
                    VoltageToMassFlowTable[i, 0] = Convert.ToDouble(result[0]);
                    VoltageToMassFlowTable[i, 1] = Convert.ToDouble(result[1]);
                    i++;
                }
            }


            //获取模块地址,具体过程同上,下同
            str = config.ReadConfig("MoudleAddress").Split(',');
            MoudleAddress = new int[str.Count()]; 
            i = 0;
            if (str[0] != "")
            {
                foreach (string s in str)
                {
                    MoudleAddress[i] = Convert.ToInt16(s);
                    i++;
                }
            }

            //获取传感器与加热单元映射表
            SensorForUint = (config.ReadConfig("SensorForPort1") + ','
                            + config.ReadConfig("SensorForPort2")+ ','
                            + config.ReadConfig("SensorForPort3")+ ','
                            + config.ReadConfig("SensorForPort4")+ ','
                            + config.ReadConfig("SensorForPort5")+ ','
                            + config.ReadConfig("SensorForPort6")+ ','
                            + config.ReadConfig("SensorForPort7")).Split(',');
   
            if (SensorForUint.Count() != NumberUnits)
            {
                MessageBox.Show("温度传感器与加热器映射表与加热器的数量不符!");
                Run.Enabled = false;
            }


            //获取加热单元电阻值
            ResistencesForPort = (config.ReadConfig("ResistencesForPort1") + ','
                + config.ReadConfig("ResistencesForPort2") + ','
                + config.ReadConfig("ResistencesForPort3") + ','
                + config.ReadConfig("ResistencesForPort4") + ','
                + config.ReadConfig("ResistencesForPort5") + ','
                + config.ReadConfig("ResistencesForPort6") + ','
                + config.ReadConfig("ResistencesForPort7")).Split(',');

            if (SensorForUint.Count() != NumberUnits)
            {
                MessageBox.Show("温度传感器与加热器映射表与加热器的数量不符!");
                Run.Enabled = false;
            }

          

            //获取加热单元开启状态
            for (i = 0; i < NumberUnits; i++)
            {
                TForm[i] = (TempForm)this.Controls.Find("tempForm" + (i + 1), true)[0];
            }
            str = config.ReadConfig("UnitEnable").Split(',');
            if (str[0] != "")
            {
                foreach (string s in str)
                {
                    TForm[Convert.ToInt16(s)].checkBox_Enable.Checked = true;
                }
            }
            //获取设置温度
            str = config.ReadConfig("UnitTempSet").Split(',');
            i = 0;
            if (str[0] != "")
            {
                foreach (string s in str)
                {
                    TForm[i].maskedTextBox_TempSet.Text = Convert.ToDouble(s).ToString("F2");
                    i++;
                }
            }

            //获取温度极性极性
            str = config.ReadConfig("ValuePolarity").Split(',');
            i = 0;
            if (str[0] != "")
            {
                foreach (string s in str)
                {
                    ValuePolarity[i] = Convert.ToDouble(s);
                    i++;
                }
            }


            //获取温度温度补偿
            str = config.ReadConfig("ValueOffset").Split(',');
            i = 0;
            if (str[0] != "")
            {
                foreach (string s in str)
                {
                    ValueOffset[i] = Convert.ToDouble(s);
                    i++;
                }
            }

            //设置默认控制串口
            if (comboBox_Control.Items.Contains(config.ReadConfig("ControlNO")))
            {
                comboBox_Control.SelectedItem = config.ReadConfig("ControlNO");
                //ControlComOpen();
            }
            else MessageBox.Show("控制串口选择不存在!");
            //设置默认监测串口
            if (comboBox_Detect.Items.Contains(config.ReadConfig("DetectNO")))
            {
                comboBox_Detect.SelectedItem = config.ReadConfig("DetectNO");
                //DetectComOpen();
            }
            else MessageBox.Show("监测串口选择不存在!");


            /*建立数据库,实时保存运行数据,保存的位置在程序根目录的data文件夹中,以xls格式保存*/
            strConn_source = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
    + AppDomain.CurrentDomain.BaseDirectory.ToString() +"data\\"+ DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".xls" + ";"
    + "Extended Properties='Excel 8.0;HDR=YES'";
            ole_conn = new OleDbConnection(strConn_source);
            ole_conn.Open();
            ole_cmd = ole_conn.CreateCommand();

            Label = "([系统时间] Char,";
            Title = "(系统时间,";
            for (i = 0; i < NumberUnits; i++)
            {
                Label += "[测试点" + (i + 1).ToString() + "]Decimal,";
                Title += "测试点" + (i + 1).ToString() + ",";
            }
            Label = Label.Remove(Label.Length - 1);
            Title = Title.Remove(Title.Length - 1);
            Label += ")";
            Title += ")";

            LabelTotal = "([系统时间] Char,[入口温度] Decimal,[环境温度] Decimal,[平均壁温] Decimal,[最大壁温] Decimal,[最小壁温] Decimal,[入口压力] Decimal,[质量流量] Decimal,[雷诺数] Decimal,";
            TitleTotal = "(系统时间,入口温度,环境温度,平均壁温,最大壁温,最小壁温,入口压力,质量流量,雷诺数,";
            for (i = 0; i < NumberUnits; i++)
            {
                LabelTotal += "[测试点" + (i + 1).ToString() + "当前]Decimal,";
                TitleTotal += "测试点" + (i + 1).ToString() + "当前,";
            }
            for (i = 0; i < NumberUnits; i++)
            {
                LabelTotal += "[测试点" + (i + 1).ToString() + "功率]Decimal,";
                TitleTotal += "测试点" + (i + 1).ToString() + "功率,";
            }
            LabelTotal = LabelTotal.Remove(LabelTotal.Length - 1);
            TitleTotal = TitleTotal.Remove(TitleTotal.Length - 1);
            LabelTotal += ")";
            TitleTotal += ")";

            ole_cmd.CommandText = "CREATE TABLE 总表 " + LabelTotal;
            ole_cmd.ExecuteNonQuery();
            ole_cmd.CommandText = "CREATE TABLE 目标 " + Label;
            ole_cmd.ExecuteNonQuery();
            ole_cmd.CommandText = "CREATE TABLE 当前 " + Label;
            ole_cmd.ExecuteNonQuery();
            ole_cmd.CommandText = "CREATE TABLE 功率 " + Label;
            ole_cmd.ExecuteNonQuery();
            ole_cmd.CommandText = "CREATE TABLE 系统参数 ([系统时间] Char,[入口温度] Decimal,[环境温度] Decimal,[平均壁温] Decimal,[最大壁温] Decimal,[最小壁温] Decimal,[入口压力] Decimal,[质量流量] Decimal,[雷诺数] Decimal)";
            ole_cmd.ExecuteNonQuery();

            //Control();
            SaveData();
        }
        /*"运行/停止"按键的回调函数*/
        private void Run_Click(object sender, EventArgs e)
        {
            byte[] Buf = new byte[2 * NumberUnits + 3];

            if (SystemRun == true)
            {
                //使所有通道停止工作
                Buf[0] = 0xAA;
                Buf[1] = 0xAA;
                for (int i = 0; i < NumberUnits; i++)
                {
                    Buf[2 * i + 2] = 0x00;
                    Buf[2 * i + 3] = 0x00;
                }
                Buf[2 * NumberUnits + 2] = (byte)(0x00 + Buf[0] + Buf[1]);
                com_Control.Write(Buf, 0, 2 * NumberUnits + 3);

                timer.Stop();
                Run.Text = "运行";
                Run.BackColor = System.Drawing.SystemColors.Control;
                SystemRun = false;
                //ole_conn.Close();
            }
            else
            {
                if (ControlConnected == false)
                {
                    MessageBox.Show("请选择控制串口!");
                    return;
                }
                if(DetectConnected == false)
                {
                    MessageBox.Show("请选择监测串口!");
                    return;
                }


                for(int i = 0; i < NumberUnits; i++)
                {
                    PWM[i] = 0;
                    for (int j = 0; j < NumberPID; j++)
                    {
                        E[i,j] = 0;
                    }
                }

                SaveCounter = 0;

                timer.Start();
                Run.Text = "停止";
                SystemRun = true;
            }

        }


        /*用于数据保存的函数*/
        private void SaveData()
        {
            string TempSet, TempNow, Power, ValueTotal;
            string Time;
            Time = DateTime.Now.ToString("yyyy/MM/dd-HH:mm:ss");
            SaveCounter++;
            if (SaveCounter == SavePoint)
            {
                SaveCounter = 0;

                TempSet = "('" + Time.ToString() + "',";
                TempNow = "('" + Time.ToString() + "',";
                Power = "('" + Time.ToString() + "',";
                for (int i = 0; i < NumberUnits; i++)
                {
                    
                    TempSet +=  TForm[i].maskedTextBox_TempSet.Text + ",";
                    TempNow +=  TForm[i].label_TempNow.Text + ",";
                    Power +=  TForm[i].label_Power.Text + ",";
                }
                TempSet = TempSet.Remove(TempSet.Length - 1);
                TempNow = TempNow.Remove(TempNow.Length - 1);
                Power = Power.Remove(Power.Length - 1);


                TempSet += ")";
                TempNow += ")";
                Power += ")";

                ValueTotal = "('" + Time.ToString() + "'," + TempIn.ToString() + "," + TempEnvironment.ToString() + "," + TempAve.ToString() + "," + TempMax.ToString() + "," + TempMin.ToString() + "," + PressIn.ToString() + "," + MassFlow.ToString() + "," + Reynolds.ToString() + ",";
                for (int i = 0; i < NumberUnits; i++)
                {
                    ValueTotal += TForm[i].label_TempNow.Text + ",";
                }
                for (int i = 0; i < NumberUnits; i++)
                {
                    ValueTotal += TForm[i].label_Power.Text + ",";
                }
                ValueTotal = ValueTotal.Remove(ValueTotal.Length - 1);
                ValueTotal += ")";



                ole_cmd.CommandText = "insert into 总表" + TitleTotal + "values" + ValueTotal;
                ole_cmd.ExecuteNonQuery();

                ole_cmd.CommandText = "insert into 目标" + Title + "values" + TempSet;
                ole_cmd.ExecuteNonQuery();
                ole_cmd.CommandText = "insert into 当前" + Title + "values" + TempNow;
                ole_cmd.ExecuteNonQuery();
                ole_cmd.CommandText = "insert into 功率" + Title + "values" + Power;
                ole_cmd.ExecuteNonQuery();
                ole_cmd.CommandText = "insert into 系统参数 (系统时间,入口温度,环境温度,平均壁温,最大壁温,最小壁温,入口压力,质量流量,雷诺数)values('"
                   + Time.ToString() + "'," + TempIn.ToString() + "," + TempEnvironment.ToString() + "," + TempAve.ToString() + "," + TempMax.ToString() + "," 
                    + TempMin.ToString() + "," + PressIn.ToString() + "," + MassFlow.ToString() + ","+ Reynolds.ToString() + ")";
                ole_cmd.ExecuteNonQuery();
            }
        }


        /*探测串口选择列表选项变化之后的回调函数*/
        private void comboBox_Detect_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetectComOpen();
        }
        /*控制串口选择列表选项变化之后的回调函数*/
        private void comboBox_Control_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlComOpen();

        }
        /*系统时钟的回调函数,系统时钟运行过程中不断执行的操作,也就是说只要运行键按下之后,会重复执行下面的函数*/
        private void timer_Tick(object sender, EventArgs e)
        {
            GetData();
            CalculateAndDisplay();
            Control();
            SaveData();
        }

        /*以下代码是界面左侧的“打开”按键的回调函数,用于批量打开加热单元*/
        private bool Status_button1 = false;
        private void button1_Click(object sender, EventArgs e)
        {
            if (Status_button1)
            {
                Status_button1 = false;
                button1.Text = "打开";
                for (int n = 0; n < 9; n++)
                {
                    TForm[n].checkBox_Enable.Checked = false;
                }
            
            }
            else
            {
                Status_button1 = true;
                button1.Text = "关闭";
                for (int n = 0; n < 9; n++)
                {
                    TForm[n].checkBox_Enable.Checked = true;
                }

            }
        }

        private bool Status_button2 = false;
        private void button2_Click(object sender, EventArgs e)
        {
            if (Status_button2)
            {
                Status_button2 = false;
                button2.Text = "打开";
                for (int n = 9; n < 18; n++)
                {
                    TForm[n].checkBox_Enable.Checked = false;
                }

            }
            else
            {
                Status_button2 = true;
                button2.Text = "关闭";
                for (int n = 9; n < 18; n++)
                {
                    TForm[n].checkBox_Enable.Checked = true;
                }

            }
        }

        private bool Status_button3 = false;
        private void button3_Click(object sender, EventArgs e)
        {
            if (Status_button3)
            {
                Status_button3 = false;
                button3.Text = "打开";
                for (int n = 18; n < 27; n++)
                {
                    TForm[n].checkBox_Enable.Checked = false;
                }

            }
            else
            {
                Status_button3 = true;
                button3.Text = "关闭";
                for (int n = 18; n < 27; n++)
                {
                    TForm[n].checkBox_Enable.Checked = true;
                }

            }

        }

        private bool Status_button4 = false;
        private void button4_Click(object sender, EventArgs e)
        {
            if (Status_button4)
            {
                Status_button4 = false;
                button4.Text = "打开";
                for (int n = 27; n < 36; n++)
                {
                    TForm[n].checkBox_Enable.Checked = false;
                }

            }
            else
            {
                Status_button4 = true;
                button4.Text = "关闭";
                for (int n = 27; n < 36; n++)
                {
                    TForm[n].checkBox_Enable.Checked = true;
                }

            }
        }

        private bool Status_button5 = false;
        private void button5_Click(object sender, EventArgs e)
        {
            if (Status_button5)
            {
                Status_button5 = false;
                button5.Text = "打开";
                for (int n = 36; n < 45; n++)
                {
                    TForm[n].checkBox_Enable.Checked = false;
                }

            }
            else
            {
                Status_button5 = true;
                button5.Text = "关闭";
                for (int n = 36; n < 45; n++)
                {
                    TForm[n].checkBox_Enable.Checked = true;
                }

            }
        }

        private bool Status_button6 = false;
        private void button6_Click(object sender, EventArgs e)
        {
            if (Status_button6)
            {
                Status_button6 = false;
                button6.Text = "打开";
                for (int n = 45; n < 54; n++)
                {
                    TForm[n].checkBox_Enable.Checked = false;
                }

            }
            else
            {
                Status_button6 = true;
                button6.Text = "关闭";
                for (int n = 45; n < 54; n++)
                {
                    TForm[n].checkBox_Enable.Checked = true;
                }

            }
        }

        private bool Status_button7 = false;
        private void button7_Click(object sender, EventArgs e)
        {
            if (Status_button7)
            {
                Status_button7 = false;
                button7.Text = "打开";
                for (int n = 54; n < 63; n++)
                {
                    TForm[n].checkBox_Enable.Checked = false;
                }

            }
            else
            {
                Status_button7 = true;
                button7.Text = "关闭";
                for (int n = 54; n < 63; n++)
                {
                    TForm[n].checkBox_Enable.Checked = true;
                }

            }
        }

    }
}

This snippet took 0.10 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).