本文主要是介绍C#与三菱FX5U、Q系列PLC通讯程序基于3E帧SLMP/MC协议,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C#与三菱FX5U、Q系列PLC通讯程序基于3E帧SLMP/MC协议
1.最近项目需要用到C#与FX5U的PLC以太网通讯,通过研究三菱FX5U和Q系列PLC的SLMP/MC协议,使用C#语言发送报文与PLC通讯,用了一个星期时间,做了一个测试程序,封装了一个类库可以实现PLC不同变量和类型的读写,并且支持数组类型批量读写操作。
2.程序可以实时监控网络状态,具有断网重连功能。并举例采集实时曲线,测试运行稳定。
3.具体程序界面如下。下面有部分源码,需要全套源码+V:1357448516 或者 qq:584472557
3.FX5UPLC需要设置SLMP和IP地址,步骤如下。
4.设置SLMP的端口号,PLC设置完成。
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 System.Net .Sockets ;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Windows.Forms.DataVisualization.Charting;
namespace FX5UTest
{
public partial class Form1 : Form
{
public bool bool_Linajiezt;
//画曲线使能
private bool ThrowEn = false;
//界面加载延时定时器
System.Windows.Forms.Timer DownloadDelayedTimer;
//PLC循环读取线程
private Thread threadPLCCycle;
//textbox控件Text多线程调用枚举
private delegate void delegateText(TextBox textbox, string text);
//DatagridView控件多线程显示
private delegate void delegateGridView(DataGridView DataView, DataTable Data);
//label控件颜色多线程调用枚举
private delegate void delegateLabelColor(Label label, Color color);
//label控件Text多线程调用枚举
private delegate void delegateLabel(Label label, string text);
//画曲线多线程委托
delegate void RefreshColumnChart(Chart chart1, ChartData item1);
//画曲线清空委托
delegate void delegateChartClear();
public Form1()
{
InitializeComponent();
}
private void listView2_SelectedIndexChanged(object sender, EventArgs e)
{
}
//手动输入报文测试,方便学习和通过返回报文判断输入报文是否正确
private void btnSend_Click(object sender, EventArgs e)
{
try
{
int sendNum = txtSend.Text.Length / 2;
byte[] strSend = new byte[sendNum];
for (int i = 0; i < sendNum - 1; i++)
{
strSend[i] = Convert.ToByte(txtSend.Text.Substring(i * 2, 2), 16);
}
_5ULink.tcpClient.Send(strSend, 0, strSend.Length, SocketFlags.None);
string strReturn = readWordeReceive(13, 250);
txtReturn.Text = strReturn;
}
catch
{
}
}
private string readWordeReceive(int intStrLen,int overTime)
{
int TT=Environment .TickCount;
byte[] rb=new byte[intStrLen];
while((Environment .TickCount-TT)<overTime)
{
if (_5ULink.tcpClient.Available >= intStrLen) break;
}
if (_5ULink.tcpClient.Available < intStrLen)
return "";
_5ULink. tcpClient.Receive (rb);
return BitConverter.ToString(rb);
}
private void Form1_Load(object sender, EventArgs e)
{
txtSend.Text = "500000FFFF03000C000000010400000A00009D0100";
txtIP .Text="192.168.1.4";
txtPort.Text = "2050";
_5ULink.newNet("192.168.1.4", 2050);//初始化PLC网络
//初始化界面加载延时计时器
DownloadDelayedTimer = new System.Windows.Forms.Timer();
DownloadDelayedTimer.Interval = 1000;
DownloadDelayedTimer.Tick += new EventHandler(DownloadDelayedTimer_Tick);
DownloadDelayedTimer.Enabled = true;
//初始化控件
comBoxBoolArea.Items.Add("X");
comBoxBoolArea.Items.Add("Y");
comBoxBoolArea.Items.Add("M");
comBoxBoolArea.SelectedIndex = 1;
comBoxBoolVal.Items.Add("True");
comBoxBoolVal.Items.Add("False");
comBoxBoolVal.SelectedIndex = 1;
comBoxIntArea.Items.Add("M");
comBoxIntArea.Items.Add("D");
comBoxIntArea.SelectedIndex = 1;
comBoxRealArea.Items.Add("M");
comBoxRealArea.Items.Add("D");
comBoxRealArea.SelectedIndex = 1;
comBoxStringArea.Items.Add("M");
comBoxStringArea.Items.Add("D");
comBoxStringArea.SelectedIndex = 1;
comBoxArrayArea.Items.Add("M");
comBoxArrayArea.Items.Add("D");
comBoxArrayArea.SelectedIndex = 1;
InitChart();//初始化曲线控件
}
/// <summary>
/// 界面加载延时处理函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DownloadDelayedTimer_Tick(object sender, EventArgs e)
{
DownloadDelayedTimer.Enabled = false;
threadPLCCycle = new Thread(PLCControl);
threadPLCCycle.IsBackground = true;
threadPLCCycle.Start();
}
/// <summary>
/// PLC循环读取处理
/// </summary>
private void PLCControl()
{
while (true)
{
_5ULink.connectPLC();//循环检测PLC通讯状态
if (_5ULink.ConectStatus == true)
{
labLink.BackColor = Color.Lime;
LabShow(labLink, "链接正常");
}
else
{
labLink.BackColor = Color.Red;
LabShow(labLink, "链接断开");
}
try
{
CyceleThrowCurve();//画曲线采集数据
}
catch (Exception ex)
{
}
Thread.Sleep(100);
}
}
private void btnWrite_Click(object sender, EventArgs e)
{
//bool变量写入控制
if(chkboxBool.Checked)
{
int writeAdrr = 0;
if (int.TryParse(txtBoxBoolAdr.Text.Trim(), out writeAdrr))//判断输入地址是否是整数
{
string strAdrr = comBoxBoolArea.Text.Trim() + txtBoxBoolAdr.Text.Trim();//变量地址
bool writeValue=false;
if (comBoxBoolVal.Text.Trim() == "True")
{
writeValue = true;
}
else
{
writeValue = false;
}
_5ULink.writeBool(strAdrr, writeValue);
}
else
{
MessageBox.Show("请输入正确的Bool变量地址");
}
}
//Int16整型变量写入控制
if (chkboxInt.Checked)
{
int writeAdrr = 0;
int writeVal = 0;
if (int.TryParse(txtBoxIntAdr.Text.Trim(), out writeAdrr) && int.TryParse(txtBoxIntVal.Text.Trim(), out writeVal))//判断输入地址是否是整数
{
string strAdrr = comBoxIntArea.Text.Trim() + txtBoxIntAdr.Text.Trim();//变量地址
_5ULink.writeInt16(strAdrr, writeVal);
}
else
{
MessageBox.Show("请输入正确的变量地址和写入值");
}
}
//Real浮点数变量写入控制
if (chkboxReal.Checked)
{
int writeAdrr = 0;
float writeVal = 0.0f;
if (int.TryParse(txtBoxRealAdr.Text.Trim(), out writeAdrr) && float.TryParse(txtBoxRealVal.Text.Trim(), out writeVal))//判断输入地址是否是整数
{
string strAdrr = comBoxRealArea.Text.Trim() + txtBoxRealAdr.Text.Trim();//变量地址
_5ULink.writeReal(strAdrr, writeVal);
}
else
{
MessageBox.Show("请输入正确的变量地址和写入值");
}
}
//String字符串变量写入控制
if (chkboxString.Checked)
{
int writeAdrr = 0;
if (int.TryParse(txtBoxStringAdr.Text.Trim(), out writeAdrr) && (txtBoxStringVal.Text!= ""))//判断输入地址是否是整数
{
string strAdrr = comBoxStringArea.Text.Trim() + txtBoxStringAdr.Text.Trim();//变量地址
_5ULink.writeString(strAdrr, txtBoxStringVal.Text);
}
else
{
MessageBox.Show("请输入正确的变量地址和写入值");
}
}
//Array数组变量写入控制
//下面以浮点数数组为例子进行测试,其他类型数组用法类似,调用相应函数就可以
if (chkboxArray.Checked)
{
int writeAdrr = 0;
if (int.TryParse(txtBoxArrayAdr.Text.Trim(), out writeAdrr))//判断输入地址是否是整数
{
string strAdrr = comBoxArrayArea.Text.Trim() + txtBoxArrayAdr.Text.Trim();//变量地址
float[] writeArray = new float[4] {100.0f,200.0f,300.0f,400.0f};
_5ULink.writeRealArray(strAdrr, writeArray);
}
else
{
MessageBox.Show("请输入正确的变量地址和写入值");
}
}
}
private void btnRead_Click(object sender, EventArgs e)
{
//bool变量读取控制
if (chkboxBool.Checked)
{
int readAdrr = 0;
if (int.TryParse(txtBoxBoolAdr.Text.Trim(), out readAdrr))//判断输入地址是否是整数
{
string strAdrr = comBoxBoolArea.Text.Trim() + txtBoxBoolAdr.Text.Trim();//变量地址
bool readbol= _5ULink.readBool(strAdrr);
if (readbol)
{
comBoxBoolVal.SelectedIndex = 0;
}
else
{
comBoxBoolVal.SelectedIndex = 1;
}
}
else
{
MessageBox.Show("请输入正确的Bool变量地址");
}
}
//int16位整数读取控制
if (chkboxInt.Checked)
{
int readAdrr = 0;
if (int.TryParse(txtBoxIntAdr.Text.Trim(), out readAdrr))//判断输入地址是否是整数
{
string strAdrr = comBoxIntArea.Text.Trim() + txtBoxIntAdr.Text.Trim();//变量地址
txtBoxIntVal.Text = _5ULink.readInt16(strAdrr).ToString();
}
else
{
MessageBox.Show("请输入正确的int变量地址");
}
}
//Real浮点数读取控制
if (chkboxReal.Checked)
{
int readAdrr = 0;
if (int.TryParse(txtBoxRealAdr.Text.Trim(), out readAdrr))//判断输入地址是否是整数
{
string strAdrr = comBoxRealArea.Text.Trim() + txtBoxRealAdr.Text.Trim();//变量地址
txtBoxRealVal.Text = _5ULink.readReal(strAdrr).ToString();
}
else
{
MessageBox.Show("请输入正确的Real变量地址");
}
}
//String字符串读取控制
if (chkboxString.Checked)
{
int readAdrr = 0;
if (int.TryParse(txtBoxStringAdr.Text.Trim(), out readAdrr))//判断输入地址是否是整数
{
string strAdrr = comBoxStringArea.Text.Trim() + txtBoxStringAdr.Text.Trim();//变量地址
txtBoxStringVal.Text = _5ULink.readString(strAdrr,10).ToString();
}
else
{
MessageBox.Show("请输入正确的Sting变量地址");
}
}
}
/// <summary>
///循环画曲线控制
/// </summary>
private void CyceleThrowCurve()
{
ChartData item1 = new ChartData();
double Torque1 = 0.0;
if (ThrowEn == true)
{
//清空曲线
this.BeginInvoke(new delegateChartClear(
() =>
{
chart1.Series[0].Points.Clear();
}));
}
while (ThrowEn)
{
try
{
item1 = new ChartData();
Torque1 = _5ULink.readReal("D50");//读取实时数据
item1.Label = DateTime.Now.ToString("HH:mm:ss");
item1.Value = Torque1;
textShow(txtbox1, Torque1.ToString());
//画1轴曲线
if (chart1.InvokeRequired)
{
RefreshColumnChart opcdelateTimer = new RefreshColumnChart(InvokeRefreshColumnChart);
this.Invoke(opcdelateTimer, chart1, item1);
}
else
{
if (chart1.Series[0].Points.Count >= 60)
{
chart1.Series[0].Points.RemoveAt(0);
chart1.Series[0].Points.InsertXY(59, item1.Label, item1.Value);
}
else
{
chart1.Series[0].Points.InsertXY(chart1.Series[0].Points.Count, item1.Label, item1.Value);
}
}
}
catch (Exception ex)
{
}
Thread.Sleep(80);
}
}
/// <summary>
/// 初始化chart
/// </summary>
private void InitChart()
{
Double maxY =200.0;
chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = Color.LightGray;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = Color.LightGray;
chart1.ChartAreas["ChartArea1"].BackColor = Color.CadetBlue;
//设置图案颜色
chart1.Series[0].Color = Color.Red;
//设置图案的线宽度
chart1.Series[0].BorderWidth = 2;
//设置显示类型-线型
chart1.Series[0].ChartType = SeriesChartType.Spline;
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 15;
//设置显示的范围
chart1.ChartAreas["ChartArea1"].AxisX.ScaleView.Size = 60;
chart1.ChartAreas["ChartArea1"].AxisX.Maximum = 60;
chart1.ChartAreas["ChartArea1"].AxisY.Interval = maxY / 5;
//设置显示的范围
chart1.ChartAreas["ChartArea1"].AxisY.ScaleView.Size = maxY;
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
chart1.Series[0].XValueMember = "Label";
chart1.Series[0].YValueMembers = "Value";
}
public class ChartData
{
public string Label { get; set; }
public double Value { get; set; }
}
//画曲线多线程处理函数
private void InvokeRefreshColumnChart(Chart chart1, ChartData item1)
{
if (chart1.Series[0].Points.Count >= 60)
{
chart1.Series[0].Points.RemoveAt(0);
chart1.Series[0].Points.InsertXY(59, item1.Label, item1.Value);
}
else
{
chart1.Series[0].Points.InsertXY(chart1.Series[0].Points.Count, item1.Label, item1.Value);
}
}
#region text控件Text多线程显示
private void textShow(TextBox textbox, string text)
{
try
{
if (textbox.InvokeRequired)
{
delegateText opcdelateTimer = new delegateText(InvokeLabel);
this.Invoke(opcdelateTimer, textbox, text);
}
else
{
textbox.Text = text;
}
}
catch
{
}
}
private void InvokeLabel(TextBox textbox, string text)
{
textbox.Text = text;
}
#endregion
#region DATAGridView控件多线程显示数据
private void InvokegridView(DataGridView DataView, DataTable Data)
{
if (DataView.InvokeRequired)
{
delegateGridView datagridView1 = new delegateGridView(InvokegateGridView);
this.Invoke(datagridView1, DataView, Data);
}
else
{
DataView.DataSource = Data;
DataView.Columns[0].Width = 155;
DataView.Columns[1].Width = 250;
DataView.Columns[2].Width = 105;
}
}
private void InvokegateGridView(DataGridView DataView, DataTable Data)
{
DataView.DataSource = Data;
DataView.Columns[0].Width = 155;
DataView.Columns[1].Width = 250;
DataView.Columns[2].Width = 105;
}
#endregion
#region lab控件多线程显示颜色
private void LabShowColor(Label label, Color color)
{
if (label.InvokeRequired)
{
delegateLabelColor opcdelateTimer = new delegateLabelColor(InvokeLabelColor);
this.Invoke(opcdelateTimer, label, color);
}
else
{
label.BackColor = color;
}
}
private void InvokeLabelColor(Label label, Color color)
{
label.BackColor = color;
}
#endregion
#region lab控件Text多线程显示
private void LabShow(Label label, string text)
{
try
{
if (label.InvokeRequired)
{
delegateLabel opcdelateTimer = new delegateLabel(InvokeLabel);
this.Invoke(opcdelateTimer, label, text);
}
else
{
label.Text = text;
}
}
catch
{
}
}
private void InvokeLabel(Label label, string text)
{
label.Text = text;
}
#endregion
private void btnStart_Click(object sender, EventArgs e)
{
ThrowEn = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
ThrowEn = false;
}
}
}
这篇关于C#与三菱FX5U、Q系列PLC通讯程序基于3E帧SLMP/MC协议的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!