Problem creating a function for an on/off button

Hello guys,

I'm trying to create a function that turns on a led when I press a button, and turns it off when I press the button again, but I'm having some trouble.
When I use this code, it works perfectly:

int led = 54;
int button = 7;
int state= 0;
int last_state = 0;
int out=0;
void setup(){
* pinMode(led,OUTPUT);*
* pinMode(button, INPUT_PULLUP);
__
digitalWrite(led,LOW);__
__
}*__
void loop(){

* state=digitalRead(button);*
* if ( state==0 && last_state==0)
__
{ __
__
out=1-out;__
__
delay(20); __
__
}__
last_state=1-state;
__
if( out==1)__
__
{__
__
digitalWrite(led, HIGH); // led on*__
* }*
* else{*
* digitalWrite(led,LOW); // led off*
* }*
}

But when I try to create a function and use this code:

void on_off(int states,int last_st,int outs,int leds,int buttons){

* states=digitalRead(buttons);*
* if ( states==0 && last_st==0)
__
{ __
__
outs=1-outs;__
__
delay(20); __
__
}__
last_st=1-states;
__
if( outs==1)__
__
{__
__
digitalWrite(leds, HIGH); // led off*__
* }*
* else{*
* digitalWrite(leds,LOW); // led on*
* } }*

int led = 54;
int button = 7;
int state= 0;
int last_state = 0;
int out=0;
void setup(){
* pinMode(led,OUTPUT);*
* pinMode(button, INPUT_PULLUP);
__
digitalWrite(led,LOW);__
__
}*__
void loop(){

* on_off(state,last_state,out,led,button);
__
}*__

It just doesn't work, the led stays on just when I keep the button pressed, when I let it go, it turns off.
Can anybody help me please? :smiley:

Your passing the params by VALUE not location (pointer) so state/last_state are not up dated.

Mark

You have a global variable called last_state.

When you call your function on_off from your loop you pass this as a parameter.

Now within your on_off function you have a copy of the global variable. So effectively your on_off function has a LOCAL variable named last_state that is totally independent of the global one.

Any changes you make to this local variable will be lost as soon as the on_off function completes.

Therefore the next time your loop calls on_off, you will find that it hasn't been changed.

Edit: Agh, Holmes beat me to it!

What you could do is stop sending the parameters and instead, let your on_off function find the global variables instead.