Arduino Variables-please help ASAP

Hey,

I am working on a project and I need to declare a global variable within a function or scope whatever you would like to call it. Another way that I could do it is by writing the code inside the same loop function but i would need to pause the looping property of the function temporarily for a certain section in the code. the purpose I need this is to have the code run a calibration by taking all of the average of the sensor reads and setting a threshold +10 of the average.
Your help is much appreciated,
Thanks in advance,
-Jack Gabbay

int led = 8;
int volume;

void setup() {

Serial.begin(9600);
pinMode(led, OUTPUT);

int t1 = analogRead(A0);
delay(10);
int t2 = analogRead(A0);
delay(10);
int t3 = analogRead(A0);
delay(10);
int t4 = analogRead(A0);
delay(10);
int t5 = analogRead(A0);
delay(10);
int t6 = analogRead(A0);
delay(10);
int t7 = analogRead(A0);
delay(10);
int t8 = analogRead(A0);
delay(10);
int t9 = analogRead(A0);
delay(10);
int t10 = analogRead(A0);
delay(10);
int t11 = analogRead(A0);
delay(10);
int t12 = analogRead(A0);
delay(10);
int t13 = analogRead(A0);
delay(10);
int t14 = analogRead(A0);
delay(10);
int t15 = analogRead(A0);
delay(10);
int t16 = analogRead(A0);
delay(10);
int t17 = analogRead(A0);
delay(10);
int t18 = analogRead(A0);
delay(10);
int t19 = analogRead(A0);
delay(10);
int t20 = analogRead(A0);
delay(10);

int total = t1 + t2 + t3 + t4 + t5 + t6 + t6 + t7 + t8 + t9 + t10 + t11 + t12 +t13 + t14 + t15 + t16 + t17 + t18 + t19 + t20;
int average = total / 20;
int newTotal = average + 10;
int threshold = newTotal;

}
}
void loop() {

volume = analogRead(A0);

Serial.print(volume);
delay(10);
if(volume>threshold){
digitalWrite(led, HIGH);
}
else{
digitalWrite(led, LOW);

}

}

sketch_apr27a.ino (1.24 KB)

You should seriously learn about arrays. Anytime you find yourself putting numbers at the end of a bunch of variables, an array would save you time and effort.

If you want threshold to be global, then declare it up above the setup function at global scope.

int threshold;

void setup(){
    
    // all of your code to calculate threshold
    
    threshold = newTotal;   // Note there's no "int" on this line because the variable already exists.
}

That will make threshold visible from any function you write.

You don't even need arrays - a single int would suffice.

Please use code tags when posting code.

long total = 0;
void setup ()
  {
  for (int i = 0; i < 20; i++)
    {
    total += analogRead (A0);
    delay (10);
    }    
  // calculate average
  }

Doesn’t that look a lot easier?

Arduino Variables …

They aren’t Arduino variables, they are C++ variables. Any C++ tutorial will help you out.