涉及技术:
1.使用NMdbus4 库
2.ushort[]转int
记得之前刚学习的时候,是ushort[] → Hex字符串→byte[] → 翻转byte[] →BitConverter.ToInt32(),饶了一大圈;实际上可以直接转;这里也有小细节:使用BitConverter之前要翻转字节数组,因为BitConverter是小端存储处理方式;
这些方法我都有记录,参见:
C#使用串口或其他通信接收到的字节数据处理方式-CSDN博客
C#short 、ushort、 byte、 byte[]转换分析_c# ushort-CSDN博客
1.使用NModbus4 注意事项:

1.地址参数为ushort类型,原因可能在这:

2.一个寄存器是16位,只能保存16位数据,有些时候要读出来32位的数据,就要连着读两个寄存器;
3.返回数据是ushort[]类型,如果读的是16位数据,结果就是一个长度的ushort数组,读32位的话结果就是长度为2的ushort数组.....
4.ushort[]与int互转:
cs
public static ushort[] Int2Ushorts(int res)
{
ushort ust1 = (ushort)(res >> 16);
ushort ust2 = (ushort)res;
return new ushort[] { ust1, ust2 };
}
public static int UShorts2Int(ushort[] res)
{
//如果确定长度的话,一行代码 : return (int)result[0] << 16 | (int)result[1];
if (res.Length > 1)
{
int high = res[0];
int low = res[1];
int value = (high << 16) + low;
return value;
}
return (int)res[0];
}
后面想起来再补充。