讀取q0.0的狀態,i0.0的狀態實時在窗口更新
PLC里寫一個程序? ?用常閉按鈕接i0.0信號 ,延時接通Q0.0
?
按按鈕,上位機測試效果,?
2396fcfa823aa951d
程序前提是引用了S7通信文件?
using Sharp7;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.AxHost;namespace _1200withC
{public delegate void delegateUsingUI();public partial class Form1 : Form{// 定義一個委托,用于更新 UIprivate delegate void UpdateUIDelegate(bool qState, bool iState);private bool _isRunning = true; // 用于控制線程的運行狀態private delegate void UpdateUIDelegate1(string message);public Form1(){InitializeComponent();Thread ThreadStationRead = new Thread(ThreadBackgroundStation);ThreadStationRead.IsBackground = true;ThreadStationRead.Priority = ThreadPriority.Highest;ThreadStationRead.Start();}private void Form1_FormClosing(object sender, FormClosingEventArgs e){_isRunning = false; // 關閉窗體時停止線程}//-------------------------開線程函數-----------------------------------------public void ThreadBackgroundStation(){delegateUsingUI delegateUsingUIS = new delegateUsingUI(uistart);delegateUsingUIS.Invoke();}public void uistart(){var Clinet = new S7Client();int Result = Clinet.ConnectTo("192.168.10.2", 0, 1);if (Result == 0){status.BackColor = Color.Green;statusS7.BackColor = Color.YellowGreen;while (_isRunning){try{// 讀取輸入區域的數據int ResultI;int startAddress = 0; // 起始地址int size = 1; // 讀取的字節數byte[] ibuffer = new byte[size];// 讀取過程映像輸入區域的數據ResultI = Clinet.ReadArea(S7Consts.S7AreaPE, 0, startAddress, size, S7Consts.S7WLByte, ibuffer);if (ResultI == 0){bool iState = S7.GetBitAt(ibuffer, 0, 0);int ResultQ;int startAddressQ = 0; // 起始地址int sizeQ = 1; // 讀取的字節數byte[] qbuffer = new byte[size];// 讀取過程映像輸出區域的數據ResultQ = Clinet.ReadArea(S7Consts.S7AreaPA, 0, startAddressQ, sizeQ, S7Consts.S7WLByte, qbuffer);if (ResultQ == 0){// 提取 Q0.0 的狀態bool qState = S7.GetBitAt(qbuffer, 0, 0);// 使用 Invoke 方法更新 UIif (this.InvokeRequired){this.Invoke(new UpdateUIDelegate(UpdateStateUI), qState, iState);}else{UpdateStateUI(qState, iState);}}}else{status.BackColor = Color.Red; ;statusS7.BackColor = Color.Red;}}catch(SocketException ) {// 檢測到網絡異常ShowNetworkError("網絡連接斷開,請檢查網絡連接!");break;}catch (Exception){// 其他異常處理ShowNetworkError("發生錯誤,請檢查連接!");break;}}Clinet.Disconnect();}else{ShowNetworkError("無法連接到 PLC,請檢查網絡連接!");}}//定義一個方法,用于更新 UIpublic void UpdateStateUI(bool qState, bool iState){// 更新 UI,例如在某個控件上顯示狀態label2.Text = qState ? "Q0.0 is ON" : "Q0.0 is OFF";labelIState.Text = iState ? "I0.0 is ON" : "I0.0 is OFF";}private void ShowNetworkError(string message){if (this.InvokeRequired){this.Invoke(new UpdateUIDelegate1(ShowNetworkErrorUI), message);}else{ShowNetworkErrorUI(message);}}private void ShowNetworkErrorUI(string message){MessageBox.Show(message, "網絡錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);status.BackColor = Color.Red;}}
}
?讀取?Q2.2
byte[] buffer = new byte[3]; // 分配3字節的緩沖區
int result = ABRead(2, 3, buffer); // 從Q2.0讀取3字節
?
if (result == 0) // 假設0表示成功
{
? ? // 成功讀取后處理buffer中的數據
? ? bool y22 = S7.GetBitAt(buffer, 0, 2); // 讀取第0字節的第2位(對應Q2.2)
? ? if (y22)
? ? {
? ? ? ? hslconveyer1.conveyeractive = true;
? ? }
}
else
{
? ? // 處理錯誤(如記錄日志或拋出異常)
? ? Console.WriteLine($"讀取失敗,錯誤代碼: {result}");
}
?讀取 I0.0
?#region
?//讀取DI數據
?var S7MULVAR = new S7MultiVar(Clinet);
?var buffer = new byte[9];
?S7MULVAR.Add(S7Consts.S7AreaPE, S7Consts.S7WLByte, 0, 0, buffer.Length, ref buffer);
?S7MULVAR.Read();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
? bool X0 = S7.GetBitAt(buffer, 0, 0);//讀取I0.0的狀態
??if (X0)
?{
? ? ?L11.LanternBackground = Color.Yellow;?
?}
?#endregion
//讀取db數據
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #region
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? byte[] buffersD = new byte[20];
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Clinet.DBRead(8, 0, 20, buffersD);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // double db8dbd10 = S7.GetLRealAt(buffersD, 10);//對應數據類型LReal,DB8的第10個字節數據
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? float db8dbd10 = S7.GetRealAt(buffersD, 10);//;//對應數據類型Real,DB8的第10個字節數據
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? label15.Text = db8dbd10.ToString();//
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #endregion
改進后可實時更新數據顯示的代碼:
using Sharp7;
using System;
using System.Drawing;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;namespace _1200PLC
{public partial class Form1 : Form{private delegate void UpdateUIDelegate(bool qState, bool iState, double db8dbd10);private delegate void UpdateStatusDelegate(bool connected);private delegate void ShowErrorDelegate(string message);private bool _isRunning = true;private S7Client _client; // 使用下劃線前綴表示私有字段public Form1(){InitializeComponent();_client = new S7Client();// 啟動后臺線程var thread = new Thread(ThreadBackgroundStation){IsBackground = true,Priority = ThreadPriority.Highest};thread.Start();}private void Form1_FormClosing(object sender, FormClosingEventArgs e){_isRunning = false;if (_client != null && _client.Connected){_client.Disconnect();}}private void ThreadBackgroundStation(){int result = _client.ConnectTo("192.168.10.2", 0, 1);if (result == 0){UpdateConnectionStatus(true);while (_isRunning){try{if (!_client.Connected){result = _client.ConnectTo("192.168.10.2", 0, 1);if (result != 0){UpdateConnectionStatus(false);Thread.Sleep(1000);continue;}UpdateConnectionStatus(true);}// 讀取輸入區域byte[] ibuffer = new byte[1];if (_client.ReadArea(S7Consts.S7AreaPE, 0, 0, 1, S7Consts.S7WLByte, ibuffer) == 0){bool iState = S7.GetBitAt(ibuffer, 0, 0);bool qState = false;double db8dbd10 = 0.0;// 讀取輸出區域byte[] qbuffer = new byte[1];if (_client.ReadArea(S7Consts.S7AreaPA, 0, 0, 1, S7Consts.S7WLByte, qbuffer) == 0){qState = S7.GetBitAt(qbuffer, 0, 0);}// 讀取DI數據var multiVar = new S7MultiVar(_client);var diBuffer = new byte[9];multiVar.Add(S7Consts.S7AreaPE, S7Consts.S7WLByte, 0, 0, diBuffer.Length, ref diBuffer);multiVar.Read();bool x0 = S7.GetBitAt(diBuffer, 0, 0);//UpdateUI(() => L11.LanternBackground = x0 ? Color.Yellow : SystemColors.Control);// 讀取DO數據var doBuffer = new byte[8];_client.ABRead(0, 1, doBuffer);bool y0 = S7.GetBitAt(doBuffer, 0, 0);UpdateUI(() => BTQ0.BackColor = y0 ? Color.Yellow : SystemColors.Control);// 讀取DB數據byte[] dbBuffer = new byte[20];if (_client.DBRead(8, 0, 20, dbBuffer) == 0){db8dbd10 = S7.GetLRealAt(dbBuffer, 10);}// 更新UIUpdateStateUI(qState, iState, db8dbd10);}else{UpdateConnectionStatus(false);}Thread.Sleep(100); // 適當延遲}catch (SocketException ex){ShowNetworkError($"網絡連接斷開: {ex.Message}");UpdateConnectionStatus(false);Thread.Sleep(1000);}catch (Exception ex){ShowNetworkError($"發生錯誤: {ex.Message}");UpdateConnectionStatus(false);Thread.Sleep(1000);}}_client.Disconnect();}else{ShowNetworkError("無法連接到 PLC,請檢查網絡連接!");UpdateConnectionStatus(false);}}private void UpdateStateUI(bool qState, bool iState, double db8dbd10){if (InvokeRequired){Invoke(new UpdateUIDelegate(UpdateStateUI), qState, iState, db8dbd10);return;}label2.Text = qState ? "Q0.0 is ON" : "Q0.0 is OFF";labelIState.Text = iState ? "I0.0 is ON" : "I0.0 is OFF";label15.Text = db8dbd10.ToString();Console.WriteLine($"DB8.DBD10: {db8dbd10}");}private void UpdateConnectionStatus(bool connected){if (InvokeRequired){Invoke(new UpdateStatusDelegate(UpdateConnectionStatus), connected);return;}status.BackColor = connected ? Color.Green : Color.Red;statusS7.BackColor = connected ? Color.YellowGreen : Color.Red;}private void ShowNetworkError(string message){if (InvokeRequired){Invoke(new ShowErrorDelegate(ShowNetworkError), message);return;}MessageBox.Show(message, "網絡錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);}// 輔助方法簡化UI更新private void UpdateUI(Action uiAction){if (InvokeRequired){Invoke(uiAction);}else{uiAction();}}}
}
注意事項:?
添加引用:1----復制文件到路徑文件夾。2---添加引用,瀏覽,選中文件,確認。
報錯? warning MSB3274: 未能解析主引用“Sharp7, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL”,因為它是針對“.NETFramework,Version=v4.8”框架生成的。該框架版本高于當前目標框架“.NETFramework,Version=v4.7.2”。
問題出在項目目標框架和 Sharp7 庫的目標框架不匹配。具體來說,Sharp7 庫是針對 .NET Framework 4.8 構建的,而你的項目目標框架是 .NET Framework 4.7.2。
解決方案
你有幾個選擇來解決這個問題:
更改項目目標框架
將項目的目標框架更改為 .NET Framework 4.8,以便與 Sharp7 庫兼容。
在 Visual Studio 中,右鍵點擊項目,選擇“屬性”。
在“應用程序”選項卡中,找到“目標框架”下拉菜單。
選擇 .NET Framework 4.8。
保存更改并重新生成項目。
運行效果:? ?變量和數據實時更新?