前言
本文介紹瞭如何使用三菱提供的MX Component外掛實現對三菱PLC軟元件資料的讀寫,記錄了使用計算機模擬,模擬PLC,直至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。
用到的軟體:
1. PLC開發程式設計環境GX Works2,GX Works2下載連結 https://www.mitsubishielectric-fa.cn/site/file-software-detail?id=18
2.實現計算機與可程式設計控制器通訊的軟體工具MX Component,MX Component下載連結 https://www.mitsubishielectric-fa.cn/site/file-software-detail?id=27
(2)修改PLC引數,PLC檔案設定=>使用一下檔案=>命名,設定合適的容量大小,擴容為了後期測試時使用(該操作可選);
(3)修改軟元件設定,使用上一步驟中的擴容操作,三菱PLC設計上位機資料操作區一般選擇D區,R區和W區亦可(該操作可選);
(4)除錯中選擇=>模擬開始,出現Simulator視窗,Mode和RUN綠燈長亮即表示模擬正常;
2.MX Component配置流程:
(1)找到MX Component安裝的對應軟體,選擇“Communication Setup Utility”,以管理員身份執行;
(2)新增Logical Station Number(通道號);(這裡以99為例)
(3)由於本案例採用的是GX Works2模擬方案,選擇GX Simulator2,選擇CPU型號,下一步即可;
(4)選擇描述,,以Test為例;
(5)配置完成後,進行測試,顯示successful表示連線成功;連線成功後可以關掉該軟體,不影響正常通訊;
3.C#上位機的程式測試:
using ActUtlTypeLib; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace MELSEC.MX.Test { public partial class Form1 : Form { private ActUtlType m_plc; public Form1() { InitializeComponent(); m_plc = new ActUtlType(); } private void Form1_Load(object sender, EventArgs e) { cmb_LogicalStationNumber.Items.Clear(); for (int i = 1;i<=256;i++) { cmb_LogicalStationNumber.Items.Add(i.ToString()); } } private void btn_Comm_Click(object sender, EventArgs e) { try { int logNUM = Convert.ToInt16(cmb_LogicalStationNumber.Text); m_plc.ActLogicalStationNumber=logNUM; m_plc.ActPassword = ""; if (m_plc.Open() != 0) { btn_Comm.BackColor = Color.Gray; btn_Comm.Text = "未建立連結"; m_plc.Close(); m_plc = null; } else { btn_Comm.BackColor = Color.Green; btn_Comm.Text = "已連線"; } } catch (Exception ) { throw; } } private void btn_Read_Click(object sender, EventArgs e) { try { Thread thread = new Thread(() => { while (true) { txb_D0.Invoke(new Action(() => { txb_D0.Text = ReadDeviceValue("D0", 2)[0].ToString(); txb_D1.Text = ReadDeviceValue("D0", 2)[1].ToString(); txb_R100.Text = ReadDeviceValue("R100", 1)[0].ToString(); txb_W500.Text = ReadDeviceValue("W500", 1)[0].ToString(); })); Thread.Sleep(300); } }); thread.IsBackground = true; thread.Start(); } catch (Exception) { throw; } } private string[] ReadDeviceValue(string DeviceName,int NumberOfData) { int iReturnCode; short[] arrDeviceValue; string szDeviceName; string[] arrData= { }; int iNumberOfData; try { szDeviceName = string.Join("\n", DeviceName); iNumberOfData = Convert.ToInt32(NumberOfData); arrDeviceValue = new short[iNumberOfData]; iReturnCode = m_plc.ReadDeviceBlock2(szDeviceName, iNumberOfData, out arrDeviceValue[0]); if (iReturnCode == 0) { arrData = new string[iNumberOfData]; for (int i = 0; i < iNumberOfData; i++) { arrData[i] = arrDeviceValue[i].ToString(); } return arrData; } return arrData; } catch (Exception ex) { MessageBox.Show(ex.Message, Name, MessageBoxButtons.OK, MessageBoxIcon.Error); return arrData; } } } }
Demo演示