C# 串口收发的 类

编程入门 行业动态 更新时间:2024-10-26 02:33:26

C# <a href=https://www.elefans.com/category/jswz/34/1769224.html style=串口收发的 类"/>

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# 串口收发的 类

本文发布于:2024-03-08 19:32:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1722055.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:串口   收发

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!