gpt4 book ai didi

C# - SerialPort.ReadLine() 卡住我的程序

转载 作者:行者123 更新时间:2023-12-03 20:30:23 25 4
gpt4 key购买 nike

我正在尝试使用波特率 9600 通过串行端口读取从我的 Arduino 发送的消息。

我的 Arduino 代码被编程为每当我按下按钮时发送“1”,当我松开手指时发送“0”。

所以它不是不断地发送数据。

我的 C# 程序是读取该消息并将其添加到 ListBox。但是每当我启动它时,程序就会挂起。

private void button1_Click(object sender, EventArgs e)
{
SerialPort port = new SerialPort();
port.BaudRate = 9600;
port.PortName = "COM4";
port.ReadTimeout = 1000;
port.Open();


timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
try
{
ee = port.ReadLine();
listBox1.Items.Add(ee);
}
catch (Exception)
{
timer1.Stop();
}
}

我想,也许原因是我的程序应该在接收之前检查是否有可用的数据接收?

最佳答案

尝试这样的事情。它至少不会挂起,然后您可以通过 DataReceived 整理出您获得的数据类型。

从那里您可以确定如何更好地编写您的应用程序

private void button1_Click(object sender, EventArgs e)
{
SerialPort port = new SerialPort();
port.BaudRate = 9600;
port.PortName = "COM4";
port.ReadTimeout = 1000;

// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);

// Begin communications
port.Open();
}

private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer in the output window
Debug.WriteLine("data : " + port.ReadExisting());
}

SerialPort.DataReceived Event

Indicates that data has been received through a port represented by the SerialPort object.



SerialPort.ReadExisting Method ()

Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.

关于C# - SerialPort.ReadLine() 卡住我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49445252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com