do.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace does
{

    public partial class does: Form
    { 
       
        [DllImport("kernel32.dll")]

 static extern uint GetTickCount(); 
  static void Delay(uint ms) {
      uint start = GetTickCount();
        while (GetTickCount() - start < ms) {
        Application.DoEvents();
    }
 }

        private byte[] bytSendData;
       // private String strSendData=""  ; //用来保存发送区的数据
        private Boolean bComOpen;//标志串口是否打开
        private Boolean bSendHex=false ;//发送区是十六进制标志
        private Boolean bReceiveHex = false;//接收区是按十六进制显示的标志
        private delegate void DataReceivedEventHandler(); //委托声明
        private int intReceiveDataCount=0; //接收数据的个数
        private int intSendDataCount=0;   //发送数据的个数
        private String weight = "";//run()中的临时变量
        private String s = "";
        private Boolean bStopShow = false;
        private double[,] speed = {{0,0,0,0,0,0},{1,1,1,1,1,1},{0,1.09,1.69,0.95,0.98,1.05},{0,2.56,2.02,1.88,1.83,1.74},{0,2.44,2.34,2.42,2.34,2.38}};
        //speed是测出来的速度;{0,}
        private double xishu=1;  //run()函数的速度选择比较系数,可以调节,以控制速度大小
        private double temp,  tim;  
        private string speeds;//速度等级
        private long[] sid;//试剂编号所对应的所在端口
        private double[] sweight;//试剂重量
        string testjieguo="";//测试储存结果,show()一下,可以存到数据库
        private double dangqianzhongliang;//当前重量
        private double mubiao;//目标重量
        private uint delaytime=3000;//默认等待时间3秒
        double wucha = 0.1;//误差调节,判断实际与目标的差值是否在0.1以内
        public does(long[] id,double[] weight)
        {
            InitializeComponent();
            sid = id;
            sweight = weight;
            show("  请检查端口号是否对应然后单击打开串口开始配置   ");
            show("  本次要配置的信息如下  ");
            for (int i = 0; i < sid.Length; i++)
            {
                show( "  sid =  "+sid[i]+"  sweght=  "+sweight[i]);
            }
        }
        public double  get()
        {
            //MessageBox.Show(weight.ToString());
            int i = weight.IndexOf("g");
            if (i == 8)
            {
                string a = weight.Substring(0, i);
                a.Trim();
                return double.Parse(a);
            }
            else
            {
                return 0.00 ;
            }
          
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LoadSerialPortConfiguration();
           cmbPortName.SelectedIndex =1;
            cmbBaudRate.SelectedIndex = 6;
            cmbDataBits.SelectedIndex = 4;
            cmbStopBits.SelectedIndex = 1;
            cmbParity.SelectedIndex = 0;
          comboBox5.SelectedIndex = 0;
            comboBox4.SelectedIndex = 6;
            comboBox3.SelectedIndex = 4;
            comboBox2.SelectedIndex = 1;
            comboBox1.SelectedIndex = 0;
        }
        private void LoadSerialPortConfiguration()
        {
            foreach (string s in SerialPort.GetPortNames())
            {
                cmbPortName.Items.Add(s);
                comboBox5.Items.Add(s);
            }

            foreach (string s in Enum.GetNames(typeof(Parity)))
            {
                cmbParity.Items.Add(s); 
                comboBox1.Items.Add(s); 
            }

            foreach (string s in Enum.GetNames(typeof(StopBits)))
            {
                cmbStopBits.Items.Add(s); 
                comboBox2.Items.Add(s);
            }
        }

        private void btnOpenSerialPort_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == false)
            {
                try
                {
                    //设置serialPort1的串口属性
                    serialPort2.PortName = comboBox5.Text; ;
                    serialPort2.BaudRate = int.Parse(comboBox4.Text);
                    serialPort2.DataBits = int.Parse(comboBox3.Text);
                    serialPort2.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox2.Text);
                    serialPort2.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox1.Text);
                    serialPort1.PortName = cmbPortName.Text;
                    
                    serialPort1.BaudRate = int.Parse(cmbBaudRate.Text);
                    serialPort1.DataBits = int.Parse(cmbDataBits.Text);
                    serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
                    serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
                    
                  
                  
                    //打开串口
                    serialPort1.Open();
                    serialPort2.Open();
                    btnOpenSerialPort.Text = "关闭串口";
                    lblState.ImageIndex =0;
                    bComOpen = true;

                    cmbPortName.Enabled = false;
                    cmbBaudRate.Enabled = false;
                    cmbDataBits.Enabled = false;
                    cmbStopBits.Enabled = false;
                    cmbParity.Enabled = false;

                    Delay(2000);
                    groupBox2.Text = "  ";
                    show("  准备开始配置!请确定仪器已经准备就绪");
               // for(int j=1;j<=5;j++)
                   // {多次重复测试
                    for (int i = 0; i < sid.Length; i++)
                    {
                        show("------------我是分割线----------");
                        show("  开始配置第  "+i.ToString()+"项    试剂编号  "  + sid[i] + "   重量   "  + sweight[i]);
                        dangqianzhongliang = get();
                        show( "   获取当前重量 !  "+ dangqianzhongliang.ToString()+"   " );
                        mubiao = sweight[i] + dangqianzhongliang;
                        show("   计算目标重量 !   "  + mubiao.ToString()+"  ");
                     //   show("   开始调用run(),参数为sid=   "  + sid[i].ToString() + "  sweight=   "  + sweight[i]);
                        run(sid[i].ToString(), sweight[i]);
                   }
                    show("--------------完成本次---------------");

                }
                //    show("全部完成");
                //}
                catch (System.IO.IOException) { } //可以进一步扩展
            }
            else
            {
                serialPort1.Close();
                serialPort2.Close();
                btnOpenSerialPort.Text="打开串口";
                lblState.ImageIndex =1;
                cmbPortName.Enabled = true ;
                cmbBaudRate.Enabled = true ;
                cmbDataBits.Enabled = true ;
                cmbStopBits.Enabled = true;
                cmbParity.Enabled = true ;
                bComOpen = false;

                //关闭串口时要做的处理
                tmrAutoSend.Enabled = false;
                chkAutoSend.Checked = false;
                chkSendHex.Checked = false;
        
            }
        }
      

        //用于检测发送数据区的数据格式的过程。
        private Boolean CheckGetSendData(String strSendData)
        {
           if (strSendData != "")
           {
               foreach (char chrTemp in strSendData)  //检测数据的合法性
                   {
                      if (chrTemp == 0x20)
                           continue;
                      else if (chrTemp >= 0x30 && chrTemp <= 0x39)
                           continue;
                      else if (chrTemp >= 0x41 && chrTemp <= 0x46)
                           continue;
                      else if (chrTemp >= 0x61 && chrTemp <= 0x66)
                            continue;
                      else
                            {
                             return (false);       
                             }

                   }
                   try
                   {
                       String[] strData = strSendData.Split(Convert.ToChar(0x20));
                        int index, intCount = strData.Length;
                        byte[] bytDataTemp = new byte[intCount];
                        for (index = 0; index < intCount; index++)  //16进制数据的字符串长度不能超过2
                        {
                            if (strData[index].Length > 2)
                            {
                            return(false ); 
                            }
                        }
                        for (index = 0; index < intCount; index++) 
                        {
                            bytDataTemp[index] = Convert.ToByte(strData[index], 16);//把字符串转化成对应的字节数组
                         }
                            bytSendData = bytDataTemp;
                            return (true);
                     }
                      catch (Exception ex)
                      {
                       Console.WriteLine(ex.Message);
                       return (false);
                       }
                       finally
                       {
                       }
              }
              return (false); 

         }
        private Boolean checkcendtime(string str)
        {
            if(str!="")
            {
            return true;
            }
            else 
                return false;
        }

        private void chkSendHex_CheckedChanged(object sender, EventArgs e)
        {
                if (chkSendHex.Checked == true)             
                    bSendHex = true;
                else
                    bSendHex = false;
        }




        //发送数据
        private void btnSend_Click(object sender, EventArgs e)
        {
            //if (bComOpen == true)
            //{
            //    if (bSendHex == false)
            //    {
            //        if (CheckGetSendData(txtSend.Text.Trim() ) == true )
            //        {
            //            byte[] data=bytSendData ;
            //            //以字节格式发送数据
            //            intSendDataCount += data.Length;
            //            serialPort2.Write(data, 0, data.Length);
            //            string s;
            //            s=timesend.Text.ToString();
            //            Delay(uint.Parse(s));
            //            MessageBox.Show(s);
            //            serialPort2.Write("00");
            //        }
            //        else
            //        {
            //            groupBox2.Text = "发送区   :发送数据有错!";
            //            if (chkAutoSend.Checked == true)  //当定时发送时,如果数据格式错误的话,就停止定时器
            //            {
            //                tmrAutoSend.Enabled = false;
            //                chkAutoSend.Checked = false;
            //            }
            //        }
            //    }
            //    else
            //    {
            //        //以文本格式发送数据
            //        //serialPort2.Write(txtSend.Text);
            //        //intSendDataCount += txtSend.Text.Length;
            //        //groupBox2.Text = "发送区   :发送数据成功!";
            //    }
            //}
        }




        //把收到的16进制数据转化成字符串
        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            return sb.ToString().ToUpper();
        }
        //串口接收数据事件
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            
            if (bReceiveHex == true)
            {
                DataReceivedEventHandler DataReceive = new DataReceivedEventHandler(this.HexDataReceive);
                DataReceive();
            }
            else
            {
                DataReceivedEventHandler DataReceive = new DataReceivedEventHandler(this.TextDataReceive);
                DataReceive();
            }
           
        }

        private void chkReceiveHex_CheckedChanged(object sender, EventArgs e)
        {
                //if (chkReceiveHex.Checked == true)
                //    bReceiveHex = true;
                //else
                //    bReceiveHex = false;
        }
        //以文本格式显示
        private void TextDataReceive()
        {
            String strReceiveData = serialPort1.ReadExisting();
            intReceiveDataCount += strReceiveData.Length;
                s += strReceiveData;
 
                if (strReceiveData == "g")
                {
                    
                    weight = s;
                    s = "";
                } 
            Log(strReceiveData);
        }

        //以16进制数据显示
        private void HexDataReceive()
        {
            // Obtain the number of bytes waiting in the port's buffer
            int bytes = serialPort1.BytesToRead; 

            // Create a byte array buffer to hold the incoming data
            byte[] buffer = new byte[bytes];

            intReceiveDataCount += bytes;

            // Read the data from the port and store it in our buffer
            serialPort1.Read(buffer,0, bytes);
                // Show the user the incoming data in hex format
                Log ( ByteArrayToHexString(buffer));
        }

        //在接收区显示数据
        private void Log(string msg )
        {
            //if (bStopShow == false)
            //{
            //    txtReceiveDataCount.Invoke(new EventHandler(delegate
            //    {
            //        txtReceive.AppendText ( msg.ToString());
            //        txtReceive.ScrollToCaret();
            //    }));
            //}
            //txtReceiveDataCount.Invoke(new EventHandler(delegate { txtReceiveDataCount.Text = intReceiveDataCount.ToString(); }));
            //txtSendDataCount.Invoke(new EventHandler(delegate { txtSendDataCount.Text = intSendDataCount.ToString(); }));
        }

        //清除接收区的文本
        private void btnReceiveClear_Click(object sender, EventArgs e)
        {
            rizhi.Text = "";
        }
        //清除发送区的文本
        private void btnSendClear_Click(object sender, EventArgs e)
        {
            //txtSend.Text = "";
        }

        //修改定时器的定时时间间隔
        private void txtTimeInterval_TextChanged(object sender, EventArgs e)
        {
            if (txtTimeInterval.Text != "")
            {
                try
                {
                    tmrAutoSend.Interval = int.Parse(txtTimeInterval.Text);
                }
                catch (OverflowException ex) { MessageBox.Show("  定时器的时间间隔溢出!", "错误提示!", MessageBoxButtons.OK, MessageBoxIcon.Warning); }

                finally
                {

                }
            }
            else
                txtTimeInterval.Text = "1000";
        }
        //开启定时器,定时发送数据
        private void chkAutoSend_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAutoSend.Checked == true)
                tmrAutoSend.Enabled = true;
            else
                tmrAutoSend.Enabled = false;
        }

        private void tmrAutoSend_Tick(object sender, EventArgs e)
        {
            this.btnSend_Click( sender, e) ; 
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            chkAutoSend.Checked = false;
            tmrAutoSend.Enabled = false;
        }

        private void btnCount_Click(object sender, EventArgs e)
        {
            intReceiveDataCount = 0;
            intSendDataCount = 0;
        }

        private void btnStopShow_Click(object sender, EventArgs e)
        {
            bStopShow = !bStopShow;
        }

        private void btnCRC_Click(object sender, EventArgs e)
        {
            //frmCRC frmCRC = new frmCRC();
            //frmCRC.ShowDialog();
            //frmCRC.Dispose();
        }

        private void button1_Click(object sender, EventArgs e)
        {
      
            MessageBox.Show(get().ToString());
        }

        private void txtReceive_TextChanged(object sender, EventArgs e)
        {
         
        }

        private void txtReceiveDataCount_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void cmbPortName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {

            //执行配置命令代码
            for (int i = 0; i < sweight.Length; i++)
            {
                dangqianzhongliang = get();
                mubiao = sweight[i]+dangqianzhongliang;
                run(sid[i].ToString(), sweight[i]);
            }



            测试速度代码
            //for (int i = 1; i <=3; i++)
            //{
            //    for (int j = 1; j <= 5; j++)
            //    {
            //        string a, b;
            //        a = j.ToString();
            //        b =i.ToString();
            //        test(a, b);
            //    }
            //}
            //MessageBox.Show(testjieguo);
            




        }

        private void txtSend_TextChanged(object sender, EventArgs e)
        {
        
        }

        private void timesend_TextChanged(object sender, EventArgs e)
        {
        
        }




        //发送命令
         private void send(string a,string b)
        {
                      string s = a + b;
                        if (bSendHex == false)
                        {
                            if (CheckGetSendData(s.Trim()) == true)
                            {
                                byte[] data = bytSendData;
                                //以字节格式发送数据
                                intSendDataCount += data.Length;
                                serialPort2.Write(data, 0, data.Length);

                            }
                            else
                            {
                                 show("  发送区   :发送数据有错!  ");
                                if (chkAutoSend.Checked == true)  //当定时发送时,如果数据格式错误的话,就停止定时器
                                {
                                    tmrAutoSend.Enabled = false;
                                    chkAutoSend.Checked = false;
                                }
                            }
                        }
                //else
                //{
                //    //以文本格式发送数据
                //    //serialPort2.Write(txtSend.Text);
                //    //intSendDataCount += txtSend.Text.Length;
                //    //groupBox2.Text = "发送区   :发送数据成功!";
                //}
            
        }

         private void txtSend_TextChanged_1(object sender, EventArgs e)
         {

         }
         public void  test(string s,string p)
         {
            
             
             uint t=1000;
             for(t=1000;t<6000;t+=1000)
             { 
                 double a = get();
                 send(s, p);
                 Delay(t);
                 send("0","0");
                 Delay(delaytime);
                 double b = get();
                 double c = (b - a )/ t;
                 c *= 1000;
                 testjieguo += c.ToString();
                 testjieguo += "   ";
             }
         }
  public void run(string  port, double ww)
  {  
      double t1=get();
      int t=int.Parse(port);
       double  w=mubiao-t1;//完成本端口目标 剩余需要配置的重量
    
   //   MessageBox.Show("speed[1]="+speed[1].ToString()+"speed[2]="+speed[2].ToString()+"speed[3]="+speed[3].ToString()+w.ToString());
   if(w>0)
   {
      if(w>=xishu*speed[4,t]){tim=w/speed[4,t];speeds="4";}
    else  if(w>=xishu*speed[3,t]){tim= w/speed[2,t];speeds="3";}
    else if (w > 0) { tim = w / speed[2, t]; speeds = "2"; }
    else { tim = 0; speeds = "0"; }
      int p=int.Parse(speeds);
    //if(w<xishu *speed[1]){tim=w/speed[1];speeds="1";}
    tim *= 1000;
   // show("蠕动泵即将开始运转参数为port="+port+"   speeds=   "+speeds+"   时间  "+tim.ToString() +"ms    内置速度为  "+speed[p,t]+"    "+"t="+t.ToString()+"p="+p.ToString() );
     send(port ,speeds);
     Delay((uint)tim);
     send("0", "0");
   //  show("等待天平稳定    ");
     Delay(delaytime);
     //MessageBox.Show(s);
    //再等待1s后天平稳定后开始读数
    double  temp=get();
    double shiji = (temp - t1) / tim;
    shiji *= 1000;
      show("本次测得port="+port+"   speeds=   "+speeds+"的  实际速度为  "+shiji.ToString()+"    ");
      show("读取当前重量为"+temp.ToString()+"    ");
   // speed[int.Parse(speeds)] = (t-t1) / tim;
   // MessageBox.Show("speed值更改为");

    if (temp > mubiao + wucha) { show("!!!!!!!本次配置重量已经超过预期值请重新调整参数!!!!!!!!!"); }
    else if(temp<mubiao-wucha)
    {
       // MessageBox.Show("");
        run(port, ww);
      // show( "再次调用run()参数为sid="+port+"sweight="+ww+"   ");
       
    }
    else {show("*******************本次成功完成*******************"); }
    }
    
      }

  private void rizhi_TextChanged(object sender, EventArgs e)
  {

  }


  private void show(string message)
  {
      rizhi.AppendText(message);
      //DateTime.Now.ToString() 
      rizhi.Text += Environment.NewLine;
      rizhi.ScrollToCaret();
  }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值