1

我有一个连接到 FSR 的 arduino 板正在运行。它应该返回有关当前压力的信息。此数据通过 COM5 传输,然后应在我的 c# 程序中进行解析。传感器将返回 0 到 1023 之间的值。

这是我的 Arduino 代码(可能不重要)

int FSR_Pin = A0; //analog pin 0

void setup(){
  Serial.begin(9600);
}

void loop(){
  int FSRReading = analogRead(FSR_Pin); 

  Serial.println(FSRReading);
  delay(250); //just here to slow down the output for easier reading
}

我的 C# 串行端口阅读器如下所示:

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#中的相同场景

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

我对串行端口完全没有经验,但看起来流是......“异步”......就像还有另一个字节要读取但接收器不会意识到这一点。

我能做些什么呢?

4

1 回答 1

3

你得到的答案被截断了(比如553become 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()应该吃\n来自 COM 端口的数据。

于 2013-09-17T11:20:16.243 回答