S7.Net.dll文件支持西门子所有PLC的通讯,本人通过几个星期的测试,搞懂了他的使用方法,并写了一个库函数,已经应用到多个系统中。该库里PLC类型里没有S7-200Smart类型,所有很多人不知道怎么通过S7.net与S7-200SmartPLC通信,实际上要想跟SmartPLC通信,用PLC类型选S7-1200,读取V区变量用DB1表示,其他的跟读取S7-1200一样了。具体测试代码如下。如果想了解具体怎么使用的可以下载上面的DOME,如果想知道具体的使用方法,控制的注意事项,以及如何控制可以加QQ:470300759咨询,下面只是简单的测试程序,本人有实际的项目程序和模板程序在闲鱼有售,欢迎咨询。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using S7.Net; //与西门子PLC建立连接的开源代码库,开源社区中可以找到该库,VS中联网就可以搜索到
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
bool status=false;
Plc plc1 = new Plc(CpuType.S71200, "192.168.6.1", 0, 1);
public Form1()
{
InitializeComponent();
}
//连接到PLC
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
plc1.OpenAsync();
status = true;
toolStripStatusLabel1.Text ="正在连接" + plc1.IP ;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
foreach (var readdata in ReadMultipleBytes(13, 1, 0)) //读取VB0开始的13个字节
{
textBox1.Text = textBox1.Text + readdata+" ";
} ;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (status)
{
if (plc1.IsConnected)
{
toolStripStatusLabel1.ForeColor = Color.Black;
toolStripStatusLabel1.Text = plc1.IP + " 已成功连接 ";
}
else
{
toolStripStatusLabel1.ForeColor = Color.Red;
toolStripStatusLabel1.Text = plc1.IP + " 连接连接断开";
}
}
}
private List
{
List
int index = startByteAdr;
while (numBytes > 0)
{
var maxToRead = (int)Math.Min(numBytes, 200);
byte[] bytes = plc1.ReadBytes(DataType.DataBlock, db, index, (int)maxToRead);
if (bytes == null)
return new List
resultBytes.AddRange(bytes);
numBytes -= maxToRead;
index += maxToRead;
}
return resultBytes;
}
private void timer2_Tick(object sender, EventArgs e)
{
try
{
byte[] bytes = plc1.ReadBytes(DataType.DataBlock, 1, 0, 1);
if (bytes == null)
{
status = false;
plc1.OpenAsync();
toolStripStatusLabel1.Text = "正在连接" + plc1.IP;
}
else
status = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
plc1.Close();
}
}
}