1

If I declare a variable 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);
 }
}
ocrdu
1,7953 gold badges12 silver badges24 bronze badges
asked May 12, 2019 at 19:27
6
  • You need to select your code and tap the {} (code formatting) button. I did it for you. Commented May 12, 2019 at 19:29
  • 3
    Of course it's undeclared. The variable is in setup. It's not in loop. Commented May 12, 2019 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 Commented May 12, 2019 at 19:32
  • This is more a question about C/C++, not about Arduino Commented May 12, 2019 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. Commented May 12, 2019 at 19:35

1 Answer 1

7

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);
 }
}
Sim Son
1,87813 silver badges21 bronze badges
answered May 12, 2019 at 19:31
2
  • 2
    Surely servo1 should be global as well? Commented May 13, 2019 at 1:02
  • Yup, that too. I was in a bit of a hurry when I made that post. Commented May 15, 2019 at 0:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.