timer if pushbutton High

Hi,

I try to get duration of pushing button, do you have a simple good idea?, or pls help me to fix one of those:

**using StopWatch.h

if (push == HIGH  && noPush==LOW) {         // check if the input is HIGH (button released)

if (act[1]==0){ s ++}                                          // increment S by 1 and only 1

MySW.start();                                                    // Start Timer

MySW.isRunning();

}else{MySW.stop(); MySW.reset();}

 
noPush = push;

Serial.print(MySW.elapsed());

** Or using Set Millis

void setMillis(unsigned long new_millis){
  uint8_t oldSREG = SREG;
  cli();
  timer0_millis = new_millis;
  SREG = oldSREG;
}
setMillis(0);

if (push == HIGH  && noPush==LOW) {         // check if the input is HIGH (button released)

if (act[1]==0){ s ++}                                          // increment S by 1 and only 1

                                              
time = millis();

}else{elapsedtime = millis()- time; }

 
noPush = push;

Serial.print(elapsedtime);

Thanks

I try to get duration of pushing button, do you have a simple good idea?

Save the time when the button becomes pressed. Save the time when the button becomes released. Subtract one from the other.

const byte buttonPin = A1;
unsigned long buttonPressedTime = 0;
unsigned long buttonReleasedTime = 0;
byte currentButtonState = HIGH;
byte previousButtonState = HIGH;

void setup()
{
  Serial.begin(115200);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
  currentButtonState = digitalRead(buttonPin);
  if (currentButtonState != previousButtonState)
  {
    if (currentButtonState == LOW)  //button has become pressed
    {
      buttonPressedTime = millis();
      Serial.println("The button is pressed");
    }
    else
    {
      buttonReleasedTime = millis();
      Serial.print("Button was pressed for ");
      Serial.print(buttonReleasedTime - buttonPressedTime);
      Serial.println(" milliseconds\n");
    }
  }
  previousButtonState = currentButtonState;
}

NOTE : you will need to change the logic of the test to match your wiring.

Hi,

Thanks,
I will try this.

Thanks

I changed it to

if (push ==LOW){
buttonPressedTime = millis()/1000;
}else
if (push == HIGH){
buttonReleasedTime = millis()/1000;
time = buttonReleasedTime - buttonPressedTime;
if (push == HIGH && noPush==LOW) {         // check if the input is HIGH (button released)
if (act[1]==0){ s ++; rcount++;}

}

It works well

As you did not post your whole program it is impossible to see what you are doing. One small comment.

if (push ==LOW){
buttonPressedTime = millis()/1000;
}else
if (push == HIGH){

Presumably push is the result of a digitalRead(). If so it can only be HIGH or LOW so in the code above you do not need the second if because if push is not LOW then it must be HIGH

Hi

Thanks it work now.

I have to get duration every time a push button is pressed and send it to phone through bluetooth.

Thanks for your help