Go Down

Topic: How to toggle led (Read 284 times) previous topic - next topic

ap16

I want to toggle 1 led. When button is pressed led comes on and when pressed again goes off.

Grumpy_Mike

That will be a state change then. Look in the IDE under File-> Examples -> 02 Digital -> StateChangeDetection

ap16

is there a way to do it without buttonpushcounter

larryd

Did your try?  StateChangeDetection
No technical PMs.
The last thing you did is where you should start looking.

3Dgeo

Here you go (connect button to PIN2 and ground):
Code: [Select]

const int buttonPin = 2;    //  button is connected to pin

bool buttonState = 0;       // variable to hold the button state
bool Mode = 0;              // What mode is the light in?


void setup()
{
  pinMode(buttonPin, INPUT_PULLUP);    // Set the switch pin as input
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  if (!digitalRead(buttonPin)) // cheks if button is pressed (cheks if it's LOW, becouse PULLUP inverts signal: LOW = button pressed)
  {
    if (!buttonState) // same as: (buttonState == false) ---I made it a bit compact, but it may be confusinf to you
    {
      buttonState = true;
      Mode = !Mode; // this inverts button mode: If Mode was True - it will make it False and viseversa
    }
  }
  else buttonState = false;

  // blink LED
  digitalWrite(LED_BUILTIN, Mode); // remember: TRUE = HIGH = 1 and FALSE = LOW = 0 (You can use whatever You like)
  delay(5);
}

Wawa

#5
Feb 14, 2018, 04:05 am Last Edit: Feb 14, 2018, 04:07 am by Wawa
Shorter version.
Leo..
Code: [Select]
const byte buttonPin = 2; // button between pin2 and ground

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  if (!digitalRead(buttonPin)) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    delay(500);
  }
}

Grumpy_Mike

is there a way to do it without buttonpushcounter
You need to know what the last state produced by the button to know what the next state should be. So how ever you dress it up you have to count the presesses up to a maximum of two.

What does that question really mean? Does it mean you can't understand the example and you think we deliberately want to make things complex?

Go Up