赞
踩
项目添加应用HslCommunication.dll和代码代码如下(示例):
dll官方支持网站>
using HslCommunication.Profinet.Siemens;
## 2.定义全局变量,选择PLC类型,设置正确的IP地址
代码如下:
` public static string PlcIpAddress = "192.168.101.50";
public static SiemensPLCS siemensPLCS = SiemensPLCS.S1200;
public static SiemensS7Net siemensTcpNet = null;
代码如下:
public static bool InitialPLC()
{
int k = 0;
tryAgain:
try
{
System.Net.IPAddress address;
if (!System.Net.IPAddress.TryParse(PublicVariables.PlcIpAddress, out address))
{
MessageBox.Show("Ip地址输入不正确!");
return false;
}
//SiemensPLCS siemensPLCS = SiemensPLCS.S1200;
PublicVariables.siemensTcpNet = new SiemensS7Net(PublicVariables.siemensPLCS);
PublicVariables.siemensTcpNet.IpAddress = PublicVariables.PlcIpAddress;
OperateResult connect = PublicVariables.siemensTcpNet.ConnectServer();
if (!connect.IsSuccess)
{
return false;
}
return true;
}
catch (Exception ex)
{
k++;
if (k < 4)
{
Thread.Sleep(50);
goto tryAgain;
}
else
{
return false;
}
}
}
-## 4.数据DB块写入–
/// <summary>
/// 统一的数据写入的结果显示
/// </summary>
/// <param name="result"></param>
/// <param name="address"></param>
public static void writeResultRender(OperateResult result, string address)
{
//Thread.Sleep(200);
if (result.IsSuccess)
{
//MessageBox.Show(DateTime.Now.ToString("[HH:mm:ss] ") + $"[{address}] 写入成功");
}
else
{
MessageBox.Show(DateTime.Now.ToString("[HH:mm:ss] ") + $"[{address}] 写入失败{Environment.NewLine}原因:{result.ToMessageShowString()}");
}
}
##4.1 写入实列如下:
writeResultRender(PublicVariables.siemensTcpNet.Write("DB80.4.6", bool.Parse("true")), "DB80.4.6")
##5 bool类型读取
public OperateResult<bool> ReadBool(string address)
{
return GetBoolResultFromBytes(ReadBitFromPLC(address));
}
##6 寄存器批量读取
public override OperateResult<byte[]> Read(string address, ushort length)
{
OperateResult<byte, int, ushort> operateResult = AnalysisAddress(address);
if (!operateResult.IsSuccess)
{
return OperateResult.CreateFailedResult<byte[]>(operateResult);
}
List<byte> list = new List<byte>();
ushort num = 0;
while (num < length)
{
ushort num2 = (ushort)Math.Min(length - num, 200);
OperateResult<byte[]> operateResult2 = Read(new OperateResult<byte, int, ushort>[1] { operateResult }, new ushort[1] { num2 });
if (!operateResult2.IsSuccess)
{
return operateResult2;
}
list.AddRange(operateResult2.Content);
num = (ushort)(num + num2);
operateResult.Content2 += num2 * 8;
}
return OperateResult.CreateSuccessResult(list.ToArray());
}
以上就是今天要讲的内容,本文仅仅简单介绍了西门子工控机和西门子PLC使用S7协议通讯,而HslCommunication提供了大量工控通讯的方法。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。