电子称串口编程

        private const int BaudRate = 600; // 电子称波特率
        private SerialPort sp = null;
        private const string PortName = "COM1";//端口号
        private delegate void UpdateTextEventHandler(string data);//定义委托
        private event UpdateTextEventHandler textChanged;//定义事件

     private void initPort()
        {
            sp = new SerialPort();
            try
            {
                sp.PortName = PortName;//端口号
                sp.BaudRate = BaudRate; //波特率
                sp.DataBits = 8;//数据位 8位
                sp.Parity = Parity.None;//无奇偶校验位 
                sp.DtrEnable = true;
                sp.RtsEnable = true;
                sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
                textChanged += new UpdateTextEventHandler(SerialPortTest_textChanged);
                if (!sp.IsOpen)
                {
                    sp.Open();
                }
            }
            catch (Exception ex)
            {
                FunctionsUI.CreateErrorDialog(ex);
            }
        }


        /// <summary>
        /// 发送数据请求命令
        /// </summary>
        private void sendDataRequest()
        {
            byte[] arrByte = new byte[2];
            //发送命令 1BH+70H  与电子称通讯,读取电子称数据,16进制
            arrByte[0] = Convert.ToByte(0x1B);
            arrByte[1] = 0x70;
            sp.Write(arrByte, 0, 2);
            byte[] buffer = new byte[sp.BytesToRead];
        }

      //返回数据,对数据进行处理
        void SerialPortTest_textChanged(string data)
        {
       //TODO
        }


        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                System.Threading.Thread.Sleep(500);//如果时间短了可能读取数据不完整
                byte[] buffer = new byte[sp.BytesToRead];
                sp.Read(buffer, 0, buffer.Length);
                string data = System.Text.Encoding.ASCII.GetString(buffer);
                txtWight.Invoke(textChanged, new string[] { data }); //通过Invoke调用事件
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        /// <summary>
        /// 关闭串口
        /// </summary>
        public void DisposeProt()
        {
            if (sp != null && sp.IsOpen)
            {
                sp.Close();
            }
        }
</pre><pre name="code" class="csharp">
电子称串口编程_第1张图片

你可能感兴趣的:(串口,电子称)