Confuzles to the maxmoozles (a matter of digital outputs)

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
Old_Man_Robo
 
Posts: 9
Joined: Wed Feb 26, 2020 1:57 pm

Confuzles to the maxmoozles (a matter of digital outputs)

Post by Old_Man_Robo »

Hello, folks.
I'm having a syntax issue that I don't quite understand. I have two pieces of code: one works and one doesn't. I can't figure out why.

The first piece of code, which is how I originally wrote it, is as follows:

Code: Select all

void setup() {
  // put your setup code here, to run once:
  int relay1=2;
  pinMode(relay1, OUTPUT);
  digitalWrite(relay1, HIGH);
}

void loop() {
delay(1000);
digitalWrite(relay1, LOW);
delay(1000);
digitalWrite(relay1, HIGH);
}
When I try to verify this, it highlights the digitalWrite in the loop section and says relay1 has not been declared.

So, I changed the code to this:

Code: Select all

void setup() {
  // put your setup code here, to run once:
  int relay1=2;
  pinMode(relay1, OUTPUT);
  digitalWrite(relay1, HIGH);
}

void loop() {
delay(1000);
digitalWrite(2, LOW);
delay(1000);
digitalWrite(2, HIGH);
}

This code verified and worked fine. Can someone explain to me why the first code didn't work but the second code will?

User avatar
adafruit_support_bill
 
Posts: 88096
Joined: Sat Feb 07, 2009 10:11 am

Re: Confuzles to the maxmoozles (a matter of digital outputs

Post by adafruit_support_bill »

Because "relay1" is defined inside the scope of your setup() function. It is not recognized outside of that scope.

If you want relay1 to be recognized everywhere, you need to define it at a global scope:

Code: Select all

int relay1=2;

void setup() 
{
	// put your setup code here, to run once:
	pinMode(relay1, OUTPUT);
	digitalWrite(relay1, HIGH);
}

void loop() 
{
	delay(1000);
	digitalWrite(relay1, LOW);
	delay(1000);
	digitalWrite(relay1, HIGH);
}

User avatar
Old_Man_Robo
 
Posts: 9
Joined: Wed Feb 26, 2020 1:57 pm

Re: Confuzles to the maxmoozles (a matter of digital outputs

Post by Old_Man_Robo »

Oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooh!
It's been a while since I've done any programming in this, and I was thinking that the Setup WAS the global scope. Awesome-sauce. Thank you!

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”