int firstAnalogPin = 0;
int secondAnalogPin = 5;
int firstVal = 0;
int secondVal = 0;
void setup(){
Serial.begin(9600); // setup serial
}
void loop(){
firstVal = analogRead(firstAnalogPin);
// read the input pin
secondVal = analogRead(secondAnalogPin);
// read the input pin
Serial.print(firstVal);
Serial.print("\t");
Serial.println(secondVal);
}
Basically, I want to know how to convert from the baud rate to the number of times loop()
runs per second. How do I control the number of loop()
s per second?
3 Answers 3
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.
If your goal is to control how often the sensor is polled and printed to SD card, I would suggest you check out Blink Without Delay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay it would be a much cleaner way than trying to slow down the loop to a specified time.
Marcello Romani's SimpleTimer library was made for this kind of problem. You let loop()
run as fast as possible but only maintain the timers and do other short tasks. The timer library runs your periodic tasks when necessary:
#include <SimpleTimer.h>
SimpleTimer timer; // creates a set of timers
// A timer call-back function - there can be more than one
void onTimer(void){
; // do stuff here, keep it short
}
void setup(void){
; // Serial.begin() and other setup
timer.setInterval(1000L, onTimer); // set a 1-sec repeating timer
}
void loop(void){
timer.run(); // updates timers, maybe calls a callback func
; // whatever other loop code
}
delay
at the end of theloop
.