读取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。
保存更改并重新生成项目。
运行效果: 变量和数据实时更新