当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Reading from Serial Port returns wrong values

问题描述:

I have an arduino board running which is connected to an FSR. It should return information about the current pressure. This data is transmitted through COM5 and should then be parsed in my c# program. The sensor will return values between 0 and 1023.

This is my Arduino Code (may be not important)

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 looks like this:

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());

}

}

}

In this case I press the sensor and release it

Console Output on arduino:

0

285

507

578

648

686

727

740

763

780

785

481

231

91

The same scenario in c#

0

55

3

61

1

6

46

666

676

68

4

69

5

6

34

480

78

12

I have absolutely no experience with Serial Ports but it looks like the stream is...."asynchronous" ... like there is another byte to read but the receiver won't realize this.

What can I do about this?

网友答案:

You get the answer truncated (like 553 becoming 55\n3) because you print as soon as DataReceived is raised, which can happen before the end of the line.

Instead, you should used ReadLine() in a loop:

Console.WriteLine("Incoming Data:");

port.Open();

while (true)
{
    string line = port.ReadLine();

    if (line == null) // stream closed ?
        break;

    Console.WriteLine(line);
}

port.Close();

This should also solve the double line break issue because ReadLine() should eat the \n coming from the COM port.

分享给朋友:
您可能感兴趣的文章:
随机阅读: