C#使用Windows窗体应用 NModbus4实现RTU主站

设计器生成的代码

namespace WaterAnalysis
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.Lamp1 = new System.Windows.Forms.Button();
            this.label5 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.cbxStopBits = new System.Windows.Forms.ComboBox();
            this.cbxParity = new System.Windows.Forms.ComboBox();
            this.cbxDataBits = new System.Windows.Forms.ComboBox();
            this.cbxBaudRate = new System.Windows.Forms.ComboBox();
            this.cbxPort = new System.Windows.Forms.ComboBox();
            this.btConnect = new System.Windows.Forms.Button();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.btMessageClear = new System.Windows.Forms.Button();
            this.tbMessage = new System.Windows.Forms.TextBox();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.rbxRWMsg = new System.Windows.Forms.TextBox();
            this.btnRW = new System.Windows.Forms.Button();
            this.label9 = new System.Windows.Forms.Label();
            this.label8 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.nudLength = new System.Windows.Forms.NumericUpDown();
            this.nudStartAdr = new System.Windows.Forms.NumericUpDown();
            this.nudSlaveID = new System.Windows.Forms.NumericUpDown();
            this.label6 = new System.Windows.Forms.Label();
            this.cbxMode = new System.Windows.Forms.ComboBox();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nudLength)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.nudStartAdr)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.nudSlaveID)).BeginInit();
            this.SuspendLayout();
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.Lamp1);
            this.groupBox1.Controls.Add(this.label5);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Controls.Add(this.cbxStopBits);
            this.groupBox1.Controls.Add(this.cbxParity);
            this.groupBox1.Controls.Add(this.cbxDataBits);
            this.groupBox1.Controls.Add(this.cbxBaudRate);
            this.groupBox1.Controls.Add(this.cbxPort);
            this.groupBox1.Controls.Add(this.btConnect);
            this.groupBox1.Location = new System.Drawing.Point(23, 12);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(232, 241);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "串口状态";
            // 
            // Lamp1
            // 
            this.Lamp1.Location = new System.Drawing.Point(134, 19);
            this.Lamp1.Name = "Lamp1";
            this.Lamp1.Size = new System.Drawing.Size(27, 25);
            this.Lamp1.TabIndex = 11;
            this.Lamp1.UseVisualStyleBackColor = true;
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(4, 209);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(53, 12);
            this.label5.TabIndex = 10;
            this.label5.Text = "停止位:";
            // 
            // label4
            // 
           this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(4, 172);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(53, 12);
            this.label4.TabIndex = 9;
            this.label4.Text = "校验位:";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(4, 135);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(53, 12);
            this.label3.TabIndex = 8;
            this.label3.Text = "数据位:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(6, 98);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(53, 12);
            this.label2.TabIndex = 7;
            this.label2.Text = "波特率:";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(6, 61);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(53, 12);
            this.label1.TabIndex = 6;
            this.label1.Text = "串口号:";
            // 
            // cbxStopBits
            // 
            this.cbxStopBits.FormattingEnabled = true;
            this.cbxStopBits.Items.AddRange(new object[] {
            "One",
            "Two"});
            this.cbxStopBits.Location = new System.Drawing.Point(80, 206);
            this.cbxStopBits.Name = "cbxStopBits";
            this.cbxStopBits.Size = new System.Drawing.Size(121, 20);
            this.cbxStopBits.TabIndex = 5;
            // 
            // cbxParity
            // 
            this.cbxParity.FormattingEnabled = true;
            this.cbxParity.Items.AddRange(new object[] {
            "Odd",
            "Even",
            "None"});
            this.cbxParity.Location = new System.Drawing.Point(80, 169);
            this.cbxParity.Name = "cbxParity";
            this.cbxParity.Size = new System.Drawing.Size(121, 20);
            this.cbxParity.TabIndex = 4;
            // 
            // cbxDataBits
            // 
            this.cbxDataBits.FormattingEnabled = true;
            this.cbxDataBits.Items.AddRange(new object[] {
            "8"});
            this.cbxDataBits.Location = new System.Drawing.Point(80, 132);
            this.cbxDataBits.Name = "cbxDataBits";
            this.cbxDataBits.Size = new System.Drawing.Size(121, 20);
            this.cbxDataBits.TabIndex = 3;
            // 
            // cbxBaudRate
            // 
            this.cbxBaudRate.FormattingEnabled = true;
            this.cbxBaudRate.Items.AddRange(new object[] {
            "9600"});
            this.cbxBaudRate.Location = new System.Drawing.Point(80, 95);
            this.cbxBaudRate.Name = "cbxBaudRate";
            this.cbxBaudRate.Size = new System.Drawing.Size(121, 20);
            this.cbxBaudRate.TabIndex = 2;
            // 
            // cbxPort
            // 
            this.cbxPort.FormattingEnabled = true;
            this.cbxPort.Items.AddRange(new object[] {
            "com1",
            "com2"});
            this.cbxPort.Location = new System.Drawing.Point(80, 58);
            this.cbxPort.Name = "cbxPort";
            this.cbxPort.Size = new System.Drawing.Size(121, 20);
            this.cbxPort.TabIndex = 1;
            // 
            // btConnect
            // 
            this.btConnect.Location = new System.Drawing.Point(6, 20);
            this.btConnect.Name = "btConnect";
            this.btConnect.Size = new System.Drawing.Size(75, 23);
            this.btConnect.TabIndex = 0;
            this.btConnect.Text = "启动连接";
            this.btConnect.UseVisualStyleBackColor = true;
            this.btConnect.Click += new System.EventHandler(this.btConnect_Click);
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.btMessageClear);
            this.groupBox2.Controls.Add(this.tbMessage);
            this.groupBox2.Location = new System.Drawing.Point(23, 259);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(765, 189);
            this.groupBox2.TabIndex = 1;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "通讯信息";
            // 
            // btMessageClear
            // 
            this.btMessageClear.Location = new System.Drawing.Point(8, 19);
            this.btMessageClear.Name = "btMessageClear";
            this.btMessageClear.Size = new System.Drawing.Size(75, 23);
            this.btMessageClear.TabIndex = 1;
            this.btMessageClear.Text = "清空";
            this.btMessageClear.UseVisualStyleBackColor = true;
            this.btMessageClear.Click += new System.EventHandler(this.btMessageClear_Click);
            // 
            // tbMessage
            // 
            this.tbMessage.Location = new System.Drawing.Point(6, 48);
            this.tbMessage.Multiline = true;
            this.tbMessage.Name = "tbMessage";
            this.tbMessage.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.tbMessage.Size = new System.Drawing.Size(714, 125);
            this.tbMessage.TabIndex = 0;
            // 
            // timer1
            // 
            this.timer1.Interval = 1000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // groupBox3
            // 
            this.groupBox3.Controls.Add(this.rbxRWMsg);
            this.groupBox3.Controls.Add(this.btnRW);
            this.groupBox3.Controls.Add(this.label9);
            this.groupBox3.Controls.Add(this.label8);
            this.groupBox3.Controls.Add(this.label7);
            this.groupBox3.Controls.Add(this.nudLength);
            this.groupBox3.Controls.Add(this.nudStartAdr);
            this.groupBox3.Controls.Add(this.nudSlaveID);
            this.groupBox3.Controls.Add(this.label6);
            this.groupBox3.Controls.Add(this.cbxMode);
            this.groupBox3.Location = new System.Drawing.Point(261, 12);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(527, 241);
            this.groupBox3.TabIndex = 2;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "读写";
            // 
            // rbxRWMsg
            // 
            this.rbxRWMsg.Location = new System.Drawing.Point(198, 58);
            this.rbxRWMsg.Multiline = true;
            this.rbxRWMsg.Name = "rbxRWMsg";
            this.rbxRWMsg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.rbxRWMsg.Size = new System.Drawing.Size(284, 169);
            this.rbxRWMsg.TabIndex = 15;
            this.rbxRWMsg.TextChanged += new System.EventHandler(this.rbxRWMsg_TextChanged);
            // 
            // btnRW
            // 
            this.btnRW.Location = new System.Drawing.Point(8, 204);
            this.btnRW.Name = "btnRW";
            this.btnRW.Size = new System.Drawing.Size(75, 23);
            this.btnRW.TabIndex = 14;
            this.btnRW.Text = "读写";
            this.btnRW.UseVisualStyleBackColor = true;
            this.btnRW.Click += new System.EventHandler(this.btnRW_Click);
            // 
            // label9
            // 
            this.label9.AutoSize = true;
            this.label9.Location = new System.Drawing.Point(6, 172);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(65, 12);
            this.label9.TabIndex = 13;
            this.label9.Text = "地址长度:";
            // 
            // label8
            // 
            this.label8.AutoSize = true;
            this.label8.Location = new System.Drawing.Point(6, 135);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(65, 12);
            this.label8.TabIndex = 12;
            this.label8.Text = "起始地址:";
            // 
            // label7
            // 
            this.label7.AutoSize = true;
            this.label7.Location = new System.Drawing.Point(6, 98);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(65, 12);
            this.label7.TabIndex = 11;
            this.label7.Text = "从站地址:";
            // 
            // nudLength
            // 
            this.nudLength.Location = new System.Drawing.Point(71, 170);
            this.nudLength.Name = "nudLength";
            this.nudLength.Size = new System.Drawing.Size(120, 21);
            this.nudLength.TabIndex = 10;
            // 
            // nudStartAdr
            // 
            this.nudStartAdr.Location = new System.Drawing.Point(71, 133);
            this.nudStartAdr.Name = "nudStartAdr";
            this.nudStartAdr.Size = new System.Drawing.Size(120, 21);
            this.nudStartAdr.TabIndex = 9;
            // 
            // nudSlaveID
            // 
            this.nudSlaveID.Location = new System.Drawing.Point(71, 96);
            this.nudSlaveID.Name = "nudSlaveID";
            this.nudSlaveID.Size = new System.Drawing.Size(120, 21);
            this.nudSlaveID.TabIndex = 8;
            // 
            // label6
            // 
           this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(6, 61);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(65, 12);
            this.label6.TabIndex = 7;
            this.label6.Text = "读写模式:";
            // 
            // cbxMode
            // 
            this.cbxMode.FormattingEnabled = true;
            this.cbxMode.Items.AddRange(new object[] {
            "读取输出线圈",
            "读取离散输入",
            "读取保持型寄存器",
            "读取输入寄存器",
            "写入单个线圈",
            "写入多个线圈",
            "写入单个寄存器",
            "写入多个寄存器"});
            this.cbxMode.Location = new System.Drawing.Point(71, 58);
            this.cbxMode.Name = "cbxMode";
            this.cbxMode.Size = new System.Drawing.Size(121, 20);
            this.cbxMode.TabIndex = 0;
            this.cbxMode.SelectedIndexChanged += new System.EventHandler(this.cbxMode_SelectedIndexChanged);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 482);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            this.Load += new System.EventHandler(this.Form1_Load);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nudLength)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.nudStartAdr)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.nudSlaveID)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Button Lamp1;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.ComboBox cbxStopBits;
        private System.Windows.Forms.ComboBox cbxParity;
        private System.Windows.Forms.ComboBox cbxDataBits;
        private System.Windows.Forms.ComboBox cbxBaudRate;
        private System.Windows.Forms.ComboBox cbxPort;
        private System.Windows.Forms.Button btConnect;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.TextBox tbMessage;
        private System.Windows.Forms.Button btMessageClear;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.Button btnRW;
        private System.Windows.Forms.Label label9;
        private System.Windows.Forms.Label label8;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.NumericUpDown nudLength;
        private System.Windows.Forms.NumericUpDown nudStartAdr;
        private System.Windows.Forms.NumericUpDown nudSlaveID;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.ComboBox cbxMode;
        private System.Windows.Forms.TextBox rbxRWMsg;
    }
}

后台代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Modbus.Device;
using System.Net.Sockets;
using System.Threading;
using System.IO.Ports;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Text.RegularExpressions;

namespace WaterAnalysis
{
    public partial class Form1 : Form
    {
        #region 定义全局变量
        //端口序号
        private int m_comBoxNums = 0;
        //串口实例
        private SerialPort serialPort = new SerialPort();
        //ModbusRTU主站字段
        private static IModbusMaster master;
 
        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //窗口开启定时器默认打开
            timer1.Enabled = true;
            //设置默认选中项
            cbxBaudRate.SelectedIndex = 0;
            cbxDataBits.SelectedIndex = 0;
            cbxParity.SelectedIndex = 2;
            cbxStopBits.SelectedIndex = 0;
            //通讯信息文本框清空
            tbMessage.Text = "";

            //设置读写窗口默认选中项
            cbxMode.SelectedIndex = 0;
            nudSlaveID.Minimum = 1;
            nudStartAdr.Minimum = 0;
            nudLength.Minimum = 1;
            //设置为默认输入法,即为英文半角
            rbxRWMsg.ImeMode = ImeMode.Disable;
        }
        
        private void timer1_Tick(object sender, EventArgs e)
        {
            //定时刷新串口,获取端口号,指示灯闪烁
            string Cur_PortName = cbxPort.Text;

            try
            {
                string[] strName = null;
                strName = SerialPort.GetPortNames();

                if (m_comBoxNums != strName.Length)
                {
                    m_comBoxNums = strName.Length;

                    cbxPort.Items.Clear();
                    cbxPort.Text = null;

                    for (int i = 0; i < m_comBoxNums; i++)//判断串口刷新后状态
                    {
                        if (strName[i] == Cur_PortName) { cbxPort.Text = Cur_PortName; }
                        cbxPort.Items.Add(strName[i]);
                    }
                    cbxPort.Text = strName[0];
                    serialPort.PortName = cbxPort.Text;
                }
            }

            catch (Exception ex)
            {
                if (ex.Source != null)
                {
                }
            }

            if (Lamp1.BackColor == Color.Red)
            {
                Lamp1.BackColor = Color.Green;
            }
            else
            {
                Lamp1.BackColor = Color.Red;
            }
        }

        /// <summary>
        /// 获取窗体选中的奇偶校验
        /// </summary>
        /// <returns></returns>
        private Parity GetSelectedParity()
        {
            switch (cbxParity.SelectedItem.ToString())
            {
                case "Odd":
                    return Parity.Odd;
                case "Even":
                    return Parity.Even;
                case "None":
                    return Parity.None;
                default:
                    return Parity.None;
            }
        }

        /// <summary>
        /// 获取窗体选中的停止位
        /// </summary>
        /// <returns></returns>
        private StopBits GetSelectedStopBits()
        {
            switch (cbxStopBits.SelectedItem.ToString())
            {
                case "One":
                    return StopBits.One;
                case "Two":
                    return StopBits.Two;
                default:
                    return StopBits.One;
            }
        }

        void ShowMesage(string Mes)//通讯显示函数
        {

            string ch = "\r\n";
            Mes += ch;
            tbMessage.AppendText(Mes);
        }

       
private void btConnect_Click(object sender, EventArgs e)
        {
            //启动连接
            if (serialPort.IsOpen)
            {
                timer1.Enabled = true;
                serialPort.Close();
                btConnect.Text = "启动连接";
                ShowMesage(serialPort.PortName.ToString() + ","+ serialPort.BaudRate.ToString() + ","+ serialPort.DataBits.ToString() + ","
                    + serialPort.Parity.ToString() + ","+ serialPort.StopBits.ToString() + ","+ "通信已断开");
            }
            else
            {
                try
                {
                    timer1.Enabled = false;
                    //创建Rtu主站
                    serialPort.PortName = cbxPort.SelectedItem.ToString();//"COM11"; 
                    serialPort.BaudRate = Convert.ToInt32(cbxBaudRate.SelectedItem);
                    serialPort.DataBits = Convert.ToInt32(cbxDataBits.SelectedItem);
                    serialPort.Parity = GetSelectedParity();
                    serialPort.StopBits = GetSelectedStopBits();
                    serialPort.Open();
                    //创建ModbusRTU主站实例
                    master = ModbusSerialMaster.CreateRtu(serialPort);
                    master.Transport.Retries = 0;
                    master.Transport.ReadTimeout = 300;

                    Lamp1.BackColor = Color.Green;
                }
                catch(Exception ex)
                {
                    btConnect.Text = "启动连接";
                    ShowMesage(serialPort.PortName.ToString() + ","+ serialPort.BaudRate.ToString() + ","+ serialPort.DataBits.ToString() + ","
                    + serialPort.Parity.ToString() + ","+ serialPort.StopBits.ToString() + ","+ "通信未建立,原因:" + ex.Message);
                    return;
                }

                btConnect.Text = "断开连接";
                ShowMesage(serialPort.PortName.ToString() + ","+ serialPort.BaudRate.ToString() + ","+ serialPort.DataBits.ToString() + ","
                + serialPort.Parity.ToString() + ","+ serialPort.StopBits.ToString() + ","+ "通信已建立");
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (serialPort.PortName != null)
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {
                if (ex.Source != null)
                {

                }
            }
        }

        private void btMessageClear_Click(object sender, EventArgs e)
        {
            tbMessage.Text = "";
        }
        private void SetMsg<T>(List<T> result)//界面显示读取结果
        {
            string msg = string.Empty;

            result.ForEach(m => msg += $"{m} ");

            rbxRWMsg.Text = msg.Trim();
        }

        private void rbxRWMsg_TextChanged(object sender, EventArgs e)//更新写入值计数
        {
            nudLength.Value = Regex.Matches(rbxRWMsg.Text, ",").Count + 1;
        }

        private void cbxMode_SelectedIndexChanged(object sender, EventArgs e)// 模式切换事件
        {
            tbMessage.Clear();
            if (cbxMode.SelectedItem.ToString().Contains("读取"))
            {
                btnRW.Text = "读取";
                rbxRWMsg.Enabled = false;
            }
            else
            {
                btnRW.Text = "写入";
                rbxRWMsg.Enabled = true;
            }
        }/// <summary>
        /// 写入单个线圈
        /// </summary>
        private void WriteSingleCoil()
        {
            bool result = false;
            if (rbxRWMsg.Text.Equals("true", StringComparison.OrdinalIgnoreCase) || rbxRWMsg.Text.Equals("1", StringComparison.OrdinalIgnoreCase))
            {
                result = true;
            }
            master.WriteSingleCoil((byte)nudSlaveID.Value, (ushort)nudStartAdr.Value, result);
        }

        /// <summary>
        /// 批量写入线圈
        /// </summary>
        private void WriteArrayCoil()
        {
            List<string> strList = rbxRWMsg.Text.Split(',').ToList();

            List<bool> result = new List<bool>();

            strList.ForEach(m => result.Add(m.Equals("true", StringComparison.OrdinalIgnoreCase) || m.Equals("1", StringComparison.OrdinalIgnoreCase)));

            master.WriteMultipleCoils((byte)nudSlaveID.Value, (ushort)nudStartAdr.Value, result.ToArray());
        }
        /// <summary>
        /// 写入单个寄存器
        /// </summary>
        private void WriteSingleRegister()
        {
            ushort result = Convert.ToUInt16(rbxRWMsg.Text);

            master.WriteSingleRegister((byte)nudSlaveID.Value, (ushort)nudStartAdr.Value, result);
        }

        /// <summary>
        /// 批量写入寄存器
        /// </summary>
        private void WriteArrayRegister()
        {
            List<string> strList = rbxRWMsg.Text.Split(',').ToList();

            List<ushort> result = new List<ushort>();

            strList.ForEach(m => result.Add(Convert.ToUInt16(m)));

            master.WriteMultipleRegisters((byte)nudSlaveID.Value, (ushort)nudStartAdr.Value, result.ToArray());
        }

        /// <summary>
        /// 读取输出线圈
        /// </summary>
        /// <returns></returns>
        private bool[] ReadCoils()
        {
            return master.ReadCoils((byte)nudSlaveID.Value, (ushort)nudStartAdr.Value, (ushort)nudLength.Value);
        }

        /// <summary>
        /// 读取输入线圈
        /// </summary>
        /// <returns></returns>
        private bool[] ReadInputs()
        {
            return master.ReadInputs((byte)nudSlaveID.Value, (ushort)nudStartAdr.Value, (ushort)nudLength.Value);
        }

        /// <summary>
        /// 读取保持型寄存器
        /// </summary>
        /// <returns></returns>
        private ushort[] ReadHoldingRegisters()//ushort[]
        {
            return master.ReadHoldingRegisters((byte)nudSlaveID.Value, (ushort)nudStartAdr.Value, (ushort)nudLength.Value);
        }

        /// <summary>
        /// 读取输入寄存器
        /// </summary>
        /// <returns></returns>
        private ushort[] ReadInputRegisters()
        {
            return master.ReadInputRegisters((byte)nudSlaveID.Value, (ushort)nudStartAdr.Value, (ushort)nudLength.Value);
        }
        private void btnRW_Click(object sender, EventArgs e)//读写事件
        {
            if (serialPort.IsOpen)
            {
                try
                {
                    //根据选择的模式进行读写
                    switch (cbxMode.SelectedItem.ToString())
                    {
                        case "读取输出线圈":
                            SetMsg(ReadCoils().ToList());
                            break;
                        case "读取离散输入":
                            SetMsg(ReadInputs().ToList());
                            break;
                        case "读取保持型寄存器":
                            SetMsg(ReadHoldingRegisters().ToList());
                            break;
                        case "读取输入寄存器":
                            SetMsg(ReadInputRegisters().ToList());
                            break;
                        case "写入单个线圈":
                            if (rbxRWMsg.Text.Contains(","))
                            {
                                MessageBox.Show("输入值过多");
                                return;
                            }
                            WriteSingleCoil();
                            break;
                        case "写入多个线圈":
                            WriteArrayCoil();
                            break;
                        case "写入单个寄存器":
                            if (rbxRWMsg.Text.Contains(","))
                            {
                                MessageBox.Show("输入值过多");
                                return;
                            }
                            WriteSingleRegister();
                            break;
                        case "写入多个寄存器":
                            WriteArrayRegister();
                            break;
                        default:
                            break;
                    }
                }
                catch(Exception ex) 
                {
                    tbMessage.AppendText(ex.Message.ToString().Replace("\r\n", "\n"));
                }
                
            }
            
        }
    }
}
/// /// 读保持寄存器03 /// /// 数据读取延迟 /// 设备从站地址 /// 数据起始地址 /// 寄存器数量 /// 返回的寄存器数值 /// 返回异常描述 /// 是否读取成功 public bool ReadHoldReg(int timeout, byte slaveAddress, ushort startAddress, ushort regCountIn, out ushort[] holdRegs, out ModbusException ex) /// /// 读输入寄存器04 /// /// 数据读取延迟 /// 设备从站地址 /// 数据地址 /// 寄存器数量 /// 返回的寄存器数值 /// 返回异常描述 /// 是否读取成功 public bool ReadInputReg(int timeout, byte slaveAddress, ushort startAddress, ushort regCountIn, out ushort[] InputRegs, out ModbusException ex) /// /// 写单寄存器(06功能码) /// /// 数据读取延迟 /// 设备从站地址 /// 寄存器地址 /// 寄存器值 /// 返回异常描述 /// 是否写入成功 public bool WriteSingleReg(int timeout, byte slaveAddress, ushort regAdr, ushort regValue, out ModbusException ex) /// /// 写单个线圈(05功能码) /// /// 数据读取延迟 /// 设备从站地址 /// 寄存器地址 /// 寄存器值 /// 返回异常描述 /// 是否写入成功 public bool WriteSingleCoil(int timeout, byte slaveAddress, ushort regAdr, ushort ONorOFF, out ModbusException ex) /// /// 写多寄存器(10功能码) /// /// 数据读取延迟 /// 设备从站地址 /// 寄存器起始地址 /// 寄存器值 /// 返回异常描述 /// 是否写入成功 public bool WriteMutilReg(int timeout, byte slaveAddress, ushort regAdr, ushort[] regValue, out ModbusException ex) ....................
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值