Instructables

Arduino On/off button?

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!

Something like this


int mylight = LOW;
int whatever = 13;
int ledpin = 12;

void setup()
 {pinMode(ledpin,OUTPUT);
  pinMode (whatever,INPUT);
 }
  
void loop()
{
while(digitalRead(whatever)==LOW);  //do nothing until button pressed
if (digitalRead(whatever)==HIGH) mylight=!mylight;
while (digitalRead(whatever)==HIGH);
digitalWrite(ledpin,mylight);
}

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!
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.
/* Thank you steve for all your help!! */

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

Steve
:D
Pro

Get More Out of Instructables

Already have an Account?

close

PDF Downloads
As a Pro member, you will gain access to download any Instructable in the PDF format. You also have the ability to customize your PDF download.

Upgrade to Pro today!