Den*_*ise 4 c# serial-port arduino readline
我正在尝试使用波特率 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想,也许原因是我的程序应该在接收之前检查是否有可用的数据接收?
尝试这样的事情。它至少不会挂起,然后您可以整理出您通过什么类型的数据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());
}
Run Code Online (Sandbox Code Playgroud)
指示已通过由 SerialPort 对象表示的端口接收到数据。
根据编码,在 SerialPort 对象的流和输入缓冲区中读取所有立即可用的字节。
| 归档时间: |
|
| 查看次数: |
3614 次 |
| 最近记录: |