-1

I did this little experiment to count the number of cycles per second in two different configurations:

1-The variable a is initialized at zero and incremented by one each cycle of the loop. -The value of a is written each cycle -at millis() = 1000, the incrementation ends, and the value of millis() is written to check the precision of timing.

Code:

long a = 0;
int v = 1; 

void setup() {

Serial.begin(9600);

}

void loop() {

if (v == 1){
a = a + 1 ;

Serial.println(a);

if (millis() >= 1000){
Serial.println(millis());
v = 0;}

}
}

Result: 1 2 . . . 227 1000

2-Same as 1, but the value of a is written only at the end.

Code:

long a = 0;
int v = 1; 

void setup() {

Serial.begin(9600);

}

void loop() {

if (v == 1){
a = a + 1 ;



if (millis() >= 1000){
Serial.println(millis());
Serial.println(a);
v = 0;}

}
}

Result:

1000 265174

-So, 227 cycles for 1, and 265174 for 2, is this correct, and can such a simple modification slow the cycling by 1000?

  • 2
    Serial.print() takes a lot of time, so result is correct. – Matej Feb 7 at 16:12
2

Writing via the serial interface takes a lot of time (just consider the baud rate you selected). You should always keep in mind that changing the amount you are printing might change your programs behaviour. That means, your 2. configuration is (more) reliable.

1

When the serial buffer (64 bytes) is full the print waits until bytes are send away at 9600 baud.

0

You could use micros() as well to increase resulution to 4uS, vs 1000uS. Up the speed to 115200, that should show some improvement as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.