设为首页 加入收藏

TOP

C#ModBus Tcp的学习及Master的实现(三)
2019-09-17 18:24:14 】 浏览:49
Tags:C#ModBus Tcp 学习 Master 实现
ort
.Parse(txt_startAddr2.Text); 179 //判断是否写线圈 180 if (comboBox1.SelectedIndex == 4 || comboBox1.SelectedIndex == 6) 181 { 182 string[] strarr = txt_data.Text.Split(' '); 183 coilsBuffer = new bool[strarr.Length]; 184 //转化为bool数组 185 for (int i = 0; i < strarr.Length; i++) 186 { 187 // strarr[i] == "0" ? coilsBuffer[i] = true : coilsBuffer[i] = false; 188 if (strarr[i] == "0") 189 { 190 coilsBuffer[i] = false; 191 } 192 else 193 { 194 coilsBuffer[i] = true; 195 } 196 } 197 } 198 else 199 { 200 //转化ushort数组 201 string[] strarr = txt_data.Text.Split(' '); 202 registerBuffer = new ushort[strarr.Length]; 203 for (int i = 0; i < strarr.Length; i++) 204 { 205 registerBuffer[i] = ushort.Parse(strarr[i]); 206 } 207 } 208 } 209 } 210 /// <summary> 211 /// 清除文本 212 /// </summary> 213 /// <param name="sender"></param> 214 /// <param name="e"></param> 215 private void button2_Click(object sender, EventArgs e) 216 { 217 richTextBox1.Clear(); 218 } 219 /// <summary> 220 /// SetMessage 221 /// </summary> 222 /// <param name="msg"></param> 223 public void SetMsg(string msg) 224 { 225 richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(msg + "\r\n"); })); 226 } 227 228 } 229 } View Code

 

界面布局

 

六 功能测试及报文解析

这里功能测试我们需要借助测试工具  Modbus Slave(Modbus从站客户端)

链接:https://pan.baidu.com/s/1Z3bET3l_2a4e6cu_p250tg
提取码:hq1r

简单说明一下,这里我实现了常用的几个功能码

0x01 读一组线圈

0x02 读一组输入线圈/离散量线圈

0x03 读一组保持寄存器

0x04 读一组输入寄存器

0x05 写单个线圈

0x06 写单个保持寄存器

0x0F 写多个线圈

0x10 写多个保持寄存器

简单说一下Modbus Slave 的操作

打开连接,建立连接,选择连接方式为Tcp/Ip 设置 Ip和端口号

选择线圈或寄存器

点击Setup->Slave Definition,这里的Function我们需要读/写什么线圈或寄存器就对应选择

 

 

测试1 功能码0x01

这里我们所有的测试从站都使用站号1 起始地址0 长度10

功能码0x01 读取线圈 Modbus Slave的Function选择01 Coil Status(0x)

测试结果:

点击Display->Communication 可以截取报文,我也不知道为什么他报文字体那么小(绝望ing)

000000-Rx:00 01 00 00 00 06 01 01 00 00 00 05
000001-Tx:00 01 00 00 00 04 01 01 01 06

测试2  功能码0x10

功能码0x10 写入一组数据到保持寄存器  Modbus Slave的Function选择03 Holding Register(4x) (说明一下 线圈和保持寄存器才有写操作)

测试结果

 报文

000070-Rx:00 01 00 00 00 11 01 10 00 00 00 05 0A 00 0C 00 22 00 38 00 4E 00 5A
000071-Tx:00 01 00 00 00 06 01 10 00 00 00 05

上文测试了一个读操作和一个写操作,其他功能码的测试与上文一致,有兴趣的可以自行测试,

下一篇博客我要针对不同的功能码做对应的报文解析

程序源码:

链接:https://pan.baidu.com/s/1mPAhRixLbsDb7h2ePENTRA
提取码:b5w6

以上都为我自己学习总结并实现,有错误之处,希望大家不吝赐教,感谢(抱拳)!

 

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇VS 快捷键使用 下一篇datatable与实体类之间相互转化的..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目