5761Views7Replies

Author Options:

Arduino On/off button? Answered

Hey so I had a question.

Can somebody post some code of how to make an LED come on when you press a button and stay on, then once you press the button again it goes off and stays off until you press the button again?

Thanks!

7 Replies

user
steveastroukBest Answer (author)2013-04-01
Something like this
int mylight = LOW;
int whatever = 13;
int ledpin = 12;

voidsetup()
 {pinMode(ledpin,OUTPUT);
  pinMode (whatever,INPUT);
 }
  
voidloop()
{
while(digitalRead(whatever)==LOW);  //do nothing until button pressedif (digitalRead(whatever)==HIGH) mylight=!mylight;
while (digitalRead(whatever)==HIGH);
digitalWrite(ledpin,mylight);
}

Select as Best AnswerUndo Best Answer

user
HavocRC (author)steveastrouk2013-04-01

Two questions :D

What does "mylight=!mylight mean? I know that "!" means (not).

How did you past the code in there with color and a different font??

Thanks!

Select as Best AnswerUndo Best Answer

user
matti.virta.1 (author)2016-01-20

i test that last code and working, but how i change output pwm ? i think analogWrite pin A5 pwm,25

and how adding button / or bush second time pwm change to 255 and plink ?

Select as Best AnswerUndo Best Answer

user
steveastrouk (author)2013-04-01

Assign the new value of mylight to NOT the value currently in mylight.

If mylight = false, then mylight=!mylight leaves mylight with true in it - so it toggles from on to off.

Copy as HTML from Arduino, Rich editor, source view, and paste in Instructables.

Select as Best AnswerUndo Best Answer

user
HavocRC (author)steveastrouk2013-04-01
/* Thank you steve for all your help!! */

Select as Best AnswerUndo Best Answer

user
steveastrouk (author)HavocRC2013-04-01

Brilliant ! What a great way of sending a reply ;-)
Its a really good way of posting code.

Steve

Select as Best AnswerUndo Best Answer