The number of times loop()
runs every second depends on the time taken for the execution of the instructions within loop()
. For instance, in your code, the time taken for one loop()
is roughly equal to the time taken for the MCU to execute all the statements in loop()
(more specifically, the time taken for each operation or function from call to return): in your case, the time taken for the Serial.print()
s + the time taken for the analogRead()
s (not considering any interrupts between statements).
That said, you generally don't want to control the interval between loop()
s; I assume you actually want to control the interval between the execution of certain operations within your loop()
. Say, you want to set the time between executions of analogRead(0)
to 500 ms. This can be done like this:
#define INTERVAL 500 // time between reads
unsigned long lastRead = 0;
void setup(){
Serial.begin(9600); // setup serial
}
void loop(){
//....your other code....
if (millis() - lastRead >= INTERVAL){ // if INTERVAL has passed
val = analogRead(0);
lastRead = millis();
Serial.println(val);
//...anything else
}
//...your other code...
}
With this code, you now have about 2 analogRead
samples every second. Of course, this is only useful if loop()
runs faster than your chosen interval. If there are function calls, or any operations otherwise, in loop()
(within or outside the IF block) that always take more time than your interval, then this code would serve no purpose.
delay
at the end of theloop
.