I have the following code which checks the latency of another board.
int triggerPin = 13;
int dataPin = 9;
int ejectorPin = A0;
unsigned long t_start = 0;
unsigned long t_end = 0;
unsigned long t_total = 0;
int value = 0;
void setup() {
// put your setup code here, to run once:
pinMode(triggerPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(ejectorPin, INPUT);
Serial.begin(9600);
}
void loop() {
t_start = micros();
while (value < 10 ) {
digitalWrite(triggerPin, HIGH);
digitalWrite(dataPin, HIGH);
delay(5.0);
digitalWrite(dataPin, LOW);
digitalWrite(triggerPin, LOW);
delay(1.0);
value = analogRead(ejectorPin);
}
t_end = micros();
t_total = (t_end - t_start);
Serial.println(double(t_total) / 1000);
Note that I'm using analogRead()
inside the while loop. With this method I get 18.3 msec. However, if I use the analogRead()
in the while condition:
void loop() {
t_start = micros();
while (analogRead() < 10 ) {
.
.
.
then I get 30.2 msec. I thought assigning value of analogRead()
to a variable would take longer but here it's the opposite.
Can someone please explain the reason behind this behaviour?
-
2What voltage are you supplying to A0? Is it consistent between runs of the program? How consistent are the printed values across loop iterations?Edgar Bonet– Edgar Bonet2022年01月05日 09:10:35 +00:00Commented Jan 5, 2022 at 9:10
-
2Your delays will be completely hiding any variance in the analog read timing. Your supposed results are meaningless to us.Majenko– Majenko2022年01月05日 11:09:49 +00:00Commented Jan 5, 2022 at 11:09
-
@EdgarBonet As far I can tell the both the input voltage and the printed values are pretty consistent.Farahi– Farahi2022年01月05日 11:40:48 +00:00Commented Jan 5, 2022 at 11:40
-
2@Farahi It won't be the analogRead. It'll be whatever is "triggering" the analogRead. The analogRead is insignificant in the scale of things.Majenko– Majenko2022年01月05日 12:08:26 +00:00Commented Jan 5, 2022 at 12:08
-
1@Majenko There's no need for passive aggressiveness. I'm new to all this so my questions may come across as dumb.Farahi– Farahi2022年01月05日 14:49:51 +00:00Commented Jan 5, 2022 at 14:49
1 Answer 1
Both of your examples use a while loop, so the while loop is not the issue.
An analogue read, with the prescalers unchanged, takes 104 μs. So, what you are really measuring is your 6 ms delays, plus a slight amount extra for the other code.
Since your first while loop necessarily takes 6+ ms, then you will naturally get a result which is a multiple of 6 ms. This appears to be happening, so you are getting two loops (18 ms). This doesn't prove a huge amount.
You need to read up on the Nyquist frequency
To get accurate sampling results you need to sample at twice the rate at which things change. Your first results may merely be the results of aliasing. Your 6 ms delays may cause you to take one sample on one transition, and another sample (maybe) a couple of transitions later. Thus your results are meaningless.