C#编程与1200PLC S7通信
读取q0.0的状态,i0.0的状态实时在窗口更新
PLC里写一个程序 用常闭按钮接i0.0信号 ,延时接通Q0.0
测试效果
程序前提是引用了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;}}
}