C# Modbus TCP上位机测试

前面说了三菱和西门子PLC的上位机通信,实际在生产应用中,设备会有很多不同的厂家生产的PLC,那么,我们就需要一种通用的语言,进行设备之间的通信,工业上较为广泛使用的语言之一就是Modbus。

Modbus有多种连接方式,如串口(RTU)、以太网(TCP/IP),今天我们讲的是TCP,也就是插网线的方式。

首先,我们安装从机的仿真,上位机软件作为主机。从机仿真可以用Modbus Slave这个软件。

这样从机就设置好了,接下来用C#编写主机(上位机)代码:

cs 复制代码
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;
using thinger.DataConvertLib;

namespace Modbus
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

            this.StartPosition = FormStartPosition.CenterScreen;
            this.MaximizeBox = false;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        }

        private void writeLog(string log)
        {
            string text = txtLog.Text;

            if (text.Length > 10000)
            {
                text = text.Substring(0, 10000) + "\n...";
            }

            txtLog.Text = "【" + DateTime.Now.ToString() + "】" + log + "\n" + text;
        }

        ModbusTcp tcp = new ModbusTcp();
        
        private void button1_Click(object sender, EventArgs e)
        {
            tcp.Connect("192.168.0.108", "502");

            if (tcp != null)
            {
                button1.BackColor = Color.LawnGreen;
            }
            else
            {
                button1.BackColor = Color.Red;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            txtLog.Text = "";

            int address = 0;//起始地址
            int num = 10;//寄存器数量

            byte[] res = tcp.ReadKeepReg(address, num);

            for (int i = 0; i < num; i++)
            {
                writeLog("【" + i.ToString() + "】" + (res[i * 2] * 256 + res[i * 2 + 1]).ToString());//byte数据类型只能包含0~255的数,超出=res[0]*256+res[1]
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            bool success = tcp.PreSetSingleReg(int.Parse(textBox1.Text.Trim()), short.Parse(textBox2.Text.Trim()));

            if (success)
            {
                button2_Click(sender, e);
            }
        }
    }
}

最后附上全部源码:

https://download.csdn.net/download/mojocube/88103605

相关推荐
xixiaoyunya5 分钟前
内网穿透工具选型分析:从 ngrok 的局限性看国内开发场景下的替代方案
网络
FreeTinker29 分钟前
远程查看的技术路径与工程选型分析
网络
YXXY3133 小时前
网络基础2(三)
网络
m24tyy4 小时前
常见空间测绘搜索引擎介绍和使用以及子域名的收集
网络·测试工具·搜索引擎
数据安全技术观察5 小时前
数据动态脱敏:让脱敏策略跟着数据目录走
大数据·网络·数据库
我爱cope5 小时前
【计算机网络 | 网络层1:网络层的职责:IP 协议究竟解决了什么问题?】
网络·tcp/ip·计算机网络
dogstarhuang7 小时前
OpenAI GPT-5.6 降价后如何重算 API 账单?多模型路由与成本治理实战
服务器·网络·人工智能·大模型·api·ai应用开发·接口管理
苏宸啊7 小时前
linux网络编程udp服务器和客户端代码编写(echo版本和字典版本)
linux·网络
奇树谦9 小时前
HDD 为什么适合顺序大文件读写:从 RAID 5 到 RAID 50 的原理与性能分析
linux·运维·网络
嵌入式阿蔡10 小时前
Linux_01:交叉编译与开发环境实战——从单片机跨到 Linux 的第一道坎
linux·运维·网络·单片机·嵌入式硬件·嵌入式实时数据库