这里写一种,COM口的数据接收,发送方法。
1.COMHelper类
1 /// <summary>初始化串行端口</summary> 2 private SerialPort _serialPort; 3 4 public SerialPort serialPort 5 { 6 get { return _serialPort; } 7 set { _serialPort = value; } 8 } 9 10 /// <summary> 11 /// COM口通信构造函数 12 /// </summary> 13 /// <param name="PortID">通信端口</param> 14 /// <param name="baudRate">波特率</param> 15 /// <param name="parity">奇偶校验位</param> 16 /// <param name="dataBits">标准数据位长度</param> 17 /// <param name="stopBits">每个字节的标准停止位数</param> 18 /// <param name="readTimeout">获取或设置读取操作未完成时发生超时之前的毫秒数</param> 19 /// <param name="writeTimeout">获取或设置写入操作未完成时发生超时之前的毫秒数</param> 20 public ComHelper(string PortID, int baudRate, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One, int readTimeout = 100, int writeTimeout = 100) 21 { 22 try 23 { 24 serialPort = new SerialPort(); 25 serialPort.PortName = "COM" + PortID;//通信端口 26 serialPort.BaudRate = baudRate;//波特率 27 serialPort.Encoding = Encoding.ASCII; 28 serialPort.Parity = parity;//奇偶校验位 29 serialPort.DataBits = dataBits;//标准数据位长度 30 serialPort.StopBits = stopBits;//每个字节的标准停止位数 31 serialPort.ReadTimeout = readTimeout;//获取或设置读取操作未完成时发生超时之前的毫秒数 32 serialPort.WriteTimeout = writeTimeout;//获取或设置写入操作未完成时发生超时之前的毫秒数 33 } 34 catch (Exception ex) { throw new Exception(ex.Message); } 35 } 36 37 /// <summary> 38 /// 打开COM口 39 /// </summary> 40 /// <returns>true 打开成功;false 打开失败;</returns> 41 public bool Open() 42 { 43 try 44 { 45 if (serialPort.IsOpen == false) 46 { 47 serialPort.Open(); 48 return true; 49 } 50 } 51 catch (Exception ex) 52 { 53 LogImpl.Debug(ex.ToString()); 54 } 55 return false; 56 } 57 58 /// <summary> 59 /// 关闭COM口 60 /// </summary> 61 /// <returns>true 关闭成功;false 关闭失败;</returns> 62 public bool Close() 63 { 64 try 65 { 66 serialPort.Close(); 67 return true; 68 } 69 catch 70 { 71 return false; 72 } 73 } 74 75 /// <summary> 76 /// 判断端口是否打开 77 /// </summary> 78 /// <returns></returns> 79 public bool IsOpen() 80 { 81 try 82 { 83 return serialPort.IsOpen; 84 } 85 catch { throw; } 86 } 87 88 /// <summary> 89 /// 向COM口发送信息 90 /// </summary> 91 /// <param name="sendData">16进制的字节</param> 92 public void WriteData(byte[] sendData) 93 { 94 try 95 { 96 if (IsOpen()) 97 { 98 Thread.Sleep(5); 99 serialPort.Write(sendData, 0, sendData.Length); 100 } 101 } 102 catch { throw; } 103 } 104 105 /// <summary> 106 /// 接收来自COM的信息 107 /// </summary> 108 /// <returns>返回收到信息的数组</returns> 109 public string[] ReceiveDataArray() 110 { 111 112 try 113 { 114 Thread.Sleep(5); 115 if (!serialPort.IsOpen) return null; 116 int DataLength = serialPort.BytesToRead; 117 byte[] ds = new byte[DataLength]; 118 int bytecount = serialPort.Read(ds, 0, DataLength); 119 return ByteToStringArry(ds); 120 } 121 catch (Exception ex) 122 { 123 LogImpl.Debug(""+ex.ToString()); 124 throw; 125 } 126 } 127 128 /// <summary> 129 /// 把字节型转换成十六进制字符串 130 /// </summary> 131 /// <param name="bytes"></param> 132 /// <returns></returns> 133 public static string[] ByteToStringArry(byte[] bytes) 134 { 135 try 136 { 137 string[] strArry = new string[bytes.Length]; 138 for (int i = 0; i < bytes.Length; i++) 139 { 140 strArry[i] = String.Format("{0:X2} ", bytes[i]).Trim(); 141 } 142 return strArry; 143 } 144 catch { throw; } 145 } 146 147 /// <summary> 148 /// 清除缓存数据 149 /// </summary> 150 public void ClearDataInBuffer() 151 { 152 try 153 { 154 serialPort.DiscardInBuffer(); 155 serialPort.DiscardOutBuffer(); 156 } 157 catch { throw; } 158 } 159 160 161 162 /// <summary> 163 /// 注册 数据接收事件,在接收到数据时 触发 164 /// </summary> 165 /// <param name="serialPort_DataReceived"></param> 166 public void AddReceiveEventHanlder(SerialPortDataReceivedDelegate serialPort_DataReceived) 167 { 168 try 169 { 170 serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived); 171 } 172 catch { throw; } 173 } 174 175 //接收事件是否有效 true开始接收,false停止接收。默认true 176 177 public static bool ReceiveEventFlag = true; 178 /// <summary> 179 /// 接收数据触发,将接收的数据,通过一个定义的数据接收事件,传递出去。 180 /// </summary> 181 /// <param name="sender"></param> 182 /// <param name="e"></param> 183 public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) 184 { 185 if (ReceiveEventFlag == false) 186 { 187 return; 188 } 189 string strReceive = ReceiveDataString(); 190 if (!string.IsNullOrEmpty(strReceive)) 191 { 192 OnReceiveDataHanlder(new ReceiveEventArgs() { ReceiveData = strReceive }); 193 } 194 } 195 196 #region 数据接收事件 197 public event EventHandler<ReceiveEventArgs> ReceiveDataHandler; 198 199 protected void OnReceiveDataHanlder(ReceiveEventArgs e) 200 { 201 EventHandler<ReceiveEventArgs> handler = ReceiveDataHandler; 202 if (handler != null) handler(this, e); 203 } 204 #endregion
这个helper类,没多少东西,一般也够用了,主要就是,读取,写入。
2.页面或其他地方使用
1 public ComHelper comHelp; 2 3 string PortID = System.Configuration.ConfigurationManager.AppSettings["PeopleAdr"]; 4 int baudRate = 9600; 5 int dataBits = 8; 6 System.IO.Ports.StopBits oStopBits = System.IO.Ports.StopBits.One; 7 //无奇偶校验位 8 System.IO.Ports.Parity oParity = System.IO.Ports.Parity.None; 9 int ReadTimeout = 100; 10 int WriteTimeout = -1; 11 comHelp = new ComHelper(PortID, baudRate, oParity, dataBits, oStopBits, ReadTimeout, WriteTimeout); 12 if (!comHelp.IsOpen()) comHelp.Open(); 13 14 comHelp.AddReceiveEventHanlder(comHelp.serialPort_DataReceived);//将接收到数据,处理数据的方法注册进去 15 comHelp.ReceiveDataHandler += new EventHandler<ReceiveEventArgs>(rds_ReceiveDataHandler);//将传递接收数据的方法注册进去,如果接收到数据,触发事件,自动存串口数据。 16 17 public string strComReciveData = "";//从COM口接收到的数据,如果接收到数据,通过事件触发,会自动有值。 18 void rds_ReceiveDataHandler(object sender, ReceiveEventArgs e) 19 { 20 try 21 { 22 strComReciveData = e.ReceiveData; 23 Thread.Sleep(200); 24 //清空缓存 25 comHelp.ClearDataInBuffer(); 26 } 27 catch (Exception ex) 28 { 29 LogImpl.Debug(ex.ToString()); 30 Thread.Sleep(200); 31 } 32 }
这是写入数据,就简单多了。
byte[] send = new byte[] { 0x7F, 0x02, 0x8F }; comHelp.WriteData(send);