今日终于到了winform上位机与西门子PLC网口通信的系列收为阶段了,一直没一口气更新完,手头上也没有可以测试用的PLC设备,虚拟仿真用到的博图软件也不想下载(会让我电脑变卡)。
于是等了些日子购买西门子PLC(S7200_SMART),目前还是没彻底明白
主要知识点有:IP地址填写检查方法、读取写入方法、西门子PLC变量地址与类型的关系
文章提供测试代码讲解、参数效果贴出、整体工程下载
以下为效果预览:
目录
头部相关提示:
检查IP地址并连接PLC函数方法:
在按键函数中调用:
简单读取与写入操作:
西门子PLC变量地址与类型的关系:
读取与写入操作:
类型接口:
读取:
写入:
部分效果展示:
所有代码贴出:
form1代码:
MainForm设计代码:
Program.cs代码:
整体工程下载:
网上查阅资料贴出网址:
头部相关提示:
添加必要的通信实例化、添加必要的变量,以防下方代码有不懂的变量:
检查IP地址并连接PLC函数方法:
之前的按键连接PLC操作只是做了相关界面提示,并未添加实际的通信库函数方法,这里先添加以下函数方法,用于实现PC与PLC的连接尝试:
之前没有检验IP地址填写是否正确的函数方法,这里添加一下:
//检查IP地址、并连接PLC的方法,并做出操作提示系统连接是否成功private bool check_IP_And_Connect(){bool blnTest;//定义 接收 检查文本组件IP地址填写规范 string address = txt_IP.Text.Trim();//读取文本组件中的IP地址,(IP未与枚举绑定,是用户直接填写的),自动移除空白//CPU_Type cpu = CPU_Type.S7200SMART;//选择CPUCPU_Type cpu = (xktComm.Common.CPU_Type)Enum.Parse(typeof(xktComm.Common.CPU_Type), cmb_CPUType.SelectedItem.ToString());//选择CPU//Regex regex = new Regex("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$");/* 创建一个正则表达式对象,用于匹配特定格式的字符串^: 表示字符串的开始。[0-9]{1,3}: 匹配1到3个数字。这表示IPv4地址中的每一个段可以有1到3位数字。.: 匹配实际的点字符(.)。在正则表达式中,.是一个特殊字符,代表匹配任何单个字符,所以在这里需要使用\进行转义,即\.。但在你给出的代码中,并没有转义,这可能是一个错误。[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}: 这部分重复了三次,意味着整个模式匹配四个由点分隔的数字段。$: 表示字符串的结束。*/Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");blnTest = regex.IsMatch(txt_IP.Text);//检查文本组件IP地址填写规范if (blnTest){string[] strTemp = this.txt_IP.Text.Split(new char[] { '.' });for (int i = 0; i < strTemp.Length; i++){if (Convert.ToInt32(strTemp[i]) > 255){ //大于255则提示,不符合IP格式MessageBox.Show("不符合IP格式");return false;}}}else{//输入非数字则提示,不符合IP格式MessageBox.Show("不符合IP格式");return false;}//尝试连接和接收连接是否成功的反馈isconnected = objS7.Connect(address, cpu, 0, 1);if (isconnected){MessageBox.Show("链接成功"); return true;}else{MessageBox.Show("链接失败"); return false;}}
在按键函数中调用:
这里改进了连接断开连接的按键逻辑,使其更符合实际设计情况:
添加了断开连接的实际函数:
//连接/断开PLCprivate void btn_Connect_Click(object sender, EventArgs e){//连接PLCif (button1_Clickf == true){btn_Connect.Text = "断开PLC";btn_Connect.BackColor = Color.Red;button1_Clickf = false;check_IP_And_Connect();//检查IP并连接PLCmyaddlog(isconnected ? 1 : 0, isconnected ? "PLC连接成功" : "连接PLC失败");//写日志//如果连接失败了,就回到连接PLC选项状态if(isconnected==false){btn_Connect.Text = "连接PLC";btn_Connect.BackColor = SystemColors.ActiveCaption;button1_Clickf = true;}}//断开PLC else if (button1_Clickf == false){btn_Connect.Text = "连接PLC";btn_Connect.BackColor = SystemColors.ActiveCaption;button1_Clickf = true;objS7?.DisConnect();isconnected = false;myaddlog(2, "PLC已经断开连接");}}
简单读取与写入操作:
private void btnread_Click(object sender, EventArgs e){textBox2.Text = ss.Read(textBox1.Text, 0).ToString();}private void btnwrite_Click(object sender, EventArgs e){ss.Write(textBox3.Text, Convert.ToBoolean(textBox4.Text));}
西门子PLC变量地址与类型的关系:
西门子PLC变量所在的地址是能够反映变量的大致类型的:
DB1.DBX0.0 BOOL类型
DB1.DBB0 BYTE类型
DB1.DBW0 SHORT/USHORT类型
DB1.DBD0 INT/UINT/FLOAT类型
读取与写入操作:
类型接口:
public class SiemensVariable{public StoreType dataType { get; set; }public int DBNo { get; set; }public int StartByte { get; set; }}
读取:
//读取private void btn_Read_Click(object sender, EventArgs e){//检查与PLC的连接if (!isconnected){ myaddlog(0, "请检查与PLC的连接"); return; }//读取地址与CPUVarType vartype = (VarType)Enum.Parse(typeof(VarType), cmb_VarType.SelectedItem.ToString());string address = this.txt_Variable.Text.Trim();object value = 0;int length = -1;//枚举只有比优特与string类型需要特殊对待区分:switch (vartype){case VarType.Byte:if (int.TryParse(this.txt_Length.Text, out length)){SiemensVariable var = AnalyseAddress(address);if (var != null){byte[] b = objS7.ReadBytes(var.dataType, var.DBNo, var.StartByte, length);if (b != null){myaddlog(1, address + "读取成功" + ByteArrayToString(b));}else{myaddlog(0, "读取失败,请检查PLC连接");}}else{myaddlog(0, "读取失败,请检查PLC变量地址或变量类型");}}else{myaddlog(0, "读取失败,长度应该为正整数");}break;case VarType.String:if (int.TryParse(this.txt_Length.Text, out length)){SiemensVariable var = AnalyseAddress(address);if (var != null){byte[] b = objS7.ReadBytes(var.dataType, var.DBNo, var.StartByte, length);if (b != null){myaddlog(1, address + "读取成功" + Encoding.ASCII.GetString(b));}else{myaddlog(0, "读取失败,请检查PLC连接");}}else{myaddlog(0, "读取失败,请检查PLC变量地址或变量类型");}}else{myaddlog(0, "读取失败,长度应该为正整数");}break;default:value = objS7.Read(address, vartype);if (value != null){myaddlog(1, address + "读取成功" + value);}else{myaddlog(0, "读取失败,请检查PLC变量地址或变量类型");}break;}}private SiemensVariable AnalyseAddress(string Address){SiemensVariable var = new SiemensVariable();if (Address.Contains(".")){string[] str = Address.Split('.');if (str.Length == 2){var.dataType = StoreType.DataBlock;var.DBNo = Convert.ToInt32(str[0].Substring(2));var.StartByte = Convert.ToInt32(str[1].Substring(str[1].IndexOf(str[1].First(c => char.IsDigit(c)))));}else{return null;}}else{switch (Address.Substring(0, 1).ToLower()){case "i":var.dataType = StoreType.Input;break;case "q":var.dataType = StoreType.Input;break;case "m":var.dataType = StoreType.Input;break;default:break;}var.DBNo = 0;var.StartByte = Convert.ToInt32(Address.Substring(2));}return var;}
写入:
//写入private void btn_Write_Click(object sender, EventArgs e){if (!isconnected){myaddlog(0, "请检查与PLC的连接");return;}string Address = this.txt_Variable.Text.Trim();string SetText = this.txt_SetValue.Text.Trim();object setValue = 0;VarType vartype = (VarType)Enum.Parse(typeof(VarType), cmb_VarType.SelectedItem.ToString());try{switch (vartype){case VarType.Bit:setValue = SetText == "1" || SetText == "true";break;case VarType.Byte:setValue = Convert.ToByte(SetText);break;case VarType.Word:setValue = Convert.ToUInt16(SetText);break;case VarType.DWord:setValue = Convert.ToUInt32(SetText);break;case VarType.Int:setValue = Convert.ToInt16(SetText);break;case VarType.DInt:setValue = Convert.ToInt32(SetText);break;case VarType.Real:setValue = Convert.ToSingle(SetText);break;case VarType.String:setValue = SetText;break;case VarType.Timer:setValue = SetText;break;case VarType.Counter:setValue = SetText;break;default:break;}}catch (Exception){myaddlog(0, "写入失败,请检查PLC变量地址、类型或写入数据值");}if (objS7.Write(Address, setValue)){myaddlog(1, Address + "写入成功" + this.txt_SetValue.Text.Trim());}else{myaddlog(0, "写入失败,请检查PLC变量地址或变量类型");}}
部分效果展示:
没有条件实际连接PLC进行测试,这里展示部分效果:
连接失败:
不符合IP格式:
表单关闭:
写入错误(未连接PLC):
读取错误(未连接PLC):
所有代码贴出:
form1代码:
以下为form1的设计与代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using xktComm;
using xktComm.Common;namespace xktComm_Siemens_YZH
{//info 表示报警级别 ,log 表示报警信息public delegate void AddLog(int info, string log);public partial class Form1 : Form{//创建这个窗体的addlog ,需要绑定一个实际方法private AddLog myaddlog;//xktComm.SiemensS7 ss = new SiemensS7();//实例化 xktComm.SiemensS7 objS7 = new xktComm.SiemensS7();//创建通信对象bool button1_Clickf = true;//连接/断链PLC按键的 双态转换bool Form1_FClosing = false;//用于防止二次Form1_FormClosing()事件发生的bool isconnected = false;//标记是否连接//表单初始化的类public Form1(){InitializeComponent();this.Load += Form1_Load1;myaddlog=this.AddLog;//绑定方法}//表单初始化private void Form1_Load1(object sender, EventArgs e){this.cmb_CPUType.DataSource = Enum.GetNames(typeof(xktComm.Common.CPU_Type));this.cmb_VarType.DataSource = Enum.GetNames(typeof(xktComm.Common.VarType));//设置第一列的宽度=整个宽度 减去 第0页宽度lstInfo.Columns[1].Width = lstInfo.ClientSize.Width - lstInfo.Columns[0].Width;}//表单初始化private void Form1_Load(object sender, EventArgs e){}/*首先判断是否需要通过Invoke调用该方法。如果不需要,则直接执行下面的代码。创建一个ListViewItem对象lst,用于存储日志信息。使用DateTime.Now.ToString(“yyyy/MM/dd HH:mm:ss”)获取当前时间,并将其添加到lst中。将Log参数添加到lst的子项中。将lst插入到lstInfo控件的第一个位置。如果需要通过Invoke调用该方法,则使用Action委托和Invoke方法来执行相同的操作。*///写入日志委托方法//创建委托private void AddLog(int info, string Log){if (!lstInfo.InvokeRequired){//创建ListViewItem ,将时间与info放进去ListViewItem lst = new ListViewItem(" " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), info);lst.SubItems.Add(Log);lstInfo.Items.Insert(0, lst);}else{Invoke(new Action(() =>{ ListViewItem lst = new ListViewItem(" " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), info);lst.SubItems.Add(Log);lstInfo.Items.Insert(0, lst);}));}}//第二个参数需要我们调用方法函数将combox的值转换回枚举类型//isconnected=SiemensS7.Connect(this.txt_IP.Text.Trim(),Enum.Parse(typeof(CPU_Type),cmb_CPUType.SelectedItem.ToString()),);//连接/断开PLCprivate void btn_Connect_Click(object sender, EventArgs e){//连接PLCif (button1_Clickf == true){btn_Connect.Text = "断开PLC";btn_Connect.BackColor = Color.Red;button1_Clickf = false;check_IP_And_Connect();//检查IP并连接PLCmyaddlog(isconnected ? 1 : 0, isconnected ? "PLC连接成功" : "连接PLC失败");//写日志//如果连接失败了,就回到连接PLC选项状态if(isconnected==false){btn_Connect.Text = "连接PLC";btn_Connect.BackColor = SystemColors.ActiveCaption;button1_Clickf = true;}}//断开PLC else if (button1_Clickf == false){btn_Connect.Text = "连接PLC";btn_Connect.BackColor = SystemColors.ActiveCaption;button1_Clickf = true;objS7?.DisConnect();isconnected = false;myaddlog(2, "PLC已经断开连接");}}//检查IP地址、并连接PLC的方法,并做出操作提示系统连接是否成功private bool check_IP_And_Connect(){bool blnTest;//定义 接收 检查文本组件IP地址填写规范 string address = txt_IP.Text.Trim();//读取文本组件中的IP地址,(IP未与枚举绑定,是用户直接填写的),自动移除空白//CPU_Type cpu = CPU_Type.S7200SMART;//选择CPUCPU_Type cpu = (xktComm.Common.CPU_Type)Enum.Parse(typeof(xktComm.Common.CPU_Type), cmb_CPUType.SelectedItem.ToString());//选择CPU//Regex regex = new Regex("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$");/* 创建一个正则表达式对象,用于匹配特定格式的字符串^: 表示字符串的开始。[0-9]{1,3}: 匹配1到3个数字。这表示IPv4地址中的每一个段可以有1到3位数字。.: 匹配实际的点字符(.)。在正则表达式中,.是一个特殊字符,代表匹配任何单个字符,所以在这里需要使用\进行转义,即\.。但在你给出的代码中,并没有转义,这可能是一个错误。[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}: 这部分重复了三次,意味着整个模式匹配四个由点分隔的数字段。$: 表示字符串的结束。*/Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");blnTest = regex.IsMatch(txt_IP.Text);//检查文本组件IP地址填写规范if (blnTest){string[] strTemp = this.txt_IP.Text.Split(new char[] { '.' });for (int i = 0; i < strTemp.Length; i++){if (Convert.ToInt32(strTemp[i]) > 255){ //大于255则提示,不符合IP格式MessageBox.Show("不符合IP格式");return false;}}}else{//输入非数字则提示,不符合IP格式MessageBox.Show("不符合IP格式");return false;}//尝试连接和接收连接是否成功的反馈isconnected = objS7.Connect(address, cpu, 0, 1);if (isconnected){MessageBox.Show("链接成功"); return true;}else{MessageBox.Show("链接失败"); return false;}}//字节数组转成16进制字符串private string ByteArrayToString(byte[] b){string result = string.Empty;foreach (var item in b){result += item.ToString("X2") + " ";}return result.Trim();}//数据类型变变换private void Cmb_VarType_SelectedIndexChanged(object sender, EventArgs e){if (this.cmb_VarType.SelectedIndex == 1 || this.cmb_VarType.SelectedIndex == 7){this.txt_Length.Enabled = true;}else{this.txt_Length.Enabled = false;}}//private void btn_Read_Click(object sender, EventArgs e)//{ }//读取private void btn_Read_Click(object sender, EventArgs e){//检查与PLC的连接if (!isconnected){ myaddlog(0, "请检查与PLC的连接"); return; }//读取地址与CPUVarType vartype = (VarType)Enum.Parse(typeof(VarType), cmb_VarType.SelectedItem.ToString());string address = this.txt_Variable.Text.Trim();object value = 0;int length = -1;//枚举只有比优特与string类型需要特殊对待区分:switch (vartype){case VarType.Byte:if (int.TryParse(this.txt_Length.Text, out length)){SiemensVariable var = AnalyseAddress(address);if (var != null){byte[] b = objS7.ReadBytes(var.dataType, var.DBNo, var.StartByte, length);if (b != null){myaddlog(1, address + "读取成功" + ByteArrayToString(b));}else{myaddlog(0, "读取失败,请检查PLC连接");}}else{myaddlog(0, "读取失败,请检查PLC变量地址或变量类型");}}else{myaddlog(0, "读取失败,长度应该为正整数");}break;case VarType.String:if (int.TryParse(this.txt_Length.Text, out length)){SiemensVariable var = AnalyseAddress(address);if (var != null){byte[] b = objS7.ReadBytes(var.dataType, var.DBNo, var.StartByte, length);if (b != null){myaddlog(1, address + "读取成功" + Encoding.ASCII.GetString(b));}else{myaddlog(0, "读取失败,请检查PLC连接");}}else{myaddlog(0, "读取失败,请检查PLC变量地址或变量类型");}}else{myaddlog(0, "读取失败,长度应该为正整数");}break;default:value = objS7.Read(address, vartype);if (value != null){myaddlog(1, address + "读取成功" + value);}else{myaddlog(0, "读取失败,请检查PLC变量地址或变量类型");}break;}}//分析地址数据private SiemensVariable AnalyseAddress(string Address){SiemensVariable var = new SiemensVariable();if (Address.Contains(".")){string[] str = Address.Split('.');if (str.Length == 2){var.dataType = StoreType.DataBlock;var.DBNo = Convert.ToInt32(str[0].Substring(2));var.StartByte = Convert.ToInt32(str[1].Substring(str[1].IndexOf(str[1].First(c => char.IsDigit(c)))));}else{return null;}}else{switch (Address.Substring(0, 1).ToLower()){case "i":var.dataType = StoreType.Input;break;case "q":var.dataType = StoreType.Input;break;case "m":var.dataType = StoreType.Input;break;default:break;}var.DBNo = 0;var.StartByte = Convert.ToInt32(Address.Substring(2));}return var;}//类型接口public class SiemensVariable{public StoreType dataType { get; set; }public int DBNo { get; set; }public int StartByte { get; set; }}//写入private void btn_Write_Click(object sender, EventArgs e){if (!isconnected){myaddlog(0, "请检查与PLC的连接");return;}string Address = this.txt_Variable.Text.Trim();string SetText = this.txt_SetValue.Text.Trim();object setValue = 0;VarType vartype = (VarType)Enum.Parse(typeof(VarType), cmb_VarType.SelectedItem.ToString());try{switch (vartype){case VarType.Bit:setValue = SetText == "1" || SetText == "true";break;case VarType.Byte:setValue = Convert.ToByte(SetText);break;case VarType.Word:setValue = Convert.ToUInt16(SetText);break;case VarType.DWord:setValue = Convert.ToUInt32(SetText);break;case VarType.Int:setValue = Convert.ToInt16(SetText);break;case VarType.DInt:setValue = Convert.ToInt32(SetText);break;case VarType.Real:setValue = Convert.ToSingle(SetText);break;case VarType.String:setValue = SetText;break;case VarType.Timer:setValue = SetText;break;case VarType.Counter:setValue = SetText;break;default:break;}}catch (Exception){myaddlog(0, "写入失败,请检查PLC变量地址、类型或写入数据值");}if (objS7.Write(Address, setValue)){myaddlog(1, Address + "写入成功" + this.txt_SetValue.Text.Trim());}else{myaddlog(0, "写入失败,请检查PLC变量地址或变量类型");}}//CPU类型private void cmb_CPUType_SelectedIndexChanged(object sender, EventArgs e){}//变量类型private void cmb_VarType_SelectedIndexChanged_1(object sender, EventArgs e){}//IP地址private void txt_IP_TextChanged(object sender, EventArgs e){}//变量地址private void txt_Variable_TextChanged(object sender, EventArgs e){}//读取长度private void txt_Length_TextChanged(object sender, EventArgs e){}//写入数值private void txt_SetValue_TextChanged(object sender, EventArgs e){}}
}
MainForm设计代码:
以下为mainform的设计与代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace xktComm_Siemens_YZH
{public partial class MainForm : Form{bool button1_cg = false;bool MainForm_FClosing = false;public MainForm(){InitializeComponent();}private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e){}private void MainForm_Load(object sender, EventArgs e){}//添加窗体实例进Tabpage中public void Add_TabPage(string str, Form myForm) //将标题添加进tabpage中{if (!this.tabControlCheckHave(this.tabControl1, str)){this.tabControl1.TabPages.Add(str);this.tabControl1.SelectTab((int)(this.tabControl1.TabPages.Count - 1));myForm.FormBorderStyle = FormBorderStyle.None;myForm.TopLevel = false;myForm.Show();myForm.Parent = this.tabControl1.SelectedTab;}}public bool tabControlCheckHave(TabControl tab, string tabName) //看tabpage中是否已有窗体{for (int i = 0; i < tab.TabCount; i++){if (tab.TabPages[i].Text == tabName){tab.SelectedIndex = i;return true;}}return false;}//private void button1_Click(object sender, EventArgs e){//第一次点击会将 Form1()添加进Tabcontrol中if (button1_cg==false){button1_cg = true;Add_TabPage("西门子", new Form1());}//第二次就会清除所有标签页else if(button1_cg==true){button1_cg = false;// 假设你的TabControl的名字是tabControl1// 清除所有的标签页while (tabControl1.TabPages.Count > 0){tabControl1.TabPages.RemoveAt(0);}}}private void MainForm_FormClosing_1(object sender, FormClosingEventArgs e){if (MainForm_FClosing == false){if (MessageBox.Show("此操作将关闭窗口,请问是否继续?", "询问", MessageBoxButtons.YesNo) == DialogResult.Yes){e.Cancel = false;MainForm_FClosing = true;Application.Exit();}else{e.Cancel = true;}}else{Application.Exit();}}}}
Program.cs代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;namespace xktComm_Siemens_YZH
{internal static class Program{/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new MainForm());}}
}
整体工程下载:
https://download.csdn.net/download/qq_64257614/89149088
网上查阅资料贴出网址:
文章学习借鉴了网上个位大佬的思想,这里专门贴出出处,一起学习借鉴:
c#与西门子smart200联合使用_xktcomm-CSDN博客