C# 使用NModbus跟信捷PLC串口通信

使用的库是NModbus4.dll。

一、新建winform窗体程序,在Load事件中加载串口,代码如下:

private void FrmMain_Load(object sender, EventArgs e)
{
    DeviceConnect();

    //PLC数据监控
    Thread plc_Thread = new Thread(ListenModusIO);
    plc_Thread.IsBackground = true;
    plc_Thread.Start();
}

void DeviceConnect()
{
            #region //PLC连接
            string strRes = ConnectSerialPort(PLC_PortName1, PLC_BaudRate1, PLC_DataBit1, PLC_StopBit1, PLC_Parity1, ref PLC_Port1);
            if (strRes == "Y")
            {
                //创建ModbusRTU主站实例
                if (SerialType == "ASCII")
                {
                    master = ModbusSerialMaster.CreateAscii(PLC_Port1);
                }
                else
                {
                    master = ModbusSerialMaster.CreateRtu(PLC_Port1);
                }

                master.Transport.ReadTimeout = 1000;//读超时
                master.Transport.WriteTimeout = 1000;//写超时
                master.Transport.Retries = 3;//尝试重复连接次数
                master.Transport.WaitToRetryMilliseconds = 200;//尝试重复连接间隔

                str_DeviceInfo.Add("[PLC设备] 连接成功");
            }
            else
            {
                str_DeviceInfo.Add("[PLC设备] 连接失败,原因:" + strRes);
            }
            #endregion
}

string ConnectSerialPort(string portName, int baudRate, int dataBits, float stopBit, 
                         string parity, ref SerialPort sp)
{
            try
            {
                sp = new SerialPort();
                sp.PortName = portName;
                sp.BaudRate = baudRate;
                sp.DataBits = dataBits;

                if (stopBit == 1)
                {
                    sp.StopBits = StopBits.One;
                }
                else if (stopBit == 1.5)
                {
                    sp.StopBits = StopBits.OnePointFive;
                }
                else if (stopBit == 2)
                {
                    sp.StopBits = StopBits.Two;
                }
                else
                {
                    sp.StopBits = StopBits.One;
                }

                if (parity.CompareTo("None") == 0)
                {
                    sp.Parity = Parity.None;
                }
                else if (parity.CompareTo("Odd") == 0)
                {
                    sp.Parity = Parity.Odd;
                }
                else if (parity.CompareTo("Even") == 0)
                {
                    sp.Parity = Parity.Even;
                }
                else
                {
                    sp.Parity = Parity.None;
                }

                sp.ReadTimeout = -1;     //  设置超时读取时间
                sp.RtsEnable = true;
                sp.ReceivedBytesThreshold = 1;

                if (!sp.IsOpen)
                {
                    sp.Open();
                }

                return "Y";
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                return ex.Message;
            }
}

二、PLC数据监控,通过创建线程获取PLC寄存器中的值,代码如下:

void ListenModusIO()
{
            Stopwatch sw = new Stopwatch();
            while (true)
            {
                try
                {
                    if (master != null)
                    {
                        sw.Restart();

                        #region 获取HD100值
                        //获取PLC的HD100(地址41188)开始的100个字节数据
                        Ds = master.ReadHoldingRegisters(1, 41188, 100);
                        //Thread.Sleep(20);
                        if (Ds != null && Ds.Length == 100)
                        {
                            #region 列表赋值
                            if (lstPLCSigns != null && lstPLCSigns.Count >= 100)
                            {
                                for (int i = 0; i < Ds.Length; i++)
                                {
                                    lstPLCSigns[i].Value = Ds[i];
                                }
                            }
                            #endregion

                        }

                        sw.Stop();
                        TimeSpan ts = sw.Elapsed;
                        plc_RunTime = ts.TotalMilliseconds;

                    }
                    else
                    {
                        Thread.Sleep(20);
                    }
                }
                catch (Exception ex)
                {
                    ShowRunInfo("PLC异常错误:" + ex.Message);
                    PLCerror++;
                    if (PLCerror > 50000)
                    {
                        PLCerror = 0;
                        break;
                    }                    
                }
            }
}

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值