Press and hold a button for 2 seconds and it flashes

At the time of pressing a button for a second it would turn on, pressing it for 2 seconds I blinked, and for 3 seconds it would turn off, I managed to make it turn on and off but can't make it blink so I thought is to make a loop, but I don't know how.
Here is what I did:

int button1 =2;
int LED = 4;
bool statebutton1;
unsigned long time;
unsigned long time2;
unsigned long time3;

void setup(){
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(LED, OUTPUT);
}

void loop() {
statebutton1 = digitalRead(button1);
if(stateboton1 == HIGH) {
time=millis();
while(estadoboton1 == HIGH) {
time2=millis();
stateboton1= digitalRead(button1);

}
time3=time2-time;

Serial.println(time3);
if((time3)>=1000){
Serial.println("on");
digitalWrite(LED, HIGH);
}
if((time3)>=2000){
Serial.println("Blinking");
digitalWrite(LED,HIGH);
delay(100);
digitalWrite(LED,LOW);
delay(100);
}
if((time3)>=3000){
Serial.println("Off");
digitalWrite(LED,LOW);
}
}
}

Translated with DeepL Translate: The world's most accurate translator (free version)

Hello
I guess the sketch needs a FSM for the differend stages and two timers at least.
Please post your sketch well formated and in code tags "</>"> to be found in this editor.

Moderator:
Please don´t cross post thread.
Spanish thread closed.

@kyonoc
A: The following Circuit (Fig-1) and Flow Chart (Fig-2) describe the hardware and behavior of your project.

sw1led1A
Figure-1:

sw1led1Flow
Figure-2:

B: the following sketch demonstrates how the LED (connected at DPin-13, Fig-1) could be turned on when Button1 (connected at DPin-2, Fig-1) remains closed for 1-sec time. This is a "building block" with which you can add codes to realize other two functions.

#include <Debounce.h>
Debounce Button1(2);
byte LED = LED_BUILTIN;
bool flag = false;

void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop()
{
  chkButton1();
  timeDelay(1000);
  if (flag == false)
  {
    digitalWrite(LED, HIGH);
  }
  else
  {
    flag = false;
  }
}

void chkButton1()
{
  while (!Button1.read() != HIGH) {}
  while (!Button1.read() != LOW){}
}

void timeDelay(unsigned long t)
{
  unsigned long prMillis = millis();
  while (millis() - prMillis <= t)
  {
    if (!Button1.read() != LOW)
    {
      flag = true;
      break;
    }
  }
}

C: Please, clarify:
1. If Button1 remains closed for 1-sec, then LED will be turned on. Correct?

2. Now release the Button1 and close it again and if remains closed for 2-sec, then LED blinks for once. Correct? (What is the blinking interval? I mean on-period/off-period.)

3. Now release the Button1 and close it again and if remains closed for 3-sec, then LED will be turend off. Correct?

D: The following sketch performs the tasks of Step-C1 and Step-C2 above.

#include <Debounce.h>
Debounce Button1(2);
byte LED = LED_BUILTIN;
bool flag = false;
bool flag2 = false;
bool flag3 = false;

void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop()
{
  if (flag2 == false)
  {
    chkButton1();   //for Button1 close condition
    timeDelay(1000);
    if (flag == false) //button1 remained closed for 1-sec
    {
      digitalWrite(LED, HIGH);
      flag2 = true;  //next step to blink 
    }
    else
    {
      flag = false;
    }
  }
  else
  {
    chkButton1();
    timeDelay(2000);
    if(flag == false) //Button1 remained closed for 2-sec
    {
      digitalWrite(LED, LOW);
      delay(500);
      digitalWrite(LED, HIGH);
      delay(500);
      flag3 = true;  //next move LED is to be turned off
    }
    else
    {
      flag = false;
    }   
  }
}

void chkButton1()
{
  while (!Button1.read() != HIGH) {}
  while (!Button1.read() != LOW) {}
}

void timeDelay(unsigned long t)
{
  unsigned long prMillis = millis();
  while (millis() - prMillis <= t)
  {
    if (!Button1.read() != LOW)
    {
      flag = true;
      break;
    }
  }
}

E: Veteran programmers may guide us to transform the above non-object sketch into object oriented codes.

not sure how your button is wired because the code only does something when the pin is HIGH. conventionally, the pin is configured as INPUT_PULLUP and connected to ground thru the button. pressing the button pulls the the input LOW

don't see where estadoboton1 is defined how it would be set HIGH and how it would ever be be set not to HIGH in the while loops

        while(estadoboton1 == HIGH) {
            time2=millis();
            stateboton1= digitalRead(button1);
        }

considering above, how is time2 set?

in general, when testing for timed button presses, the code needs to capture when the button is pressed, if some max button press time has been exceeded while the button is pressed and when it is released before the max time occurs.

consider the following which compiles but is untested. i hope is demonstrates the above comment

int pinBut =2;
int pinLed = 4;

byte butLst;

unsigned long msec;
unsigned long time;
unsigned long ledTime;

// -----------------------------------------------------------------------------
#define BlinkPeriod 250
enum { Off = HIGH, On = LOW };

enum { LedOff, LedOn, LedBlink };
int ledState = LedOff;

void
led (void)
{
    switch (ledState) {
    case LedBlink:
        if ( (msec - ledTime) > BlinkPeriod)
            digitalWrite (pinLed, ! digitalRead (pinLed));
        break;

    case LedOn:
        digitalWrite (pinLed, On);
        break;

    case LedOff:
    default:
        digitalWrite (pinLed, Off);
        break;
    }
    
}

// -----------------------------------------------------------------------------
void loop () {
    msec = millis ();

    led ();

    byte but = digitalRead (pinBut);
    if (butLst != but)  {
        butLst = but;

        if (LOW == but)     // pressed
            time = msec;

        else  {             // button released
            if (time)  {    // 3000 not exceeded
                if ( (msec - time) > 2000)
                    ledState = LedBlink;
                else
                    ledState = LedOn;
                time = 0;
            }
        }
    }

    // turn LED off as soon as time > 3000 w/o waiting for button release
    if (time && (msec - time) > 3000)  {
        time = 0;
        ledState = LedOff;
    }
}

// -----------------------------------------------------------------------------
void setup (){
    Serial.begin (9600);
    pinMode (pinBut, INPUT_PULLUP);
    butLst = digitalRead (pinBut);
    pinMode (pinLed, OUTPUT);
}

@gcjr
I compiled and uploaded your sketch of Post-5 unto UNO but did not respond to the activation of pinBut of Fig-1. (When pinBut is pressed and kept pressed for more than 1-sec, ledPin still reamins turned off. The pinLed should turn on as per description of Post-1.)
sw1led1B

Figure-1:

My idea is that at the moment of pressing the button, it starts a timer that counts the time since it was pressed until it stops being pressed, everything was going well but I have a problem with the time conditions because the Arduino thinks that if I put a maximum value it will take all the values below it.
My conflict is that I do not know how to make a loop because I am new to this.

it does not find where it is defined(estadoboton1) is because I took a part of another person who made the code and as I only had the void loop part the rest I completed it as I thought it was.

Hello
The mother of all time handlers used inside the Arduino Biotop is based onto the IDE example "BlinkWithOutDelay".
This simple example can extentend to your needs simply.

the code i posted was untested (i was traveling).
i'm home and when i tested it, it turned the led on and off, but it did not blink.
i corrected the problem and now it turns the led on, off and blinks if held for more than 2 secs but less than 3 (count mississippi)

#undef MyHW
#ifdef MyHW
int pinBut = A1;
int pinLed = 13;

#else
int pinBut =2;
int pinLed = 4;
#endif

byte butLst;

unsigned long msec;
unsigned long time;
unsigned long ledTime;

// -----------------------------------------------------------------------------
#define BlinkPeriod 250
enum { Off = HIGH, On = LOW };

enum { LedOff, LedOn, LedBlink };
int ledState = LedOff;

void
led (void)
{
    switch (ledState) {
    case LedBlink:
        if ( (msec - ledTime) > BlinkPeriod)  {
            ledTime = msec;
            digitalWrite (pinLed, ! digitalRead (pinLed));
        }
        break;

    case LedOn:
        digitalWrite (pinLed, On);
        break;

    case LedOff:
    default:
        digitalWrite (pinLed, Off);
        break;
    }
    
}

// -----------------------------------------------------------------------------
void loop () {
    msec = millis ();

    led ();

    byte but = digitalRead (pinBut);
    if (butLst != but)  {
        butLst = but;

        if (LOW == but)     // pressed
            time = msec;

        else  {             // button released
            if (time)  {    // 3000 not exceeded
                if ( (msec - time) > 2000)  {
                    ledState = LedBlink;
                    Serial.println ("led blink");
                }
                else  {
                    ledState = LedOn;
                    Serial.println ("led On");
                }
                time = 0;
            }
        }
    }

    // turn LED off as soon as time > 3000 w/o waiting for button release
    if (time && (msec - time) > 3000)  {
        time = 0;
        ledState = LedOff;
        Serial.println ("led Off");
    }
}

// -----------------------------------------------------------------------------
void setup (){
    Serial.begin (9600);
    pinMode (pinBut, INPUT_PULLUP);
    butLst = digitalRead (pinBut);
    pinMode (pinLed, OUTPUT);
}

I uploaded your revised sketch of Post-10 in my UNO with Button at DPin-2 and LED at DPin-4. After uploading, LED becomes turned on and the CP (Control Program) does not respond to Button press. What Arduino are you using?

i'm using an Uno and testing with a multifunction board where LEDs are on when pulled LOW and buttons are connected between the pin and ground

serial prints should indicate how the button press is interpreted.

led On
led Off
led On
led On
led blink
led On
led On

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