之前一直想用C#写一个MODBUS通信的案例,本来想用SerialPort直接写的,然后发现可以用 nModbus类库,可以直接引用来开发做Modbus接口,非常方便,不说了,上图上代码
ps:nmodbus的中文说明书需要可以下载。
安装部署nModbus类库:
2.winform设计
3.为了测试我没有写成开放性的,也只是调用了timer做一个小的数据监控,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Modbus.Device;
namespace modbus
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Enabled = false;
}
//实例化一个串口
public SerialPort serialPort1 = new SerialPort("COM3");
IModbusSerialMaster master;
byte slaveID = 1;
ushort startAddress = 0;
ushort numOfPoints = 10;
private void Form1_Load(object sender, EventArgs e)
{
}
private void OpenBtn_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
OpenBtn.Text = "打开串口";
serialPort1.Close();
timer1.Enabled = false;
}
else {
timer1.Enabled = true;
OpenBtn.Text = "关闭串口";
serialPort1.Open();
//myThread.Start();
}
serialPort1.BaudRate = 9600;//配置
serialPort1.DataBits = 8;//数据位
serialPort1.Parity = Parity.None;//校验位
serialPort1.StopBits = StopBits.One;//停止位
//创建 Rtu 传输模式、通过串口 port 通信的主站
master = ModbusSerialMaster.CreateRtu(serialPort1);
master.Transport.ReadTimeout = 1000;//读取串口数据超时为 1000ms master.Transport.WriteTimeout = 1000;//写入串口数据超时
master.Transport.Retries = 3;//重试次数
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
serialPort1.Close();
timer1.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
bool[] all = master.ReadCoils(slaveID, startAddress, numOfPoints);
textBox1.Text = all[0].ToString();
if (all[0] == true)
{
button1.BackColor = Color.Red;
}
else { button1.BackColor = Color.Green; }
}
}
}