1

if i declare a var in void setup() and try to do something with it in void loop(), it just says that the variable is undeclared. here is the code:

#include "Servo.h"

void setup() {
    Servo servo1;
    int x_key = A0;
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

    int x_position = 90;
}

void loop() { 
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}
  • You need to select your code and tap the {} (code formatting) button. I did it for you. – Duncan C May 12 at 19:29
  • 3
    Of course it's undeclared. The variable is in setup. It's not in loop. – Majenko May 12 at 19:30
  • 1
    Because the variable is only valid, where it is declared, to use the official term: it's scope. When the program moves out of the scope of this variable, it will get thrown away and be no longer available. You can declare it in global scope, meaning outside of any function – chrisl May 12 at 19:32
  • This is more a question about C/C++, not about Arduino – chrisl May 12 at 19:33
  • @chrisl true, but the OP doesn't know enough to know where to ask the question. We all have to start somewhere. I just wish people would do some self-study before running to the internet looking for somebody else to answer their questions for them. – Duncan C May 12 at 19:35
5

Yes, that is how C and C++ (and most other C-like languages) work. Variables have "scope". Any variable define inside a pair of curly braces (between a { and a }) is only visible inside those braces.

If you want to reference a variable in both setup() and loop(), you have to make it a global variable, defined at the top of your code.

#include "Servo.h"
Servo servo1;
int x_position = 90;  //Define your global var(s) here



void setup() {
    int x_key = A0;  //This var only exists inside the setup function
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

}

void loop() { 
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}
  • 2
    Surely servo1 should be global as well? – copper.hat May 13 at 1:02
  • Yup, that too. I was in a bit of a hurry when I made that post. – Duncan C May 15 at 0:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.