Using a physical switch to chnange global variable

I've attempted to change the value of the global variable via a physical switch but no success. Is this possible? Or is there a more efficient way ??? Thanks in advance.

int batt = 3;
int firstswitch = 7;

void setup() {
  if ( digitalRead(firstswitch) == LOW)
  {
    batt = 3.5;
  }

}

void loop() {
  // put your main code here, to run repeatedly:

}

int = integer. 3.5 is not an integer.

Steve

I see your point. What if I change the 3.5 to 4

int batt = 3;
int firstswitch = 7;

void setup() {
  if ( digitalRead(firstswitch) == LOW)
  {
    batt = 4;
  }

}

void loop() {
  // put your main code here, to run repeatedly:

}

Looks fine to me though you'll need the switch to be connected correctly with a pull-up resistor, since you haven't used pinMode INPUT_PULLUP. What happens when you try it?

Steve

Strangely it's working now but it wouldn't compile before. But I'm glad that it does.

I added the pinmode.

Will the two variables conflict when the switch is flipped or does the new definition override the original global variable?

This statement stores (assigns) a value into a variable.

    batt = 4;

If "batt" is global, defined outside of a function, any function can make the assignment.

Just make sure not to confuse local variables (defined only within functions or blocks) with global variables.

Example of (possibly) confusing local versus global variables (try it).

int batt=3; //declare and initialize global batt

void setup() {
Serial.begin(9600);
int batt = 4; //declare and initialize local variable batt
Serial.print("Setup: batt= ");
Serial.println(batt);
}

void loop() {
Serial.print("loop: batt= ");
Serial.println(batt);
while(1); //hang here
}

ArdUser14:
Will the two variables conflict when the switch is flipped or does the new definition override the original global variable?

Because it is defined globally there is only one VARIABLE batt. What you have done is changed the VALUE of that variable. Anything that uses it after that change sees the new value.

Steve

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.