Voting resources, early voting, and poll worker information - VOTE. ... Adafruit is open and shipping.
0

Confuzles to the maxmoozles (a matter of digital outputs)
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Confuzles to the maxmoozles (a matter of digital outputs)

by Old_Man_Robo on Wed Feb 26, 2020 2:00 pm

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 | TOGGLE FULL SIZE
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 | TOGGLE FULL SIZE
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?

Old_Man_Robo
 
Posts: 6
Joined: Wed Feb 26, 2020 1:57 pm

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

by adafruit_support_bill on Wed Feb 26, 2020 2:11 pm

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 | TOGGLE FULL SIZE
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);
}

adafruit_support_bill
 
Posts: 79109
Joined: Sat Feb 07, 2009 10:11 am

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

by Old_Man_Robo on Wed Feb 26, 2020 2:12 pm

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!

Old_Man_Robo
 
Posts: 6
Joined: Wed Feb 26, 2020 1:57 pm

Please be positive and constructive with your questions and comments.


cron