S7.NET开源库的质料说明支持的PLC是:S7-200,S7-1200,S7-1500,S7-300 ,S7-400
好像不支持SMART ,
经测试C#使用S7.NET可以与SMART通信。将图片及源码分享出来供大家参考,初学C#代码有点乱。
几点注意事项:
1,与SMART通信时选择PLC类型 选的是S7-1200,机架号是 0,插槽号是 1
2,读写 V 区数据使用的是DB1
源程序代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using S7.Net;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
bool status=false;
public Form1()
{
InitializeComponent();
}
Plc plc1 = new Plc(CpuType.S71200, "192.168.1.10", 0, 1);
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
plc1.OpenAsync();
status = true;
toolStripStatusLabel2.Text ="正在连接" + plc1.IP ;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
foreach (var readdata in ReadMultipleBytes(13, 1, 0))
{
try
{
textBox1.Text = textBox1.Text + readdata+" ";
}
catch
{
;
}
} ;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (status)
{
if (plc1.IsConnected)
{
toolStripStatusLabel2.ForeColor = Color.Black;
toolStripStatusLabel2.Text = plc1.IP + " 已成功连接 ";
}
else
{
toolStripStatusLabel2.ForeColor = Color.Red;
toolStripStatusLabel2.Text = plc1.IP + " 连接连接断开";
}
}
}
private void toolStripStatusLabel1_Click(object sender, EventArgs e)
{
}
private List<byte> ReadMultipleBytes(int numBytes, int db, int startByteAdr = 5)
{
List<byte> resultBytes = new List<byte>();
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<byte>();
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();
toolStripStatusLabel2.Text = "正在连接" + plc1.IP;
}
else
status = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
plc1.Close();
}
}
}
附件:
WindowsFormsApplication4.rar
s7netplus-develop.zip