LED Blink with button Press and LED stop glowing with Butoon press

here is code below

const int IN2 = 2;

int i;

int LedState = 0;

const byte LedPin12 = 12;



void setup()
 
{

      pinMode (IN2, INPUT_PULLUP);

      pinMode (LedPin12, OUTPUT);
      digitalWrite(LedPin12, LOW);

}


void loop() 

{


    if (digitalRead(IN2)==0)

    {
    LedState=!LedState;


    if(LedState)
    {

      for (i = 2; i <= 5 ; i++) 
    {
    digitalWrite(LedPin12, HIGH);
    delay(200);
    }
    for (i = 5; i >= 2 ; i--) 
    {
    digitalWrite(LedPin12, LOW);
    delay(200);
    }
      

    }

    

    else  if(!LedState)
    {
      digitalWrite(LedPin12, 0);
    }

      delay(200);

    }

}

I want LED at pin 12 starts blinking when I press the button at pin 2 , no matter if I hold down the button or not , I mean after releasing the button the LED will keep blinking

Then again if I push the button the LED will stop blinking and too will not glow (just OFF state)

This is just like a toggle action :-

When I switch ON the LED blinks

& when Switch OFF the LED goes OFF

I prepared the above code but the bilking action takes place if I

Press and Hold the button only

When I release the button it simply Turns OFF with no other actions

Please solve the issue in code

consider

const int IN2 = 2;
const byte LedPin12 = 12;
enum { Off = HIGH; On = LOW };

int i;
int LedState = 0;

byte butState;
bool run;

// -----------------------------------------------------------------------------
void setup ()
{
    pinMode (IN2, INPUT_PULLUP);
    butState = digitalRead (IN2);

    pinMode (LedPin12, OUTPUT);
    digitalWrite (LedPin12, Off);
}

// -----------------------------------------------------------------------------
void loop ()
{
    byte but = digitalRead (IN2);

    if (butState != but)  {
        butState = but;
        delay (20);     // debounce
        if (LOW == but) {
            run = ! run;
            if (false == run)
                digitalWrite (LedPin12, Off);
        }
    }

    // -------------------------------------
    if (run) {
        digitalWrite (LedPin12, !  digitalRead (LedPin12));
        delay (200);
    }
}

This time I post the a similar text: consider reading and learning
The behaviour is slightly different from your description
the change to blink or not to blink is only done when the button is released

/* explanation of the most important details:

  realising a functionality where using a momentary push-button
  acts as a toogle-switch
  push       => activated  push again => DE-activated
  push again => activated  push again => DE-activated
  etc. etc. ...
  This needs quite some code. This code is well organised in MULTIPLE functions
  where each function is a senseful SUB-program

  This is the reason why function loop looks super-short:

  void loop () {
  activationMode = GetToggleSwitchState(); // must be executed all the time
  execute_if_Active(activationMode);       // function that does what its name says
  }

  Huh that's all? No. Of course there is more (below function loop)

  If you just want to APPLY the functionality to your own code
  replace the code inside function    void my_Action()
  with your own code that shall only be  executed if you activated execution
  with the momentary push-button

  I recommend to RENAME the function my_Action() to a SELF-explaining name
  This will cause a compiler-error which shows you where you have to rename
  the function-call of this function too (this is inside function execute_if_Active
  If you want to understand how it works read and analyse the rest of the functions.

*/


#define ProjectName "Toggle Button demonstration"

// define IO-states for inputs with pull-up-resistors
// pull-up-resistors invert the logig
#define unPressed HIGH
#define pressed   LOW

const byte ToggleButtonPin = A0;

bool activationMode = false;
unsigned long myCounter = 0;
unsigned long MyBlinkTimer = 0;


void setup() {
  Serial.begin(115200); // adjust baudrate in the serial monitor to match the number
  Serial.println( F("Setup-Start") );
  printFileNameDateTime();

  pinMode (LED_BUILTIN, OUTPUT);  // used for indicating logging active or not
  digitalWrite(LED_BUILTIN, LOW);
  // wire button between IO-pin and GND
  // Pull-up-resistor inverts the logic
  // unpressed: IO-pin detects HIGH
  // pressed:   IO-Pin detects LOW
  pinMode(ToggleButtonPin, INPUT_PULLUP);
  MyBlinkTimer = millis();
}



// this is the function that is called
// inside function execute_if_Active()
void my_Action() {

  if ( TimePeriodIsOver(MyBlinkTimer, 500) ) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN) ); // read state of LED-output and set to invertetd state
  }
}


void loop () {
  activationMode = GetToggleSwitchState(); // must be executed all the time
  execute_if_Active(activationMode);       // function that does what its name says
}


bool GetToggleSwitchState() {
  // "static" makes variables persistant over function calls
  static bool toggleState     = false;
  static bool lastToggleState = false;

  static byte buttonStateOld = unPressed;
  static unsigned long buttonScanStarted  =  0;
  unsigned long buttonDebounceTime = 50;
  static unsigned long buttonDebounceTimer;

  byte buttonStateNew;

  if ( TimePeriodIsOver(buttonDebounceTimer, buttonDebounceTime) ) {
    // if more time than buttonDebounceTime has passed by
    // this means let pass by some time until
    // bouncing of the button is over
    buttonStateNew = digitalRead(ToggleButtonPin);

    if (buttonStateNew != buttonStateOld) {
      // if button-state has changed
      buttonStateOld = buttonStateNew;
      if (buttonStateNew == unPressed) {
        // if button is released
        toggleState = !toggleState; // toggle state-variable
      } // the attention-mark is the NOT operator
    }   // which simply inverts the boolean state
  }     // !true  = false   NOT true  is false
  //       !false = true    NOT false is true
  return toggleState;
}


void execute_if_Active(bool p_IsActivated) {
  printActionState(p_IsActivated);   // for demonstration purposes only

  if (p_IsActivated) {
    my_Action();
  }
}


// helper-function ignore at first
void printFileNameDateTime() {
  Serial.print( F("File   : ") );
  Serial.println( F(__FILE__) );
  Serial.print( F("Date   : ") );
  Serial.println( F(__DATE__) );
  Serial.print( F("Project: ") );
  Serial.println( F(ProjectName) );
}

// ignore at first
// helper-function for easy to use non-blocking timing
boolean TimePeriodIsOver (unsigned long &expireTime, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - expireTime >= TimePeriod ) {
    expireTime = currentMillis; // set new expireTime
    return true;                // more time than TimePeriod) has elapsed since last time if-condition was true
  }
  else return false;            // not expired
}

void printActionState(boolean p_IsActivated) {
  static boolean lastIsActivated;
  
  if ( p_IsActivated != lastIsActivated) {
    // only if state of parameter p_logIsActivated has changed
    if (p_IsActivated) {
      Serial.println();
      Serial.println("start executing");
      Serial.println();
      digitalWrite(LED_BUILTIN, HIGH);
    }
    else { // not activated
      Serial.println();
      Serial.println("stopp executing");
      Serial.println();
      digitalWrite(LED_BUILTIN, LOW);
    }
    lastIsActivated = p_IsActivated; // update variable lastSDlogActive
  }  
}

best regards Stefan

Woww Sir Thanks . .

I ll have to check this !!

Ya Sir this one is working
Great one !!!

Thanks !!

Please check this Thread as I am unable to solve it !!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.