Hello,
I want to Make Serial Communication Between PC and Arduino.
I know how to send data from PC using C# to Arduino but I have few problems when I'm sending Data from Arduino to PC.
Heres My Code:
String s;
SerialPort mySerialPort;
private void Form1_Load(object sender, EventArgs e)
{
mySerialPort = new SerialPort("COM4");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
s += mySerialPort.ReadExisting().ToString();
pdata(s);
}
delegate void SetTextCallback(string text);
private void pdata(string data)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.label2.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(pdata);
this.Invoke(d, new object[]
{
data
});
}
else
{
if (data.Length >= 7)
{
this.label2.Text = "";
this.label2.Text = data;
}
}
}
The Problem is that C# dont waits Until it has received full string and it just sends characters to label1 and then clears them.
From Arduino Im sending Test String:
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println("TEST 1 2 3");
delay(1000);
Serial.println("Arduino");
delay(1000);
}
To Read Text on Arduino I'm Using this Code:
if (Serial.available() > 0)
{
int h = Serial.available();
for (int i=0;i<h;i++)
{
inData += (char)Serial.read();
}
but how to do this on C#?