C# 从串行端口读取返回错误的值
我有一个arduino板正在运行,它连接到FSR。它应该返回有关当前压力的信息。这些数据通过COM5传输,然后在我的c#程序中解析。传感器将返回0和1023之间的值 这是我的Arduino代码(可能不重要) 我的C#串行端口读取器如下所示:C# 从串行端口读取返回错误的值,c#,event-handling,serial-port,arduino,C#,Event Handling,Serial Port,Arduino,我有一个arduino板正在运行,它连接到FSR。它应该返回有关当前压力的信息。这些数据通过COM5传输,然后在我的c#程序中解析。传感器将返回0和1023之间的值 这是我的Arduino代码(可能不重要) 我的C#串行端口读取器如下所示: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Ports; using System.Windows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
namespace Serial_Reader
{
class Program
{
// Create the serial port with basic settings
SerialPort port = new SerialPort("COM5",
9600);
static void Main(string[] args)
{
new Program();
}
Program()
{
Console.WriteLine("Incoming Data:");
// 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();
// Enter an application loop to keep this thread alive
Application.Run();
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
}
在这种情况下,我按下传感器并将其释放
arduino上的控制台输出:
0
0
0
0
285
507
578
648
686
727
740
763
780
785
481
231
91
0
0
0
0
0
c中的相同场景#
我绝对没有使用串行端口的经验,但它看起来是…异步的。。。就像有另一个字节要读取,但接收器不会意识到这一点
对此我能做些什么?您会得到截断的答案(比如
553
变成55\n3
),因为您会在发出DataReceived
后立即打印,这可能发生在行尾之前
相反,您应该在循环中使用ReadLine()
:
Console.WriteLine("Incoming Data:");
port.Open();
while (true)
{
string line = port.ReadLine();
if (line == null) // stream closed ?
break;
Console.WriteLine(line);
}
port.Close();
这还可以解决双线中断问题,因为
ReadLine()
应该吃掉来自COM端口的\n
。您好,我已经尝试使用ReadLine,我的行代码总是空的。但是当我在python中使用串口时,它是有效的。你知道为什么会这样吗?
0
0
0
0
55
3
61
1
6
46
666
676
68
4
69
5
6
34
480
78
12
0
0
0
0
Console.WriteLine("Incoming Data:");
port.Open();
while (true)
{
string line = port.ReadLine();
if (line == null) // stream closed ?
break;
Console.WriteLine(line);
}
port.Close();