3
votes

So, I am trying to read data from the serial port to communicate with an Arduino. Here is the code I am using:

    public partial class Form1 : Form
{
    SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);

    public Form1()
    {
        InitializeComponent();
        port.Open();
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
    }


    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        this.Invoke(new EventHandler(DoUpDate));
    }

    private void DoUpDate(object s, EventArgs e)
    {
        textBox1.AppendText(port.ReadLine() + "\r\n");
    }
}

But the result I get in the textBox is (check the picture):

enter image description here

The value read should be 975 but I got separated values as well as many empty lines.

Any help is apperciated.

EDIT#1:

Here is the Arduino code:

int sensorPin=A0;
int sensorValue=0;

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

void loop()
{
  sensorValue=analogRead(sensorPin);
  Serial.print(sensorValue);
  Serial.print("\n");
}

And here is the result when I click on the serial reader within arduino IDE (which what C# code should show)

enter image description here

EDIT#2

After thinking more about the problem, I think that the C# code is very fast that it is reading uncomplete data but I don't have a solution for it, do you know anything I can try to solve it?

2
where's the arduino code that sends that data?Piglet
@Piglet I haved added it in the op. Please check it.Forenkazan1
Try subscribing to the ErrorReceived event and see if any errors are occurring.SteelSoul

2 Answers

0
votes

I'm not fluent in C#, but maybe you should wait for data to be in the Serial buffer before trying to read them. A method for that is to use port.ReadExisting() as it can be seen here!

Hope it helps!

0
votes

Insert a 20ms delay in your loop()