我写的串口工具,发现在接收了一会数据后 就停止接收了 有人知道是什么原因引起的吗
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Ck
{
public partial class Form1 : Form
{
string timeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
byte[] receiveBuffer = new byte[20];
// 声明一个变量,用于记录已经接收的数据字节数
int receivedBytes = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
button1.Text = "点击打开串口";
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.Open();
button1.Text = "点击关闭串口";
}
}
catch (Exception ex)
{
//捕获可能发生的异常并进行处理
//捕获到异常,创建一个新的对象,之前的不可以再用
serialPort1 = new System.IO.Ports.SerialPort();
//刷新COM口选项
comboBox1.Items.Clear();
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
button1.Text = "打开串口";
button1.BackColor = Color.ForestGreen;
MessageBox.Show(ex.Message);
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string abc;
// 检查是否允许跨线程调用控件,这里为了简化代码直接禁用了该功能
CheckForIllegalCrossThreadCalls = false;
// 读取所有可用字节数
int bytesToRead = serialPort1.BytesToRead;
// 如果缓冲区大小不足以存储所有的字节,则扩展缓冲区
if (receivedBytes + bytesToRead > receiveBuffer.Length)
{
Array.Resize(ref receiveBuffer, receivedBytes + bytesToRead);
}
// 将所有可用字节读取到缓冲区中
serialPort1.Read(receiveBuffer, receivedBytes, bytesToRead);
// 更新已经接收的字节数
receivedBytes += bytesToRead;
// 如果已经接收到了所有数据,则进行处理
if (receivedBytes == receiveBuffer.Length)
{
// 将接收到的数据转换为十六进制字符串
string receivedString = BitConverter.ToString(receiveBuffer).Replace("-", " ");
StreamWriter sw = new StreamWriter(@"C:\Users\guoxiaoru\Desktop\ACVB.txt", true);
sw.WriteLine(receivedString, "\n");
//对比第一字节数据
if (receivedString.Substring(0,2)=="68")
{
//截取自己想要的数据
abc = receivedString.Substring(0,30);
// 将接收到的数据显示到文本框中
textBox1.AppendText(abc + " ");
sw.WriteLine(abc, "\n");
receivedBytes = 0;
Array.Clear(receiveBuffer, 0, receiveBuffer.Length);
}
}
}
}
}