接上一篇,我们连接PLC并握手成功,并且封装生成读写PLC的命令
C#使用TCP-S7协议读写西门子PLC(三)-CSDN博客
public OperateResult
public OperateResult WriteSerialData(PlcRegisterCategory plcRegisterCategory, ushort offsetAddress, ushort dbNumber, byte[] data)
public OperateResult
public OperateResult WriteData
public OperateResult
public OperateResult WriteSerialRealArray(PlcRegisterCategory plcRegisterCategory, ushort offsetAddress, ushort dbNumber, float[] realArray)
public OperateResult DB_WriteString(ushort dbNumber, ushort offsetAddress, int maxLength, string writeString)
public OperateResult
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlcSiemesS7Demo
{
///
/// 综合读写S7协议操作,
/// 所有读操作都统一使用方法:ReadSerialData(PlcRegisterCategory plcRegisterCategory, ushort offsetAddress, ushort dbNumber, int readByteCount)
/// 所有写操作都统一使用方法:WriteSerialData(PlcRegisterCategory plcRegisterCategory, ushort offsetAddress, ushort dbNumber, byte[] data)
///
public partial class SiemensS7ProtocolUtil
{
///
/// 读取任意连续字节数据,因西门子PLC的每个DB块的最大偏移量是65535,因此最多读取65536个字节数据
/// 任意多个Byte读取--每次最多读取200个字节,如果超过200,自动分多次读取
///
///
///
///
///
///
public OperateResult ReadSerialData(PlcRegisterCategory plcRegisterCategory, ushort offsetAddress, ushort dbNumber, int readByteCount)
{
byte[] destArray = new byte[readByteCount];
int pageSize = (readByteCount + 199) / 200;
for (int i = 0; i < pageSize; i++)
{
int byteCount = 200;//每次读取200个字节
if (i + 1 == pageSize) //最后一次读取剩余字节
{
byteCount = readByteCount - 200 * i;
}
OperateResult resultAddress = AnalysisAddress(plcRegisterCategory, offsetAddress, dbNumber);
OperateResult operateResult = Read(new OperateResult[] { resultAddress }, new ushort[] { (ushort)byteCount });
if (!operateResult.IsSuccess)
{
return operateResult;
}
Array.Copy(operateResult.Content, 0, destArray, 200 * i, byteCount);
offsetAddress += 200;
}
return OperateResult.CreateSuccessResult(destArray);
}
///
/// 写入任意连续的字节数组,每次写入400个字节,如果多于400个,分多次写入
/// 因西门子PLC的每个DB块的最大偏移量是65535,因此最多写入65536个字节数据
///
///
///
///