0


c# modbus/Tcp通讯连接

一、新建一个Winform窗体应用

二、建好后添加管理程序包

** 三、在浏览中输入EasyModbus,找到第一个包下载**

四、代码部分

using EasyModbus;
using System;
using System.Windows.Forms;

namespace Modbus
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static ModbusClient mc;

    private void button4_Click(object sender, EventArgs e)
     {
         try
         {
             int add = Convert.ToInt32(textBox1.Text);
             int num = Convert.ToInt32(textBox2.Text);
             mc.WriteSingleRegister(add, num);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }

    private void button1_Click(object sender, EventArgs e)
     {
         try
         {
             mc = new ModbusClient();
             mc.Connect(textBox6.Text, Convert.ToInt32(textBox7.Text));
             MessageBox.Show("连接成功");
         }
         catch { }
     }

    private void button2_Click(object sender, EventArgs e)
     {
         try
         {
             textBox5.Clear();
             bool[] b = mc.ReadCoils(Convert.ToInt32(textBox3.Text), Convert.ToInt32(textBox4.Text));
             for (int i = 0; i < b.Length; i++)
             {
                 textBox5.AppendText(b[i].ToString() + "\r\n");
             }
         }
         catch(Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }

    private void button3_Click(object sender, EventArgs e)
     {
         try
         {
             textBox5.Clear();
             bool[] b = mc.ReadDiscreteInputs(Convert.ToInt32(textBox3.Text), Convert.ToInt32(textBox4.Text));
             for (int i = 0; i < b.Length; i++)
             {
                 textBox5.AppendText(b[i].ToString() + "\r\n");
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }

}

五、前端控件部分

** **对应代码中textbox1-7和buttonclick1-4

六、连接测试

标签: c# visual studio

本文转载自: https://blog.csdn.net/flowsea123/article/details/127211717
版权归原作者 三亩花开 所有, 如有侵权,请联系我们删除。

“c# modbus/Tcp通讯连接”的评论:

还没有评论