I'm working on a project where I have to send some setup data from my computer (C#) to my Arduino Mega 2560. I'm focussing on the communication part now. I wrote this piece of test code. The purpose is: I send a byte with C#, the Arduino receives it, waits a second and sends it back. This is to check if I receive the same as I send.:
const int ledPin = 13;
byte input1;
void setup()
{
Serial.begin(28800);
}
void loop()
{
while(!Serial.available()) // wait until data is received
{}
input1 = Serial.read();
delay(1000);
if (input1 <128) // just a check that I don't receive random crap
{
Serial.write(input1); // send the data back to check
}
}
My problem: when I set the serial speed to 4800 or 9600, everything works fine, but when I set it to a higher value (28800 or 115200) the delay(1000); takes 5 seconds! How is this possible?
The problem must be in the Arduino, because first the RX led blinks, then 5 seconds nothing happens, and then the TX led blinks.
To me it suggests there is nothing wrong with the arduino, but rather that your C# program is not set to run at the correct baud rate - in which case there arduino recieves a series of nonsense bytes instead on 1. It processes the first and decides that it is no <128, so processes the next, and so on until presumably it gets to the fifth at which point that one happens to be <128, so it sends it back. That would account for the 5s delay.
But as you haven't said what it sends back, or what you send, it is impossible to know that for sure.
Does it work at the higher BAUD rates using the Arduino Serial monitor? (My bet is that it does). If so, then it is nothing to do with the Arduino.
If sending 1 byte causes receiving 4 bytes of crap + 1 repliable byte, and it's really related to baud rate, one of my guesses were you don't modify the sender's baud rate ?
What if you only do the delay, if you intend to reply,
or you reply always ( e.g. some error msg in case of unexpected input ),
or you simply skip that if (input1 < 128 ) check ?
const int ledPin = 13;
byte input1;
void setup()
{
Serial.begin(28800);
}
void loop()
{
while (Serial.available()) // while data is received
{
input1 = Serial.read();
if (input1 < 128) // just a check that I don't receive random crap
{
Serial.write(input1); // send the data back to check
}
}
// short delay *here* if you absolutely must
}