Hi can anybody enlighten me as to why the led is not staying on after the pushbutton is pressed? Its driving me nuts! I have created a function because there will be 13 leds, Thankyou!!!! It's actually working without the function
ok you lost me there, sorry but i am very new, i just don't understand why the same code works when it's not put into a function
const int LED = 15;
const int BUTTON = 2;
int val = 0;
int old_val = 0;
int state = 1;
void setup () {
pinMode(LED,OUTPUT);
pinMode(BUTTON, INPUT_PULLUP);
}
void loop (){
val = digitalRead(BUTTON);
if( val == HIGH && old_val == LOW) {
state = 1-state;
delay (10);
}
old_val = val;
if ( state == 1)
digitalWrite(LED,HIGH);
else
digitalWrite(LED, LOW);
}
It works when the code is in loop() because the changes to state affect the global variable named state, not the function argument named state. I told you that changes made in the function are lost, but you seem to have ignored that.
Google pass-by-reference and pass-by-value to understand passing data to functions.
PaulS:
It works when the code is in loop() because the changes to state affect the global variable named state, not the function argument named state. I told you that changes made in the function are lost, but you seem to have ignored that.
Google pass-by-reference and pass-by-value to understand passing data to functions.
Sorry if it seems that i ignored you but i didn't, i tried making the variables global and that still didn't work, I'm trying me best to understand i've been programming a few days actually but anyway thanks for the info. I will look into it
You are using pass-by-value now. The call has no variables that contain values, so pass-by-value must be used.
If you changed the function call to use the global variables, nothing would change, because the value in the variable is passed, not the address of the variable.
Pass-by-reference passes the address of the variable, so that changes made to the variables are known to the caller (for the next call).
You use type &name, instead of type name, in the function declaration/implementation to use pass-by-reference. You can't (meaningfully) then use constants in the call.
But, with global variables that you want o modify, the function really doesn't need to take any arguments. Let it operate on/with the global variables.
Of course, when you start making multiple calls, wanting to operate on different pins, etc., that will be a problem.