S7.Net.DLL类库与西门子S7-200Smart的通讯和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 SiemensTest
{
public partial class S7_200SmartCommunicationTest : Form
{
public S7_200SmartCommunicationTest()
{
InitializeComponent();
}
Plc plc;//声明plc连接对象
///
/// 连接plc
///
/// /// private void btnConnect_Click(object sender, EventArgs e)
{
string TypeName = txtPLCType.Text;//PLC型号名称
string Ip = txtIp.Text;//plcIp地址
switch (TypeName)
{
case "200":
case "1200":
/*S7.Net.dll类库中没有S7-200Smart类型,想跟S7-200Smart通讯选择S71200即可*/
plc = new Plc(CpuType.S71200, Ip, 0, 2);//创建plc实例
break;
case "300":
plc = new Plc(CpuType.S7300, Ip, 0, 2);//创建plc实例
break;
case "400":
plc = new Plc(CpuType.S7400, Ip, 0, 2);//创建plc实例
break;
case "1500":
plc = new Plc(CpuType.S71500, Ip, 0, 2);//创建plc实例
break;
}
plc.Open();//连接plc
if (plc.IsConnected)//检查plc是否连接上
{
//连接成功
}
else
{
//连接失败
}
}
///
/// 给plc指定寄存地址写入数据
///
/// /// private void btnWrite_Click(object sender, EventArgs e)
{
string address = txtAddress.Text;//寄存地址
string writedata = txtWriteData.Text;//写入数据
/*
检查plc的可用性,检查此属性时,回向plc发送ping命令,如果plc响应ping则返回true,否则返回false.
*/
if (plc.IsAvailable)
{
plc.Write(address,writedata);
}
else
{
//连接失败
}
}
///
/// 读取单个plc数据
///
/// /// private void btnReadSingleData_Click(object sender, EventArgs e)
{
string address = txtAddress2.Text;//寄存地址
/*
检查plc的可用性,检查此属性时,回向plc发送ping命令,如果plc响应ping则返回true,否则返回false.
*/
if (plc.IsAvailable)
{
var bytes = plc.Read(address);
txtReadSingleData.Text = bytes.ToString();
}
else
{
//连接失败
}
}
///
/// 读取多个plc数据,最多读取200个,超过则需要使用递归
///
/// /// private void btnReadMultipleData_Click(object sender, EventArgs e)
{
txtReadMultipleData.Clear();//清空文本框数据
int AddressType = Convert.ToInt16(txtAddRessType.Text);//地址类型
int Address = Convert.ToInt16(txtAddRess3.Text);//寄存地址
int ReadCount = Convert.ToInt16(txtReadCount.Text);//读取个数
var bytes = plc.ReadBytes(DataType.DataBlock, AddressType, Address, ReadCount);
for (int i = 0; i < bytes.Count(); i++)
{
txtReadMultipleData.AppendText(bytes[i].ToString() + "
");
}
}
///
/// 递归读取数据
///
/// /// /// ///
private List ReadMultipleBytes(int numBytes, int db, int startByteAdr = 0)
{
List resultBytes = new List();
int index = startByteAdr;
while (numBytes > 0)
{
var maxToRead = (int)Math.Min(numBytes, 200);
byte[] bytes = plc.ReadBytes(DataType.DataBlock, db, index, (int)maxToRead);
if (bytes == null)
return new List();
resultBytes.AddRange(bytes);
numBytes -= maxToRead;
index += maxToRead;
}
return resultBytes;
}
}
}