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);
}
}
1 Answer 1
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);
}
}
-
2Surely servo1 should be global as well?copper.hat– copper.hat05/13/2019 01:02:39Commented May 13, 2019 at 1:02
-
Yup, that too. I was in a bit of a hurry when I made that post.Duncan C– Duncan C05/15/2019 00:14:41Commented May 15, 2019 at 0:14
Explore related questions
See similar questions with these tags.
{}
(code formatting) button. I did it for you.