using System;
using System.IO.Ports;
using System.Text;
public class SerialPortHelper
{
public delegate void HanderInterfaceUpdataDelegate(string sendData);
private static SerialPort _port;
private static readonly object lockHelper = new object();
public static SerialPort SerialPortIns
{
get
{
if (_port == null)
{
lock (lockHelper)
{
_port = new SerialPort();
}
}
return _port;
}
}
/// <summary>
/// 打开串口
/// </summary>
/// <param name="portName">端口</param>
/// <param name="baudRate">波特率</param>
/// <param name="parity">奇偶校验检查协议</param>
/// <param name="stopBits">每个字节的标准停止位数</param>
public static SerialPort ConnectSerialPort(string portName, int baudRate, Parity parity, StopBits stopBits,int dataBits, Handshake handShake)
{
try
{
_port = new SerialPort();
//端口
_port.PortName = portName;
//波特率
_port.BaudRate = baudRate;
//奇偶校验检查协议
_port.Parity = parity;
//每个字节的标准停止位数
_port.StopBits = stopBits;
//数据位
_port.DataBits = dataBits;
//握手协议
_port.Handshake = handShake;
//打开串口
if (!_port.IsOpen)
{
_port.Open();
}
return _port;
}
catch (System.Exception ex)
{
return null;
}
}
/// <summary>
/// 关闭串口
/// </summary>
public static void CloseSerialPort(SerialPort port)
{
if (port.IsOpen)
{
port.Close();
}
_port = null;
}
/// <summary>
/// 接收数据
/// </summary>
/// <param name="port"></param>
public static string ReceiveData(SerialPort port)
{
//Thread.Sleep(1000);
var i = port.BytesToRead;
byte[] bytes = new byte[i];
port.Read(bytes, 0, i);
string str = Encoding.Default.GetString(bytes);
return str;
}
public static string ReceiveDataByLine(SerialPort port)
{
return port.ReadTo("\r\n");
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="port"></param>
/// <param name="text"></param>
public static void SendBytesData(SerialPort port, string text)
{
port.Write(text);
}
}
c#串口通讯
最新推荐文章于 2024-08-14 12:02:23 发布