C#S7协议通讯西门子PLC,读写宽字符串(WSTRING)

在网上没找到关于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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值