我的串口工具每次读取一个字节的16进制数据 ,我想判断我读取的数据满足8个字节的时候,就传给一个变量 然后打印到textBox1上面,我该如何写
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolBar;
namespace danzijie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(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 hex;
CheckForIllegalCrossThreadCalls = false;
byte ReceiveData;
ReceiveData = (byte)serialPort1.ReadByte();
string str = Convert.ToString(ReceiveData, 16).ToUpper();
StreamWriter sw = new StreamWriter(@"C:\Users\g'x'r\Desktop\jieshou.txt", true);//写入文件夹
if (str.Length != 2)
{
str += 0;
}
else if (str == "68")
{
if (str.Length<=8)
{
hex = str + str;
textBox1.Text = hex;
}
}
sw.Write(str);
sw.Close();
}
}
}