C#引用S7netplus库通过网络读写西门子S7_200_SMART点位
S7netplus
https://github.com/S7NetPlus/s7netplus
开源,免费,无点位数限制,无运行时长限制。
-
新建C#项目,由于S7netplus库原因,选择.net 4.5.2及以上版本
-
安装S7netplus
3.引用库
4、连接、回读、写入
Plc plc1;//新建对象
plc1 = new Plc(CpuType.S71200, "192.168.0.200",0,1); //连接,内置没有200 Smart,型号选S1200,使其兼容
plc1.Open(); //打开连接
//M7.0 置为1
plc1.WriteBit(DataType.Memory, 0, 7, 0, true);
//M7.0 复位为0
plc1.WriteBit(DataType.Memory, 0, 7, 0, false);
//回读状态
byte[] D = plc1.ReadBytes(DataType.Memory,0,7,1);
bool[] B = Bytes2Bools(D);
if (B[0])//M7.0
{
button25.BackColor = Color.Green;
}else{
button25.BackColor = Color.Red;
}
//函数,实现功能:字节数组转换为位数组
private bool[] Bytes2Bools(byte[] data)
{
int len = data.Length;
bool[] newBit = new bool[len * 8];
int MidByt;
for (int i = 0; i < len; i++)
{
MidByt = data[i];
for (int j = 0; j < 8; j++)
{
newBit[i * 8 + j] = Convert.ToBoolean(MidByt % 2);
MidByt = MidByt / 2;
}
}
return newBit;
}
5.运行