串口收发的 类"/>
C# 串口收发的 类
这个是一个完整的类,经过测试,收发数据都正常
<pre name="code" class="csharp">using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;namespace zicox_print_sdk.libs
{class serial{public String debugMessage = String.Empty;public Bytes ReadBuf;public int CountBytesToRead = 0;const int ReadBufSize = 1024 * 1;private SerialPort _port;const int BAUD_RATE = 115200;const int DATA_BITS = 8;const Parity PARITY = Parity.None;const StopBits STOP_BITS = StopBits.One;const Handshake HANDSHAKE = Handshake.None;const int READ_TIMEOUT = 3000;const int WRITE_TIMEOUT = 3000;const int SLEEP = 750;public serial(int portNum){ReadBuf = new Bytes(ReadBufSize);_port = new SerialPort(String.Format("COM{0:D}",portNum),BAUD_RATE,PARITY,DATA_BITS,STOP_BITS);_port.ReadTimeout = READ_TIMEOUT;_port.WriteTimeout = WRITE_TIMEOUT;_port.DataReceived += new SerialDataReceivedEventHandler(data_received);}void data_received(object sender, SerialDataReceivedEventArgs e){debugMessage = "here";if (_port.IsOpen){int dataLength = _port.BytesToRead;byte[] data = new byte[dataLength];int nbrDataRead = _port.Read(data, 0, dataLength);if (nbrDataRead == 0)return;ReadBuf.AddBytes(data, dataLength);}}public bool read_bytes(byte[] bytes, int len, int timeOutMs){int time = 0;while (time < timeOutMs){int lenToRead = ReadBuf.m_Pos;if (lenToRead >= len){for (int i = 0; i < len; i++)bytes[i] = ReadBuf.m_ByteArry[i];return true;}Thread.Sleep(10);time += 10;}bytes[0]=0;return false;}public void send_bytes(byte[] bytes,int len){_port.Write(bytes, 0, len); }public bool is_opened(){return _port.IsOpen;}public void open(){if ((_port != null) && (_port.IsOpen == false)) _port.Open();}public void Dispose(){Dispose(true);}protected virtual void Dispose(bool disposing){if (disposing)_port.DataReceived -= new SerialDataReceivedEventHandler(data_received);if (_port != null){if (_port.IsOpen)_port.Close();_port.Dispose();}}}
}
更多推荐
C# 串口收发的 类
发布评论