public static bool checkBuf(byte[] bb)
        {
            ModbusCRC16 crc16 = new ModbusCRC16();

            crc16.update(bb, bb.Length - 2);
            int ri = crc16.getValue();

            if (bb[bb.Length - 1] == (byte)(ri & 0xff) &&
                bb[bb.Length - 2] == (byte)((0xff00 & ri) >> 8))
            {
                return(true);
            }
            return(false);
        }
        //将16进制的字符串转换为带有CRC校验的字节型数组的方法
        public static byte[] getSendBuf(String toSend)
        {
            toSend = toSend.Replace(" ", "");

            byte[]      bb    = HexString2Buf(toSend);
            ModbusCRC16 crc16 = new ModbusCRC16();

            crc16.update(bb, bb.Length - 2);
            int ri = crc16.getValue();

            bb[bb.Length - 1] = (byte)(0xff & ri);
            bb[bb.Length - 2] = (byte)((0xff00 & ri) >> 8);
            return(bb);
        }
Пример #3
0
        private void btnSendCRC_Click(object sender, EventArgs e)
        {
            //发送前判断串口是否打开
            if (!serialPort.IsOpen)
            {
                MessageBox.Show("请先打开串口!", "提示信息",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //判断cbTimeSend是否被勾选,来决定是否启动Timer控件进行定时发送
            if (cbTimeSend.Checked)
            {
                timeSend.Enabled = true;
            }
            else
            {
                timeSend.Enabled = false;
            }

            if (rbSend16.Checked == true)
            {
                try
                {
                    //如果以16进制带CRC校验形式发送,调用ModbusCRC16的方法将16进制字符串转换为带CRC的字节数组
                    byte[] byteBuffer = ModbusCRC16.getSendBuf(txtSend.Text);

                    serialPort.Write(byteBuffer, 0, byteBuffer.Length);

                    SendMessage(ByteToHex(byteBuffer));
                }
                catch (Exception ex)
                {
                    MessageBox.Show("16进制数的格式或长度不正确,请检查格式后重新发送。\n" + ex.Message, "信息提示",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("请选择数据发送的格式!", "信息提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }