从串行端口读取返回错误的值

时间:2013-09-17 11:08:10

标签: c# event-handling serial-port arduino

我有一个运行的arduino板连接到FSR。它应该返回有关当前压力的信息。这些数据通过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
}

My C#Serial Port Reader如下所示:

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

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

我该怎么办?

1 个答案:

答案 0 :(得分:3)

您的答案会被截断(例如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