格式
/// <summary>
/// 数据格式:0-6位:报文头;7位:功能码;8-9位:起始地址;10-11位:寄存器位数(读)/写入数据(写)
/// </summary>
byte[] data = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x06, 0x00, 0x00, 0x00, 0x01 };
// 0 1 2 3 4 5 6:ID,7:功能码 8 9 10 11
.....................
byte[] func = GetHex(textBox2.Text);//功能码
byte[] addr = GetAddrHex(textBox3.Text);//起始地址
byte[] regis = GetHex(textBox4.Text);//写入数据,读取寄存器数量
data[7] = func[0];
data[8] = addr[1];
data[9] = addr[0];
data[10] = regis[1];
data[11] = regis[0];
类型转换
....................................
/// <summary>
/// 10转16
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
private byte[] GetHex(string msg)
{
ushort val = ushort.Parse(msg);
byte[] hex = BitConverter.GetBytes(val);
return hex;
}
private byte[] GetAddrHex(string msg)
{
int val = int.Parse(msg)-1;
byte[] hex = BitConverter.GetBytes(val);
return hex;
}
网友评论