For-loop not exiting at condition

Hello guys,
I am currently working on my bachelor thesis and as a preperation for that I followed a simple guide on YT on how to meassure the max frequency the controller can process. That includes a for-loop that counts to 1000000 (1 million) and meassures the time it took.
The weird behavior is: If I set the loop-limit to round about 30000 everything works like intended, but going higher for like 40000 and more, the loop is not exiting anymore. Does anyone know why this is happening?

Here is the code:

const int audioInPin = 0;

int analogValue;
unsigned long newTime;

void setup() {
  Serial.begin(115200);
}

void loop() {
  newTime = micros();

  for (int i = 0; i < 100000; i++) {
    analogValue = analogRead(audioInPin);
    Serial.println(i);
  }

  float conversionTime = (micros() - newTime) / 100000.0;

  Serial.print("Conversion time: ");
  Serial.print(conversionTime);
  Serial.println(" uS");
  
  Serial.print("Max sampling frequency: ");
  Serial.print((1.0 / conversionTime) * 100000);
  Serial.println(" Hz");
}

The calculations after the for-loop can be ignored so far. Those are not part of the problem. It is just the for-loop. I don't know why at some certain point, it doesn't stop looping.

Kind regards,
Aprikosengelee

Welcome to the forum

What is the largest value that an int can hold on the Arduino board that you are using ?

This is significant in forming your answer

I just checked, and it would fit the problem. I am using the Arduino Uno R3 which can process 16 bit values, so the max int would be round about 32k.

The solution is to use a variable type that can hold the value required. A further suggestion would be to use an unsigned variable so that the max value could be twice that of a signed variable

Ich changed the code to that:

const int audioInPin = 0;

int analogValue;
unsigned long newTime;

void setup() {
  Serial.begin(115200);
}

void loop() {
  //Serial.println("Starting...");
  newTime = micros();

  //Do 1 million reads and record time taken
  for (float i = 0; i < 1000000.0; i++) {
    analogValue = analogRead(audioInPin);
  }

  float conversionTime = (micros() - newTime) / 1000000.0;

  Serial.print("Conversion time: ");
  Serial.print(conversionTime);
  Serial.println(" uS");
  
  Serial.print("Max sampling frequency: ");
  Serial.print((1.0 / conversionTime) * 1000000.0);
  Serial.println(" Hz");
}

now it works. No unsigned needed in that case, maybe not even the float, guess the long would do the trick as well. Thanks so much for the quick response.

float will work but is the wrong choice. An unsigned long would be better

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.