c#中modubus tcp如何读写数据
话不多说,直接上代码,上代码之前前提是你的modubus实体机器能和电脑连通,至于如何连接,自行百度,一搜一大把,我这里就不做过多解释了,目前我用的软件是Modubus Slave
连接成功是这样的:
首先创建连接:
ModbusTcpNet busTcpClient = new ModbusTcpNet("192.168.3.1", 5005, 0x01);
这里我用的方式是长连接方式,打开长连接:
busTcpClient.ConnectServer();
下面是我抓取数据的点击事件里面所写的代码:
private void Btn_receivedata_Click(object sender, EventArgs e)
{
ModbusTcpNet busTcpClient = new ModbusTcpNet("192.168.3.1", 5005, 0x01);
//ModbusTcpNet busTcpClient = new ModbusTcpNet("127.0.0.1", 502, 0x01);//127.0.0.1是从站也就是服务端的ip地址,502是服务端的端口号,0*01是功能码
busTcpClient.ConnectServer();//开启长连接
//busTcpClient.AddressStartWithZero = false;//设备地址从1开始,必写
// 读取操作
//; busTcpClient.ReadBool("0", 10)
//HslCommunication.OperateResult<byte[]> read =new HslCommunication.OperateResult<byte[]>( BitConverter.GetBytes(Convert.ToBoolean(busTcpClient.ReadBool("0", 10))).ToString());//主站访问方式
HslCommunication.OperateResult<byte[]> read = busTcpClient.Read("0", 10);
if (read.IsSuccess)
{
// 共返回20个字节,每个数据2个字节,高位在前,低位在后:
string s ="";
bool t;
// 前两个字节是short数据类型
for (int i = 0; i < read.Content.Length; i++)
{
t = busTcpClient.ByteTransform.TransBool(read.Content, i);
if (i % 2 != 0)
{
s += " " + Convert.ToInt32(t) + " ";
}
}
textBox4.Text = s;
// 已经提取完所有的数据
}
else
{
//弹出报错信息
MessageBox.Show(read.ToMessageShowString());
}
}
下面是向你的modbus从站服务器中发送数据的点击事件代码:
ModbusTcpNet busTcpClient = new ModbusTcpNet("127.0.0.1", 502, 0x01);//127.0.0.1是从站也就是服务端的ip地址,502是服务端的端口号,0*0F是功能码
busTcpClient.ConnectServer();//开启长连接
//busTcpClient.AddressStartWithZero = false;//设备地址从1开始,必写
//bool[] nnn = new bool[] {true,false, true, false, true, false, true, false, true, false };
//short[] value = new short[] { };//1,1,1,0,1,0,0,0,0,1
if (textBox4.Text == "")
{
MessageBox.Show("请输入您要发送的数据");
}
else
{
HslCommunication.OperateResult write = busTcpClient.Write("0", textBox4.Text.ToString());
if (write.IsSuccess)
{
// 写入成功
textBox4.Text = "写入成功";
}
else
{
MessageBox.Show(write.ToMessageShowString());
}
}
注释我自认为写的已经很详细,希望能够帮助到大家,不会的可以直接问
我设计的界面是这样的: