Is there a way to define a variable in setup() and use it in loop()?

I am using a gas sensor and want to get a value during the setup function and use it throughout the loop function as a constant, without having to repeatedly get the same value. So, it would be something like the below :

void setup() {
    pinMode(1, INPUT);
    int constant = analogRead(1);
}

void loop() {
    int changing = analogRead(1); //This will be a different value than the constant
    int ratio = changing / constant; //I should be able to access the constant variable here
}

Currently, this does not compile and i understand the scope of the variables, but is there a way I can use the value of the "constant" variable in loop()? Would it be something like putting const int constant = analogRead(1); in loop()? Any help would be much appreciated!

1 Like

So, make constant global, set it in setup() and refrain from any further assignment to it.

What are you hoping to accomplish that the above would not?

a7

int constant; 

void setup() {
    pinMode(1, INPUT);
    constant = analogRead(1);
}

void loop() {
    int changing = analogRead(1); //This will be a different value than the constant
    int ratio = changing / constant; //I should be able to access the constant variable here
}

I’m not sure that you do… go read about the scope of variables.

If I understand you correctly, this will work

void loop()
{
   // Constant will be initialized to the value of analogRead(1) the first time loop
   // runs and will hold that value forever
   static int constant = analogRead(1);

}

Nice trick.

When is the call to analogRead() made?

Answer: "The static variable is initialized the first time execution hits its declaration."

If you don't know… now you know.

a7

if you are creating a reference level, you should sample once and discard one value, then take a few values and average them.

I've removed the unhelpful and possibly misleading posts about 'the float command'. Also removed the associated replies. I hope that what remains is useful to @xxrw

2 Likes

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