首页 > 编程语言 >C# 读取Victor86E的显示数值

C# 读取Victor86E的显示数值

时间:2023-01-05 15:12:11浏览次数:30  
标签:Victor86E 读取 SerialPortInstance C# LogMsg OnUpdateProgressEvent PortName public 

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();
        }
    }

 

标签:Victor86E,读取,SerialPortInstance,C#,LogMsg,OnUpdateProgressEvent,PortName,public,
From: https://www.cnblogs.com/BlueSky2023/p/17027608.html

相关文章

  • DevEco Device Tool 搭建Windows环境+vscode markdown入门
    DevEcoDeviceTool搭建Windows环境+vscodemarkdown入门系统要求Windows10/1164位系统Windows系统安装的DecEcoDeviceTool3.1Beta2版本搭建Windows环境......
  • Centos7搭建Gitlab服务器
    GitLab介绍GitLab是一个用于仓库管理系统的开源项目,使用Git作为代码管理工具,并在此基础上搭建起来的Web服务。官方网站:https://about.gitlab.com/安装配置需求:2.5GB的......
  • Q420qC力学性能、Q420qC期货订轧、Q420qC钢板介绍
    1、Q420qC钢板用途:Q420qC桥梁板是制造桥梁结构件专用的厚钢板,使用专用钢种桥梁建筑用碳素钢和低合金钢制造。用于架造铁路、公路桥梁、建筑及桥梁、跨海大桥用钢板。 2、Q4......
  • [华为SDK]Could not resolve com.huawei.agconnect:agcp:1.6.x.300解决方法
    接入huaweiSDK过程中出现的问题,解决时需要关注项目根路径下的gradle脚本文件这三个地方:首先,华为的maven源需要放置在最前边其次,根gradle依赖项中也需要加入相关依赖最后,记得......
  • H3C-IRF(堆叠)配置
    (1)配置DeviceA将用作IRF物理端口的FortyGigE1/0/53~FortyGigE1/0/54的手工关闭。<DeviceA>system-view[DeviceA]interfacerangefortygige1/0/53tofortygig......
  • 重磅直播|PatchmatchNet:一种高效的Multi-view Stereo框架(CVPR2021)
    本期由苏黎世联邦理工学院ComputerVisionandGeometryGroup王方锦华博士分享,分享的主题为《PatchmatchNet:基于传统PatchMatch算法的高效Multi-viewStereo框架》,主讲人会......
  • Linux - 配置远程开发Linux C/C++程序环境
    1.使用VS2019远程开发LinuxC/C++程序所谓工欲善其事必先利其器,开发一个项目之前,我们要选择好合适的开发工具以及开发环境。1.1LinuxC/C++程序常见的开发方式在Lin......
  • Spring bean注入问题:NoUniqueBeanDefinitionException解决方案归纳
    引言   spring实现的bean自动注入在项目开发中是一个经常使用到的功能,但自动装配两个或多个bean时,会抛出NoUniqueBeanDefinitionException:Noqualifyingbeanoftyp......
  • Mapper that could not be found
    现象1mapper资源扫不到resources建的是目录,不是package所以如果直接a.b的方式创建,会扫描不到mapper.xml文件现象2缺少配置文件HisDruidConfigSpringBoo......
  • NFS协议分析 - rfc1813
    IntroductionNFS协议实现基于RPC(RemoteProcedureCall)和XDR(eXternalDataRepresentation)XDR:astandardwayofrepresentingasetofdatatypesonanetwork该文档......