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):
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)
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?