我在电脑上运行程序的时候 发现读取不到串口,串口是正常的,用其他的工具就可以读到,我是电脑本身有问题吗
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)
{
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();
}
}
}