简体   繁体   中英

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
0
0
0
285
507
578
648
686
727
740
763
780
785
481
231
91
0
0
0
0
0

The same scenario in 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM