C# 读取Victor86E的显示数值

1.准备工作:安装对应驱动程序,安装自带软件(方便测试验证),将万用表连接到电脑,注意要长按万用表上RS232键。

2.将以下代码拷贝,可以直接使用(这里只验证了电流读取的数值准确性,其他单位需要根据实际情况验证下小数点位置)。其中,OnUpdateProgressEvent为日志记录事件。

3.如有需要找到对应通信协议,确认波特率及数据解析方式

 需要特别注意:确认波特率是第一步,因为同一型号不同批次的万用表,波特率可能会不同,通信协议中的波特率可能与你硬件也不一致,不同波特率读取出的数据无法正确解析。

 public class Victor86E
    {     
        public delegate void UpdateProgresEventsHandler(string uiInfo, string logInfo, MessageType.MsgType msgType);
        public static event UpdateProgresEventsHandler OnUpdateProgressEvent;

        private SerialPort SerialPortInstance;
        private string PortName;
        private string LogMsg;

        public bool isConnect;
        public Victor86E(string name)
        { 
            PortName = name;
            Initilize();
        }

        private void Initilize()
        {
             SerialPortInstance = new SerialPort();          
            //if (SerialPortInstance.IsOpen)
            //{
            //    ReleasePort();
            //    //// Wait a while, for that the port may not be closed immediately.
            //    //Thread.CurrentThread.Join(Interval);
            //}
            ReleasePort();
            #region Initialize the port

            SerialPortInstance.Encoding = Encoding.ASCII;
            SerialPortInstance.NewLine = "\n";
            SerialPortInstance.RtsEnable = true;
            SerialPortInstance.DtrEnable = true;

            // Set the port name with the specified name.
            SerialPortInstance.PortName = PortName;
            SerialPortInstance.ReadTimeout = 1000;
            // Set the baud rate with the specified name.
            SerialPortInstance.BaudRate = 9600;

            // Set the parity with  the specified value.
            SerialPortInstance.Parity = Parity.None;

            // Set the data bits with the specified value.
            SerialPortInstance.DataBits = 8;

            // Set the stop bits with the specified value
            SerialPortInstance.StopBits = StopBits.One;
            SerialPortInstance.ReceivedBytesThreshold = 14;

            #endregion

            try
            {
                // Open the port for use.
                SerialPortInstance.Open();
                SerialPortInstance.DiscardInBuffer();
                SerialPortInstance.DiscardOutBuffer();

                LogMsg = string.Format("SerialDevice Opened {0}", PortName);
                OnUpdateProgressEvent(LogMsg, LogMsg, MessageType.MsgType.Info);

                isConnect= true;
            }
            catch (Exception ex)
            {
                LogMsg = string.Format("SerialDevice_Failed_Open:{0}", PortName) + "SerialDevice_More_Details_Colon:" + ex.Message;
                OnUpdateProgressEvent(LogMsg, LogMsg, MessageType.MsgType.Warning);
                isConnect= false;
            }
        }

        public void ReleasePort()
        {
            if (ReferenceEquals(null, SerialPortInstance))
            {
                return;
            }

            try
            {
                // If the state is OPEN, then close it.
                if (SerialPortInstance.IsOpen)
                {
                    SerialPortInstance.Close();
                    LogMsg = PortName + "SerialDevice_Is_Closed";
                    OnUpdateProgressEvent(LogMsg, LogMsg, MessageType.MsgType.Info);
                }
            }
            catch (Exception ex)
            {
                LogMsg = string.Format("SerialDevice_Failed_Close_Port_Para:{0}", PortName) + "SerialDevice_More_Details_Colon" + ex.Message;
                OnUpdateProgressEvent(LogMsg, LogMsg, MessageType.MsgType.Warning);
            }
        }
        public double Read()
        {
            string format = "";
            double v = 0.0;
            var str = "";
            try
            {
                if (!SerialPortInstance.IsOpen)
                {
                    Initilize();
                    Thread.Sleep(100);
                }
                if (!isConnect)
                {
                    LogMsg = PortName + "未连接。";
                    OnUpdateProgressEvent(LogMsg, LogMsg, MessageType.MsgType.Error);
                    return 0.0;
                }
                int n = SerialPortInstance.BytesToRead;
                var buf = new byte[n];
                SerialPortInstance.Read(buf, 0, n);
                var idx = buf.ToList().FindLastIndex(m => m == 0x0A);
                if (idx<14)
                {
                    //var hex1 = ByteArrayToHexString(buf).Split(' ');
                    //for (int i = 0; i < hex1.Count(); i++)
                    //{
                    //    str += hex1[i];
                    //}
                    LogMsg = PortName + "未读到电流";
                    OnUpdateProgressEvent(LogMsg, LogMsg, MessageType.MsgType.Warning);
                    return 0.0;
                }
                var data = buf.ToList().GetRange(idx - 13, 14).ToArray();
                var hexStr = ByteArrayToHexString(data);
                string[] hex;

                //去除空格
                hexStr = hexStr.Replace(" ", "");
                //hex = hexStr.Split(' ');
                //var positiveStr = hex[0].Substring(1, 1);
                //var formatStr = hex[6].Substring(1, 1);
                //value = hex[1].Substring(1, 1) + hex[2].Substring(1, 1) + hex[3].Substring(1, 1) + hex[4].Substring(1, 1) + hex[5].Substring(1, 1);

                var positiveStr = hexStr.Substring(1, 1);
                var formatStr = hexStr.Substring(13, 1);
                var value = hexStr.Substring(3, 1) + hexStr.Substring(5, 1) + hexStr.Substring(7, 1) + hexStr.Substring(9, 1) + hexStr.Substring(11, 1);
                var v1 = int.Parse(value);
                LogMsg = PortName + "电流读数:" + ByteArrayToHexString(data) + "数值:" + value;
                OnUpdateProgressEvent(LogMsg, LogMsg, MessageType.MsgType.Info);
                switch (int.Parse(formatStr))
                {
                    case 0:
                        v = v1 * 1.0 / 10;
                        break;
                    case 1:
                        v = v1 * 1.0 / 100;
                        break;
                    case 2:
                        v = v1 * 1.0 / 1000;
                        break;
                    case 3:
                        v = v1 * 1.0 / 10000;
                        break;
                    case 4:
                        v = v1 * 1.0 / 100000;
                        break;
                    case 5:
                        v = v1 * 10.0;
                        break;
                    case 6:
                        v = v1 * 100.0;
                        break;
                    case 7:
                        v = v1 * 1000.0;
                        break;
                }
                if (positiveStr.Contains("D"))
                {
                    v = -v;
                }
            }
            catch (Exception ex)
            {
                LogMsg = PortName + "读取数据错误:"+ex.Message;
                OnUpdateProgressEvent(LogMsg, LogMsg, MessageType.MsgType.Error);
            }
            return v;
        }
      
        private string ByteArrayToHexString(byte[] decode)
        {
            var strBuilder = new StringBuilder(decode.Length * 3);
            foreach (byte b in decode)
            {
                strBuilder.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            }
            return strBuilder.ToString().ToUpper();
        }
    }

 

posted @ 2023-01-05 15:02  天若晴2023  阅读(195)  评论(0)    收藏  举报