1、读取操作
2、写入操作
① Visual Studio 2022社区版
② Modsim32
③ VSPD虚拟串口
1、打开VS 2022,创建新项目
2、引入NModbus4类库
3、界面设计
4、代码
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace ModbusRTU
{
public partial class Form1 : Form
{
private SerialPort serialPort = new SerialPort(); //创建串口实例
private static IModbusMaster master; //创建Modbus主站实例
public Form1() //构造窗体
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) //窗体加载
{
cbxPort.Items.AddRange(SerialPort.GetPortNames()); //获取设备串口
cbxBaudRate.Items.AddRange(new object[] { 9600, 14400,19200, 38400,56000,57600,115200,128000,256000 }); //可选波特率
cbxParity.Items.AddRange(new object[] { "None", "Odd", "Even", "Mark", "Space" }); //可选奇偶校验
cbxDataBits.Items.AddRange(new object[] { 5, 6, 7, 8 }); //可选数据位
cbxStopBits.Items.AddRange(new object[] { 1, 1.5, 2 }); //可选停止位
cbxMode.Items.AddRange(new object[]
{
"读输出线圈","读离散输入","读保持寄存器","读输入寄存器",
"写单个线圈","写多个线圈","写单个寄存器","写多个寄存器"
}); //可选读写模式
cbxPort.SelectedIndex = 1; //各参数默认项
cbxBaudRate.SelectedIndex = 0;
cbxParity.SelectedIndex = 0;
cbxDataBits.SelectedIndex = 3;
cbxStopBits.SelectedIndex = 0;
cbxMode.SelectedIndex = 0;
nudLength.Minimum = 1;
nudSlaveID.Minimum = 1;
nudStartAdr.Minimum = 0;
rbxRWMsg.ImeMode = ImeMode.Disable; //默认输入法
}
.....................................................................
文末附完整程序链接。
5、使用VSPD构建虚拟串口对COM5、COM6
6、使用Modsim32模拟Modbus从站数据
关于VSPD和Modsim32的使用,可参考之前的文章:
浅谈Modbus调试工具与VSPD虚拟串口的使用
7、程序运行测试
链接:https://pan.baidu.com/s/1C2oXs6CP1UnjrtFQ1c3MbA?pwd=7777
提取码:7777
C#学习记录——Modbus学习(NModbus4)_阿雷笔记的博客-CSDN博客_nmodbus4
该网址程序拷贝后,运行起来有些不正常,已修改并另有小改动。
页面更新:2024-03-13
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号