int inPin = 6; // pushbutton connected to digital pin 6
int switch_1 = 0; // global to hold switch state
void setup()
{
pinMode(inPin, INPUT ); // sets the digital pin 6 as input
}
void loop()
{
switch_1 = digitalRead(inPin); // read the input pin
}
seems like it takes a lot more space and does the same thing
Delta_G:
Do you mean using the pin number directly instead of having it in a variable? Sure, you can do that but if the project ever changes and you need to change the pin number you'll have to go through the entire code changing it every time it comes up.
If you are trying to save memory by not declaring a variable for that then use a #define. That gets replaced before the code gets compiled so it doesn't take up any space.
When I look at the state of a switch, I only have one line that looks at the switch and loads that into a global variable.
the global variable is used from that point on.
That is what has me puzzled.
It seems that (IMHO) one only looks at the actual pin once, typically at the very top of a scan, then loads that information into a variable.
It's still good practise to gather all of your pin assignments together at the top of the code, either using #define or const int declarations. You will find that those pin assignments change a lot more often than you think and if you used digitalRead(6) ANYWHERE in your code, it's not easy to find.
Not only what has been said - but also by defining them at the top, you can give them meaningful names which, as you read the code - make the code more "self-documenting" (which you will come back to the code - whether in an hour, or 10 years later).
ie - which of the following examples is more meaningful? First, example 1 (your original):
int inPin = 6; // pushbutton connected to digital pin 6
int switch_1 = 0; // global to hold switch state
void setup()
{
pinMode(inPin, INPUT ); // sets the digital pin 6 as input
}
void loop()
{
switch_1 = digitalRead(inPin); // read the input pin
}
or example 2 (I'm imagining it as a doorbell button here):
int doorbellInputPin = 6; // pushbutton connected to digital pin 6
int doorbellState = 0; // global to hold switch state
void setup()
{
pinMode(doorbellInputPin, INPUT);
}
void loop()
{
doorbellState = digitalRead(doorbellInputPin);
}
Note also that I removed some of your other comments; when you write code using descriptive variables, a lot of commenting can be superfluous and can be eliminated. When you comment, your comments should explain the "why" - not the "what" (as in most cases, the "what" is readily apparent by the code itself) - but only if explaining the "why" adds clarification to the process (note also that if your comments start to go over a few sentences - you may want to rethink and refactor your code).