c#上位機與三菱PLC(FX3U)串口通訊


項目中會經常用到上位機與PLC之間的串口通信,本文介紹一下C#如何編寫上位機代碼

與三菱FX3U進行通訊

1. 第一種方法是自己寫代碼實現,主要代碼如下:

//對PLC的Y7進行置1
byte[] Y007_ON = { 0x02, 0x37, 0x30, 0x37, 0x30, 0x35, 0x03, 0x30, 0x36 };
//選擇串口參數
SerialPort sp = new SerialPort("COM5", 9600, Parity.Even, 7);
//打開串口
sp.Open();
//寫入數據
sp.Write(Y007_ON, 0, Y007_ON.Length); 
//關閉串口
sp.Close();

  該方法的缺點在於我們首先要熟悉三菱PLC的通訊協議,然后根據通信規程來編寫通信代碼

  舉例說就是要對三菱PLC的Y007口進行操作,我們需要知道要對三菱PLC發送什么參數,這

  里可以參考百度文庫的一篇文章:

  https://wenku.baidu.com/view/157632dad05abe23482fb4daa58da0116c171fa8.html

2.使用MX COMPONENT軟件

  2.1 MX Component 是一個工具,通過使用該工具,可以在無需具備通信協議及模塊知

    識的狀況下實現從計算機至三菱PLC的通信。

    MX Component的安裝使用教程網上有很多,順便找一下就可以找到合適的,這樣

    要說明的是MX Component工具,使用手冊和編程手冊都可以在三菱的網站上下載。

    工具下載:

    https://cn.mitsubishielectric.com/fa/zh/download/dwn_idx_softwareDetail.asp?sid=45

    手冊下載:

    https://cn.mitsubishielectric.com/fa/zh/download/dwn_idx_manual.asp

    下載安裝之后sample路徑(win10,默認安裝):C:\MELSEC\Act\Samples

  2.2 介紹安裝配置好MX Component之后C#使用ActUtlType控件進行串口通信

    首先要引用,這兩個DLL在例程中可以找到

    

//Logical Station Number的值和在MX Component中設置一樣
int logicalStationNumber = 0; 

//添加axActUtlType對象
AxActUtlTypeLib.AxActUtlType axActUtlType = new AxActUtlTypeLib.AxActUtlType();
//不加這三句會報
//引發類型為“System.Windows.Forms.AxHost+InvalidActiveXStateException”的異常
((System.ComponentModel.ISupportInitialize)(axActUtlType)).BeginInit();
this.Controls.Add(axActUtlType);
((System.ComponentModel.ISupportInitialize)(axActUtlType)).EndInit();

//open
axActUtlType.ActLogicalStationNumber = logicalStationNumber;
axActUtlType.ActPassword = "";
axActUtlType.Open();

//Y7寫入1
int wirteData = 1;
axActUtlType.WriteDeviceRandom("Y7", 1, ref wirteData);
//D0寫入100
int wirteData1 = 100;
axActUtlType.WriteDeviceRandom("D0", 1, ref wirteData1);
//讀D0數據
int readData;
axActUtlType.ReadDeviceRandom("D0", 1, ref readData);

//close
axActUtlType.Close();

    這里只是簡單介紹,更深入的內容還是去看編程手冊和例程。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM