串口接收数据的时候,textbox1 只显示了2位数据,在写入文件只写入了8位数据 我发送的68 20 DF 68 02 02 35 41 49 16 我希望显示我发送的所有数据
以下是我的代码 希望在我的代码上进行修改,并标明注释,如果按照需求可以正常运行 我会采纳
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.Net;
using System.Net.NetworkInformation;
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 xiaoniu
{
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 Button4_Click(object sender, EventArgs e) //全选所有功能
{
RadioButton5.Checked = true;
checkBox1.Checked = true;
checkBox2.Checked = true;
}
private void RadioButton5_CheckedChanged(object sender, EventArgs e) //控制器类
{
}
private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) //串口类
{
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);//写入文件夹
textBox1.Text = str;
sw.Write(str);
sw.Close();
}
}
}