C#串口通讯接收数据为16进制如下 5
展开全部
写了一个,不知道可不可以达到你的需求.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
namespace PortTestAAA
{
class Program
{
static void Main(string[] args)
{
PortOperator myTestPort = new PortOperator();
myTestPort.PortName = "COM1";
myTestPort.BaudRate = 9600;
myTestPort.DataChange += new PortOperator.DataChangeEventHandle(myTestPort_DataChange);
myTestPort.Start();
}
static void myTestPort_DataChange(object sender, byte[] data)
{
//在这里写你需要处理东西就行了
Console.WriteLine(Encoding.UTF8.GetString(data));
}
}
class PortOperator
{
public delegate void DataChangeEventHandle(object sender,byte[] data);
public event DataChangeEventHandle DataChange;
SerialPort gPort;
public string PortName { get; set; }
public int BaudRate { get; set; }
/// <summary>
/// Suspend : /ms
/// </summary>
public int Suspend { get; set; }
public PortOperator()
{
gPort = new SerialPort();
Suspend = 200;
}
void OnDataChange(byte[] data)
{
if (DataChange != null)
DataChange(this, data);
}
public void Start()
{
gPort.Close();
gPort.PortName = PortName;
gPort.BaudRate = BaudRate;
gPort.Open();
Thread thReadData = new Thread(() => { ReadData(); });
thReadData.IsBackground = true;
thReadData.Start();
}
void ReadData()
{
while (true)
{
Thread.Sleep(Suspend);
if (!gPort.IsOpen || gPort.BytesToRead < 1)
continue;
var buffer = new byte[gPort.BytesToRead];
gPort.Read(buffer, 0, buffer.Length);
OnDataChange(buffer);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
namespace PortTestAAA
{
class Program
{
static void Main(string[] args)
{
PortOperator myTestPort = new PortOperator();
myTestPort.PortName = "COM1";
myTestPort.BaudRate = 9600;
myTestPort.DataChange += new PortOperator.DataChangeEventHandle(myTestPort_DataChange);
myTestPort.Start();
}
static void myTestPort_DataChange(object sender, byte[] data)
{
//在这里写你需要处理东西就行了
Console.WriteLine(Encoding.UTF8.GetString(data));
}
}
class PortOperator
{
public delegate void DataChangeEventHandle(object sender,byte[] data);
public event DataChangeEventHandle DataChange;
SerialPort gPort;
public string PortName { get; set; }
public int BaudRate { get; set; }
/// <summary>
/// Suspend : /ms
/// </summary>
public int Suspend { get; set; }
public PortOperator()
{
gPort = new SerialPort();
Suspend = 200;
}
void OnDataChange(byte[] data)
{
if (DataChange != null)
DataChange(this, data);
}
public void Start()
{
gPort.Close();
gPort.PortName = PortName;
gPort.BaudRate = BaudRate;
gPort.Open();
Thread thReadData = new Thread(() => { ReadData(); });
thReadData.IsBackground = true;
thReadData.Start();
}
void ReadData()
{
while (true)
{
Thread.Sleep(Suspend);
if (!gPort.IsOpen || gPort.BytesToRead < 1)
continue;
var buffer = new byte[gPort.BytesToRead];
gPort.Read(buffer, 0, buffer.Length);
OnDataChange(buffer);
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询