PLC侧设置:
和校验+协议4
读D200单字: 05 30 30 46 46 57 52 30 44 30 32 30 30 30 31 返回“201”:02 30 30 46 46 30 30 43 39 03
- 1 private void ReadOrder(string Add)
- 2 {
- 3 Byte[] sendData = new Byte[20];
- 4 sendData[0] = 0x05; //ENQ
- 5 sendData[1] = 0x30; //站号
- 6 sendData[2] = 0x30;
- 7 sendData[3] = 0x46; //PC号
- 8 sendData[4] = 0x46;
- 9 sendData[5] = 0x57; //命令 “WR” 57 52
- 10 sendData[6] = 0x52;
- 11 sendData[7] = 0x30; //报文等待
- 12 sendData[8] = (byte)Convert.ToChar(Add[0]); //起始软元件 “D0200”
- 13 sendData[9] = (byte)Convert.ToChar(Add[1]);
- 14 sendData[10] = (byte)Convert.ToChar(Add[2]);
- 15 sendData[11] = (byte)Convert.ToChar(Add[3]);
- 16 sendData[12] = (byte)Convert.ToChar(Add[4]);
- 17 sendData[13] = 0x30; //软元件点数 默认“01”
- 18 sendData[14] = 0x31;
- 19 int allInt = 0;
- 20 for (int i = 1; i <= 14; i++)
- 21 {
- 22 allInt += (int)sendData[i]; //进行和校验
- 23 }
- 24 string allStrX = allInt.ToString("X"); //转换成十六进制
- 25 sendData[15] = (byte)Convert.ToChar(allStrX.Substring(allStrX.Length - 2, 1)); //提取十六进制倒数第二位的ASCII值
- 26 sendData[16] = (byte)Convert.ToChar(allStrX.Substring(allStrX.Length - 1, 1)); //提取十六进制倒数第一位的ASCII值
- 27 sendData[17] = 0x0D; //CR
- 28 sendData[18] = 0x0A; //LF
- 29 this.PLC_SendData(sendData);
- 30 }
写1到D100: 05 30 30 46 46 57 57 30 44 30 31 30 30 30 31 30 30 30 31 返回:06 30 30 46 46
- 1 private void WriteOrder(string Add,string Con)
- 2 {
- 3 Byte[] sendData = new Byte[20];
- 4 sendData[0] = 0x05; //ENQ
- 5 sendData[1] = 0x30; //站号
- 6 sendData[2] = 0x30;
- 7 sendData[3] = 0x46; //PC号
- 8 sendData[4] = 0x46;
- 9 sendData[5] = 0x57; //命令 “WR” 57 57
- 10 sendData[6] = 0x57;
- 11 sendData[7] = 0x30; //报文等待
- 12 sendData[8] = (byte)Convert.ToChar(Add[0]); //起始软元件 “D0100”
- 13 sendData[9] = (byte)Convert.ToChar(Add[1]);
- 14 sendData[10] = (byte)Convert.ToChar(Add[2]);
- 15 sendData[11] = (byte)Convert.ToChar(Add[3]);
- 16 sendData[12] = (byte)Convert.ToChar(Add[4]);
- 17 sendData[13] = 0x30; //软元件点数 默认“01”
- 18 sendData[14] = 0x31;
- 19 sendData[15] = (byte)Convert.ToChar(Con[0]); //内容 “0001”
- 20 sendData[16] = (byte)Convert.ToChar(Con[1]);
- 21 sendData[17] = (byte)Convert.ToChar(Con[2]);
- 22 sendData[18] = (byte)Convert.ToChar(Con[3]);
- 23 int allInt = 0;
- 24 for (int i = 1; i <= 18; i++)
- 25 {
- 26 allInt += (int)sendData[i]; //进行和校验
- 27 }
- 28 string allStrX = allInt.ToString("X"); //转换成十六进制
- 29 sendData[19] = (byte)Convert.ToChar(allStrX.Substring(allStrX.Length - 2, 1)); //提取十六进制倒数第二位的ASCII值
- 30 sendData[20] = (byte)Convert.ToChar(allStrX.Substring(allStrX.Length - 1, 1)); //提取十六进制倒数第一位的ASCII值
- 31 sendData[21] = 0x0D; //CR
- 32 sendData[22] = 0x0A; //LF
- 33 this.PLC_SendData(sendData);
- 34 }