Reputation: 307
I'm trying to communicate with my arduino from my pc. I'm sending 1,0,0,0 in a loop and the arduino sends the received data back. However, instead of getting 1,0,0,0 back, this is what I get:
1000
1000
1000
1000
1000
1000
1000
0011
0000
0010
0100
1001
0000
0011
0000
As you can see, it works at the beginning, but starts to get weird after a few messages. Instead of sending 3 0's it sent 5. Why is that?
Here is my code:
C# Application:
class Program
{
SerialPort p;
static void Main(string[] args)
{
Program p = new Program();
p.initialize();
}
private void initialize()
{
p = new SerialPort("COM3", 115200);
p.Open();
byte[] data = { 1, 0, 0, 0 };
Thread t = new Thread(reading);
t.Start();
while(true)
{
p.Write(data, 0, data.Count());
}
Console.ReadLine();
}
private void reading()
{
while (true)
{
Console.WriteLine(p.ReadLine());
}
}
}
Arduino:
void setup()
{
Serial.begin(115200);
delay(5000);
Serial.println("Program started....");
}
void loop()
{
for (int i = 0;i<4;i++)
{
Serial.print(Serial.read());
}
Serial.println();
delay(500);
}
Upvotes: 1
Views: 2012
Reputation: 1362
I think the problem is caused by your 500 ms delay in the Arduino loop.
The PC is sending characters as fast as it can.
However the the Arduino receives 4 characters and then delays 1/2 a second (during the delay the PC could send 62,000 characters).
For a while the Arduino serial receive routine puts the characters into a buffer. But after it receives a few correctly the buffer is full and starts overwriting old characters with the new characters received.
To verify this is the problem, remove the line delay(500); from your Arduino code and add a delay to the PC after the line: p.Write(data, 0, data.Count());
Also, how does Console.ReadLine(); ever get executed since if is after your while(true) infinite loop?
Upvotes: 2