图片:
简单写了个c#连接西门子PLC的小程序来练习,源代码放在下面,可以看看
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;
using S7.Net;
namespace 西门子连接上位机
{
public partial class Form1 : Form
{
public Plc Myplc;
public string IP = "192.168.1.118";//PLC的IP地址
public void Connect()//创建连接PLC方法
{
try
{
Myplc = new Plc(CpuType.S71500, IP, 0, 1);//实例化PLC对象
}
catch { MessageBox.Show("连接失败!"); }
}
public Form1()
{
InitializeComponent();
Connect();//调用连接PLC方法
}
private void button1_Click(object sender, EventArgs e)
{
if(Myplc==null)
{
MessageBox.Show("连接失败!");
return;
}
try
{
Myplc.Open();//打开PLC连接
button1.BackColor = Color.Lime;//改变按钮1颜色为绿色
button2.BackColor = Color.White;//改变按钮2颜色为白色
button1.Text = "已连接PLC";//改变按钮1文字为已连接PLC
label1.Text = "已连接到PLC";//改变label1文字为已连接到PLC
label1.Visible = true;//显示label1
}
catch { MessageBox.Show("连接失败!"); }//捕获异常
}
private void button2_Click(object sender, EventArgs e)
{
if (Myplc == null)
{
MessageBox.Show("连接失败!");//判断PLC是否连接成功
return;
}
try
{
Myplc.Close();//关闭PLC连接
button2.BackColor = Color.Lime;//改变按钮2颜色为绿色
button1.BackColor = Color.White;//改变按钮1颜色为白色
button2.Text = "已断开PLC";//改变按钮2文字为已断开PLC
label1.Visible = false;//隐藏label1
}
catch { MessageBox.Show("断开失败!"); }//捕获异常
}
private void button3_Click(object sender, EventArgs e)
{
if (Myplc == null)
{
MessageBox.Show("连接失败!");//判断PLC是否连接成功
return;
}
try
{
if ((bool)Myplc.Read("DB1.DBX0.0") == false)//判断读取的BOOL变量对按钮进行取反操作
{
Myplc.Write("DB1.DBX0.0", 1);//写入BOOL变量
button3.BackColor = Color.Lime;//改变按钮3颜色为绿色
}
else if ((bool)Myplc.Read("DB1.DBX0.0") == true)
{
Myplc.Write("DB1.DBX0.0", 0);//写入BOOL变量
button3.BackColor = Color.White;//改变按钮3颜色为白色
}
else { MessageBox.Show("读取或写入失败!"); }//捕获异常
}
catch { MessageBox.Show("读取或写入失败!"); }//捕获异常
}
}
}