111,129
社区成员
发帖
与我相关
我的任务
分享
List<byte> arr = new List<byte>();
while (true)
{
if (serialPort1.BytesToRead > 0)
{
arr.Add((byte)serialPort1.ReadByte());
if (arr.Count > 2)
{
int len = arr.Count;
if (arr[len - 1] == 255 && arr[len - 2] == 255)
{
break;
}
}
}
}
/*
* 处理arr
*/
arr.Clear();
public partial class Form1 : Form
{
delegate void del();
public Form1()
{
InitializeComponent();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
this.Invoke(new del(A));
}
private void A()
{
if (serialPort1.BytesToRead == 9)
{
byte[] buffer = new byte[serialPort1.BytesToRead];
serialPort1.Read(buffer, 0, serialPort1.BytesToRead);
string str=Encoding.ASCII.GetString(buffer);
richTextBox1.AppendText(str);
}
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.Open();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
}
}