I am using QtSerialPort to send and receive data from Arduino. I am sending more than 64 bytes (125, 220, more), I receive the data with Arduino, and trying to sending back the same data, but Arduino sending only 64 bytes in its response. Then I am thinking that the problem is with Arduino buffer. I am trying to clear the data but without result.
Here is my Arduino code:
void loop() {
if (Serial.available() > 0) {
int i = 0;
delay(500);
int size = Serial.available();
while (i < size)
buffer[i++] = Serial.read();
Serial.print(buffer);
//delay(500);
int j = 0;
while (j < size)
buffer[j++] = '0円';
//while (Serial.available()) Serial.read(); I tried it
//Serial.flush(); Also tried it, but nothing.
}
}
1 Answer 1
Instead of blocking the loop for 500 ms, you should be actively
reading the data as it comes. Otherwise the internal buffer of the
Serial
object will overflow after only 64 bytes are received.
Here is an example that copies the incoming bytes into a larger buffer (256 bytes) and, upon receiving an end-of-line character, echoes back the whole line.
void loop() {
static char buffer[256];
static size_t pos; // position of next write
while (Serial.available() && pos < sizeof buffer - 1) {
// Read incoming byte.
char c = Serial.read();
buffer[pos++] = c;
// Echo received message.
if (c == '\n') { // \n means "end of message"
buffer[pos] = '0円'; // terminate the buffer
Serial.print(buffer); // send echo
pos = 0; // reset to start of buffer
}
}
}
-
after every read action the buffer consume one character and the buffer size is menor? So if I constantly send data to Arduino and constantly read from buffer, the buffer never going to be on overloaded?Robert– Robert2015年06月10日 16:40:04 +00:00Commented Jun 10, 2015 at 16:40
-
Did not really understand your question. There are two buffers: the one from the Serial object (64 bytes), and your application's buffer. Which one are you talking about? At 9600 bps, each byte takes about one millisecond, which is plenty. As long as
loop()
runs often enough (with nodelay()
), the Serial buffer is not going to overflow.Edgar Bonet– Edgar Bonet2015年06月10日 17:49:27 +00:00Commented Jun 10, 2015 at 17:49 -
The final result was receive each byte one by one and removed any delay in the code. Thank you @Edgar BonetRobert– Robert2015年06月18日 15:39:29 +00:00Commented Jun 18, 2015 at 15:39
delay(500)
: during this delay, you are letting the internal buffer ofSerial
overflow. Instead of just wasting 500 ms, you should be copying the incoming data into your ownbuffer
array as it comes.