Hello guys.
I'm trying to work with the delay function, which I used to do without any problem, but now there seems to be some issue with the timing.
I have written a very simple example code to emphasize to problem I'm having:
int x=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
So afaik this code is supposed so count up and every 1000 is one second because: delay(ms), but actually, for example, it takes about 11 seconds for the counter to reach 2000...
The 9600 baud is very slow, I mean v-e-r-y s-l-o-w.
There is a buffer of 64 bytes for the outgoing data with Serial.println(). When that buffer is full, the sketch waits until there is a new free spot in that buffer. That can slow down the Arduino hundred times.
Thanks for the quick reply.
I have had the same results printed on an lcd screen, without even starting the monitor.
I think it means that it means that your solution in irrelevant? Thanks
So that's 11/2000 seconds per loop. Roughly 5.5 milliseconds. You are using 1 millisecond in delay() so you just have to figure out where the other 4.5 microseconds milliseconds are going. The "x++" shouldn't take long. My guess is that most of the time is spent in Serial.println(). Printing out "2000" and a Newline should take about 5 milliseconds at 9600.
I tried your sketch at 115200 baud and counting to 2000 took about 3 seconds.
The crystals of the LCD can not change very fast, you only need to update the display a few times per second. If you try to update the display 1000 times per second, then it will take some time, even with a normal LCD display without I2C.
For very fast clocks, 7-segment led displays are used.
delay will d-e-l-a-y your learning-process about advanced programming-techniques. Delay builds up a different picture about how programming works which you have to almost unlearn to understand how non-blocking timing based on the function millis() works.
Fortunately your democode is on the right way.
You are doing a very short delay() and use a counter.
The function millis() is an inbuild ready to use counter that is always counting in the backround.
These two videos explain non-blocking timing based on function millis()