private void btnWriteRegisters_Click(object sender, EventArgs e) { if (!ModbusTool.bConnect) { MessageBox.Show("请先打开串口!"); return; } txtWrong.Text = ""; try { String str = txtWrite.Text.ToString(); String data = str.Replace(" ", ""); if (data.Length % 4 != 0) { data = "000" + data; } int dataCount = data.Length / 4; int[] arr = new int[dataCount]; ushort[] uArr = new ushort[dataCount]; for (int i = dataCount; i > 0; i--) { uArr[dataCount - i] = (Convert.ToUInt16(data.Substring(data.Length - 4 * i, 4), 16)); } //for (int i = 0; i < dataCount; i++) //{ // Buffer.BlockCopy(arr, 4 * i, uArr, 4 * i, 4); //} //List<ushort> listData = new List<ushort>(); ushort startAddress; try { startAddress = Convert.ToUInt16(txtStartAddr.Text, 16); } catch (Exception) { MessageBox.Show("请输入正确的起始地址!"); return; } ModbusTool.WriteMultipleRegisters(startAddress, uArr); } catch (Exception ex) { string str = ex.Message; txtWrong.Text = ex.ToString(); } }
//发送一行数据,一行内容中包括地址和数据,如果不选择“第一列为地址”,则地址也作为数据发送 private int SendLine(int nLineId, bool bModbus, bool bWithAddress, bool bHex) { string address = ltStrAddress[nLineId - 1].Replace(" ", ""); String str = ""; String data = ""; if (ltStr.Count >= nLineId) { str = ltStr[nLineId - 1].Replace(" ", ""); } if (bWithAddress) { data = str; } else { data = address + str; //如果不选择“第一列为地址”,则地址也作为数据发送 } if (bModbus) { if (data.Length % 2 != 0) { data = "0" + data; } if (data.Length % 4 != 0) //发送以字为单位,即ushort { data = "00" + data; } int dataCount = (data.Length) / 2; ushort[] uArr = new ushort[dataCount / 2]; string subStr; for (int i = 0; i < dataCount / 2; i++) { subStr = data.Substring(4 * i, 4); uArr[i] = Convert.ToUInt16(subStr, 16); } ushort startAddress = 0; if (bWithAddress) { try { startAddress = Convert.ToUInt16(address, 16); } catch (Exception) { return(2); } } else { startAddress = RegisterAddress; } ModbusTool.WriteMultipleRegisters(startAddress, uArr); if (txtSend.Text.Length > 1000000) { txtSend.Text = ""; } if (bShowSend) { if (bWithAddress) { data = address + "," + data; } txtSend.AppendText(data + "\r\n"); txtSend.ScrollToCaret(); } } else //如果不是Modbus才考虑是否16进制发送 { if (!bHex) //ASCII码发送Excel中内容 { if (data.Length > 0) { ModbusTool.serialPort.Write(data); if (txtSend.Text.Length > 1000000) { txtSend.Text = ""; } if (bShowSend) { txtSend.AppendText(data + "\r\n"); txtSend.ScrollToCaret(); } } } else { byte[] arr = null; try { arr = StrToHexByte(data); } catch (Exception) { return(1); } if (data.Length > 0) { ModbusTool.SendAny(arr, 0, arr.Length); if (txtSend.Text.Length > 1000000) { txtSend.Text = ""; } if (bShowSend) { txtSend.AppendText(data + "\r\n"); txtSend.ScrollToCaret(); } } } } return(0); }