对汇川PLC采用Modbus-TCP进行读写寄存器测试示例
新建WinForms应用程序InovancePlcDemo,.net framework 4.5。
重命名窗体名为FormInovancePlcDemo
窗体FormInovancePlcDemo设计器如下:

使用上一篇的InovanceTcp类,
测试程序示例代码如下(忽略设计器自动生成的代码、事件):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InovancePlcDemo
{
public partial class FormInovancePlcDemo : Form
{
/// <summary>
/// 汇川PLC操作相关对象
/// </summary>
InovanceTcp inovanceTcp;
public FormInovancePlcDemo()
{
InitializeComponent();
cboReadType.SelectedIndex = 0;
cboWriteType.SelectedIndex = 0;
//默认字节顺次为CDAB 字颠倒
cboByteCategory.SelectedIndex = 2;
}
/// <summary>
/// 显示文本框的消息
/// </summary>
/// <param name="message"></param>
private void DisplayInfo(RichTextBox rtxbResult, string message)
{
this.BeginInvoke(new Action(() =>
{
if (rtxbResult.TextLength >= 20480)
{
rtxbResult.Clear();
}
rtxbResult.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} --> {message}\n");
rtxbResult.ScrollToCaret();
}));
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
inovanceTcp = new InovanceTcp(txtIP.Text, int.Parse(txtPort.Text));
inovanceTcp.Connect();
inovanceTcp.RecordDataEvent -= InovanceTcp_RecordDataEvent;
inovanceTcp.RecordDataEvent += InovanceTcp_RecordDataEvent;
DisplayInfo(rtxtMessageRead, $"连接汇川PLC结果:{inovanceTcp.IsConnected}");
MessageBox.Show($"连接汇川PLC结果:{inovanceTcp.IsConnected}");
}
catch (Exception ex)
{
DisplayInfo(rtxtMessageRead, $"连接汇川PLC失败:{ex.Message}");
MessageBox.Show($"连接汇川PLC失败:{ex.Message}");
}
}
/// <summary>
/// 记录数据包事件
/// </summary>
/// <param name="sendBuffer"></param>
/// <param name="receiveBuffer"></param>
/// <param name="spendTime"></param>
private void InovanceTcp_RecordDataEvent(byte[] sendBuffer, byte[] receiveBuffer, double spendTime)
{
DisplayInfo(rtxtMessageRead,
$"发送命令【{string.Join(" ", sendBuffer.Select(element => element.ToString("X2")))}】\n接收命令【{string.Join(" ", receiveBuffer.Select(element => element.ToString("X2")))}】\n通信耗时【{spendTime}】ms");
}
private void bt

本文介绍了如何使用InovanceTcp类在WinForms应用程序中通过Modbus-TCP协议进行汇川PLC的读写寄存器操作,包括连接、读取基本数据类型、写入数据及长字符串处理的详细步骤和示例代码。
,接上篇&spm=1001.2101.3001.5002&articleId=120182572&d=1&t=3&u=44c9ec9d203f4e088737927bb67b1d69)
1万+

被折叠的 条评论
为什么被折叠?



