C# 对NModbus4的简单应用

时间:2025-05-12 08:27:19
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Modbus.Device; using System.Net.Sockets; using System.Net; using Modbus.Data; using Modbus.Utility; namespace NModbus4_Pro.U_UserPage { public partial class UserModbusMaster : UserControl { public UserModbusMaster() { InitializeComponent(); } private TcpClient client; private ModbusIpMaster master; private void ModbusSlave_Load(object sender, EventArgs e) { } #region Control private void SetDataCoil(bool[] coils) { foreach(Control c in groupBox1.Controls) { if (c.GetType() == typeof(CheckBox)&& c.Tag != null) { CheckBox ck = c as CheckBox; int tag = Convert.ToInt32(c.Tag); if (ck.InvokeRequired) { this.BeginInvoke(new Action(delegate { ck.Checked = coils[tag]; })); } else { ck.Checked = coils[tag]; } } } } private void SetDataHoldingRegister(ushort[] holding_register) { foreach (Control c in groupBox2.Controls) { if (c.GetType() == typeof(TextBox) && c.Tag != null) { TextBox txtBox = c as TextBox; int tag = Convert.ToInt32(c.Tag); if (txtBox.InvokeRequired) { this.BeginInvoke(new Action(delegate { txtBox.Text = holding_register[tag-1].ToString(); })); } else { txtBox.Text = holding_register[tag-1].ToString(); } } } } #endregion private void btnStart_Click(object sender, EventArgs e) { try { this.Close(); client = new TcpClient(); client.Connect(IPAddress.Parse(txtIP.Text.Trim()), (int)txtPort.Value); master = ModbusIpMaster.CreateIp(client); if (client.Connected) { btnMaster.BackColor = Color.Green; } } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void Close() { try { if (client != null && master != null) { client.Close(); master.Dispose(); btnMaster.BackColor = Color.LightYellow; } } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void btnWrite_Click(object sender, EventArgs e) { if(client!=null&& master != null) { if (client.Connected) { master.WriteSingleCoil((ushort)nud_MasterCoilAds.Value, nud_MasterCoilVal.Value == 1 ? true : false); master.WriteSingleRegister((ushort)nud_MasterHRAds.Value, (ushort)nud_MasterHRVal.Value); } else { MessageBox.Show("连接已断开!"); } } } private void timer1_Tick(object sender, EventArgs e) { try { if (client != null && master != null) { if (client.Connected) { bool[] coils = master.ReadCoils(1, 0, 9); this.SetDataCoil(coils); ushort[] holding_register = master.ReadHoldingRegisters(1, 0, 12); this.SetDataHoldingRegister(holding_register); } } } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } } }