I was trying to figure out approximately how long it takes to send data with my board via serial... and I found out something I do not manage to explain to myself. I used the following code :
long tini = 0;
int compt = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
// if(compt==0){
int value = 10100;
tini = micros();
// }
uint8_t b2send[5]={10100};
Serial.print("2000|2000|4333|4444|4844|nog|");
long tf = micros() - tini;
Serial.print("Time : ");
Serial.println(tf);
delay(10);
}
When I comment the delay(10) line I get around 50µs and with the line I get around 10µs???
(Also it crashes without the delay line but that I can understand )
Serial.print() is very fast when there is space left in the output buffer. Once the buffer is full, the Serial.print() has to wait for characters to leave the buffer before it can put more characters in.
Thanks for your answers, that brings me to a few questions :
Where can I find information on the buffer size? (So that I can optimize the size of what I send)
I tried Serial.flush() , if I understood correctly the Arduino Reference it is supposed to act as a delay waiting for the buffer to be free. So how come my board manages to crash even though the buffer should be free after each loop iteration??
Do you mean when you include Serial.flush() it should be empty?
Yes that's what I understood. As for my code I just replaced the delay(10) line with a Serial.flush(), the 'crash' is my way of saying the serial communication stops writing to the COM port after a random number of loop iterations.
long tini = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
tini = micros();
Serial.print("2000|2000|4333|4444|4844|nog|");
long tf = micros() - tini;
Serial.print("Time : ");
Serial.println(tf);
Serial.flush();
}
void loop() {
// put your main code here, to run repeatedly:
int value = 10100;
tini = micros();
Serial.print("2000|2000|4333|4444|4844|nog|");
Serial.flush();
long tf = micros() - tini;
Serial.print("Time : ");
Serial.println(tf);
//Serial.flush();
}
Or like that?
void loop() {
// put your main code here, to run repeatedly:
int value = 10100;
Serial.print("2000|2000|4333|4444|4844|nog|");
tini = micros();
Serial.flush();
long tf = micros() - tini;
Serial.print("Time : ");
Serial.println(tf);
//Serial.flush();
}
(it keeps crashing,for both codes I get that I should do around a 1000 iteration of the operation to be more accurate but since it crahes way before...)