Beispiel #1
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="sendFormat">数据格式</param>
        public void SendData(string data, SendFormat sendFormat)
        {
            if (!SerialPortObj.IsOpen)
            {
                throw new Exception("端口未打开,请打开相关端口");
            }

            byte[] byteData = null;

            switch (sendFormat)
            {
            case SendFormat.String:
                byteData = SysconvertHelper.StringToBytes(data, false);
                break;

            case SendFormat.Hex:
                if (!data.Valid_IsHex())
                {
                    throw new Exception("数据不是十六进制");
                }
                //将16进制转换为byte[]数组
                byteData = SysconvertHelper.From16ToBtyes(data);
                break;

            default:
                break;
            }

            //发送数据
            SerialPortObj.Write(byteData, 0, byteData.Length);
        }
Beispiel #2
0
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <returns></returns>
        public byte[] ReceiveData()
        {
            //定义一个接收数组,获取接收缓冲区数据的字节数
            byte[] byteData = new byte[SerialPortObj.BytesToRead];
            //读取数据
            SerialPortObj.Read(byteData, 0, SerialPortObj.BytesToRead);

            return(byteData);
        }
Beispiel #3
0
        /// <summary>
        /// 根据端口名称操作
        /// </summary>
        /// <param name="portName">端口名</param>
        /// <param name="serialPortStatus">具体操作</param>
        /// <returns></returns>
        public bool OpenSerialPort(string portName, SerialPortStatus serialPortStatus)
        {
            switch (serialPortStatus)
            {
            //打开
            case SerialPortStatus.Open:
                SerialPortObj.PortName = portName;
                SerialPortObj.Open();
                break;

            //关闭
            case SerialPortStatus.Close:
                SerialPortObj.Close();
                break;

            default:
                break;
            }

            //返回串口打开的状态
            return(SerialPortObj.IsOpen);
        }