在网上没找到关于wstring的读写m免费代码,自己摸索自己写的代码
写
// PLC连接参数
string plcIp = "192.168.0.100"; // PLC的IP地址
short plcRack = 0; // PLC的机架号
short plcSlot = 1; // PLC的槽位号
Plc plc = new Plc(CpuType.S71200, plcIp, plcRack, plcSlot);
plc.Open();
string strToWrite = "你好";
WriteWString(plc, 2000, 0, strToWrite);
plc.Close();
WriteWString()方法
static void WriteWString(Plc plc, short dbNumber, ushort offsetAddress, string value)
{
if (string.IsNullOrEmpty(value)) throw new ArgumentException("字符串不能为空");
// 每个字符为两个字节,WString实际上是字的组合
// 第一个字是最大长度(字)
// 第二个字是实际长度(字)
ushort maxLength = (ushort)(value.Length); // 实际字符数
ushort byteCount = (ushort)(maxLength * 2); // 字节数
// 字节数组长度: 最大长度WORD(2字节) + 实际长度WORD(2字节) + 每个字符的字节数
byte[] buffer = new byte[byteCount + 4];
// 最大长度
buffer[0] = (byte)(maxLength >> 8); // 高字节
buffer[1] = (byte)(maxLength & 0xFF); // 低字节
// 实际长度
buffer[2] = (byte)(maxLength >> 8); // 高字节
buffer[3] = (byte)(maxLength & 0xFF); // 低字节
// 将字符串写入字节数组,转换为Unicode编码
for (int i = 0; i < maxLength; i++)
{
ushort character = (ushort)value[i];
buffer[4 + (i * 2)] = (byte)(character >> 8); // 高字节
buffer[5 + (i * 2)] = (byte)(character & 0xFF); // 低字节
}
// 写入PLC
plc.Write($"DB{dbNumber}.DBW{offsetAddress}", buffer);
Console.WriteLine($"写入到DB{dbNumber}.{offsetAddress} 完成");
}
读
string plcIp = "192.168.0.100"; // PLC的IP地址
short plcRack = 0; // PLC的机架号
short plcSlot = 1; // PLC的槽位号
Plc plc = new Plc(CpuType.S71200, plcIp, plcRack, plcSlot);
plc.Open();
int start = 2;
string res = "";
int num = int.Parse(plc.Read("DB2000.DBW2").ToString());
for (int i = 0; i < num; i++)
{
start += 2;
res += Convert.ToChar(plc.Read("DB2000.DBW" + start));
}
Console.WriteLine(res);
Console.ReadLine();
plc.Close();
plcDB