自動化的行業其實有別於軟件行業,但是在我們平時工作中,可能會遇到一些需要用高級語言編寫程序來完成的工作,這時候稍微學會一門高級語言,可以提高工作效率,本篇就用一個簡單的C#程序來完成ModbusTCP的通信功能。
1、 打開Visual studio 2019
首先,選擇"創建新項目"
然後選在"Windows 窗體應用",點擊下一步
然後填寫應用存放的目錄,框架選擇 .net 4.0,點擊創建。
2、 我們新建的窗體應用
在我們新建的窗體上放置兩個按鈕(Button)及兩個標籤(Label)
修改我們新建的兩個Button為"連接","讀取數據"
右鍵單擊"引用",選擇"管理NuGet程序包"
搜索"easymodbus",下載安裝
3、 程序片段
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EasyModbus;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
EasyModbus.ModbusClient modbusClient = new ModbusClient();
int[] int1;
public Form1()
{
InitializeComponent();
}
public void InitModbus()
{
modbusClient.Connect("127.0.0.1", 502);
if (modbusClient.Connected)
{
label1.Text = "連接上";
}
else
{
label1.Text = "未連接上";
}
}
private void Button1_Click(object sender, EventArgs e)
{
InitModbus();
}
private void Button2_Click(object sender, EventArgs e)
{
int1 = modbusClient.ReadHoldingRegisters(0, 10);
string str = "";
foreach(int i in int1)
{
str += i.ToString()+",";
}
label2.Text = str;
}
}
}
4、 效果
我們現在電腦上建立一個modbusTcp服務器
然後運行程序,我們可以看到數據被讀取並顯示。
想要了解更多,關注留言,或者私信我,將為你解答。
閱讀更多 能源工控微課堂 的文章