三合一网站搭建价格,品牌网站的目的,app应用网站单页模板,网站做流量推广的方式前面说了三菱和西门子PLC的上位机通信#xff0c;实际在生产应用中#xff0c;设备会有很多不同的厂家生产的PLC#xff0c;那么#xff0c;我们就需要一种通用的语言#xff0c;进行设备之间的通信#xff0c;工业上较为广泛使用的语言之一就是Modbus。
Modbus有多种连…前面说了三菱和西门子PLC的上位机通信实际在生产应用中设备会有很多不同的厂家生产的PLC那么我们就需要一种通用的语言进行设备之间的通信工业上较为广泛使用的语言之一就是Modbus。
Modbus有多种连接方式如串口RTU、以太网TCP/IP今天我们讲的是TCP也就是插网线的方式。
首先我们安装从机的仿真上位机软件作为主机。从机仿真可以用Modbus Slave这个软件。 这样从机就设置好了接下来用C#编写主机上位机代码
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]*256res[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